file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
rpc_mock.py | from bitcoingraph.bitcoind import BitcoinProxy, BitcoindException
from pathlib import Path
import json
TEST_DATA_PATH = "tests/data"
class BitcoinProxyMock(BitcoinProxy):
def __init__(self, host=None, port=None):
super().__init__(host, port)
self.heights = {}
self.blocks = {}
... |
def getrawtransaction(self, tx_id, verbose=1):
if tx_id not in self.txs:
raise BitcoindException("Unknown transaction", tx_id)
else:
return self.txs[tx_id]
def getrawtransactions(self, tx_ids, verbose=1):
results = []
for tx_id in tx_ids:
re... | print("No info") | identifier_body |
rpc_mock.py | from bitcoingraph.bitcoind import BitcoinProxy, BitcoindException
from pathlib import Path
import json
TEST_DATA_PATH = "tests/data"
class BitcoinProxyMock(BitcoinProxy):
def __init__(self, host=None, port=None):
super().__init__(host, port)
self.heights = {}
self.blocks = {}
... | (self):
p = Path(TEST_DATA_PATH)
files = [x for x in p.iterdir()
if x.is_file() and x.name.endswith('json')]
for f in files:
if f.name.startswith("block"):
height = f.name[6:-5]
with f.open() as jf:
raw_block = json... | load_testdata | identifier_name |
rpc_mock.py | from bitcoingraph.bitcoind import BitcoinProxy, BitcoindException
from pathlib import Path
import json
TEST_DATA_PATH = "tests/data"
class BitcoinProxyMock(BitcoinProxy):
def __init__(self, host=None, port=None):
super().__init__(host, port)
self.heights = {}
self.blocks = {}
... | height = f.name[6:-5]
with f.open() as jf:
raw_block = json.load(jf)
block_hash = raw_block['hash']
self.heights[int(height)] = block_hash
self.blocks[block_hash] = raw_block
elif f.name.startswit... | for f in files:
if f.name.startswith("block"): | random_line_split |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... |
pub fn can_reset(body: &Body) -> bool {
match body.reader {
Kind::Bytes(_) => true,
Kind::Reader(..) => false,
}
}
| {
match body.reader {
Kind::Bytes(ref bytes) => {
let len = bytes.len();
::hyper::client::Body::BufBody(bytes, len)
}
Kind::Reader(ref mut reader, len_opt) => {
match len_opt {
Some(len) => ::hyper::client::Body::SizedBody(reader, len),
... | identifier_body |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... |
Kind::Bytes(ref mut bytes) => {
(&**bytes).read_to_string(&mut s)
}
}.map(|_| s)
}
enum Kind {
Reader(Box<Read + Send>, Option<u64>),
Bytes(Vec<u8>),
}
impl From<Vec<u8>> for Body {
#[inline]
fn from(v: Vec<u8>) -> Body {
Body {
reader: Kind::Bytes(... | {
reader.read_to_string(&mut s)
} | conditional_block |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(),
&Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(),
}
}
}
// Wraps a `std::io::Write`.
//pub struct Pipe(... | fmt | identifier_name |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... | }
}
}
impl fmt::Debug for Kind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(),
&Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(),
}
... | #[inline]
fn from(f: File) -> Body {
let len = f.metadata().map(|m| m.len()).ok();
Body {
reader: Kind::Reader(Box::new(f), len), | random_line_split |
go_thrift_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from pants.backend.codegen.thrift.lib.thrift import Thrift
from pant... | (self):
return self._thrift.select(context=self.context)
@property
def _thrift_version(self):
return self._thrift.version(context=self.context)
@memoized_property
def _thrift(self):
return Thrift.scoped_instance(self)
@memoized_property
def _deps(self):
thrift_import_target = self.get_opt... | _thrift_binary | identifier_name |
go_thrift_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from pants.backend.codegen.thrift.lib.thrift import Thrift
from pant... | from pants.util.dirutil import safe_mkdir
from pants.util.memo import memoized_method, memoized_property
from pants.util.process_handler import subprocess
from twitter.common.collections import OrderedSet
from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary
class GoThriftGen(Sim... | from pants.task.simple_codegen_task import SimpleCodegenTask | random_line_split |
go_thrift_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from pants.backend.codegen.thrift.lib.thrift import Thrift
from pant... |
SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)')
NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE)
def _declares_service(self, source):
with open(source) as thrift:
return any(line for line in thrift if self.SERVICE_PARSER.search(line))
def _get_go_namespace(self... | service_deps = self.get_options().get('service_deps')
return list(self.resolve_deps(service_deps)) if service_deps else self._deps | identifier_body |
go_thrift_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from pants.backend.codegen.thrift.lib.thrift import Thrift
from pant... |
gen_dir = os.path.join(target_workdir, 'gen-go')
src_dir = os.path.join(target_workdir, 'src')
safe_mkdir(src_dir)
go_dir = os.path.join(target_workdir, 'src', 'go')
os.rename(gen_dir, go_dir)
@classmethod
def product_types(cls):
return ['go']
def execute_codegen(self, target, target_w... | file_cmd = target_cmd + [os.path.join(get_buildroot(), source)]
with self.context.new_workunit(name=source,
labels=[WorkUnitLabel.TOOL],
cmd=' '.join(file_cmd)) as workunit:
result = subprocess.call(file_cmd,
... | conditional_block |
mod.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/. */
use document_loader::{DocumentLoader, LoadType};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::... | }
/// Corresponds to the latter part of the "Otherwise" branch of the 'An end
/// tag whose tag name is "script"' of
/// https://html.spec.whatwg.org/multipage/#parsing-main-incdata
///
/// This first moves everything from the script input to the beginning of
/// the network input, effectiv... | pub fn script_nesting_level(&self) -> usize {
self.script_nesting_level.get() | random_line_split |
mod.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/. */
use document_loader::{DocumentLoader, LoadType};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::... | {
Received,
NotReceived,
}
impl ServoParser {
pub fn parse_html_document(
document: &Document,
input: DOMString,
url: ServoUrl,
owner: Option<PipelineId>) {
let parser = ServoParser::new(
document,
owner,
Tokenizer... | LastChunkState | identifier_name |
socialMediaMetaTag.ts | module ngX.components {
ngX.Component({
module: "ngX.components",
selector: "social-media-meta-tag",
template: [
"<!-- Update your html tag to include the itemscope and itemtype attributes. --> ",
"<html itemscope itemtype='http://schema.org/Article'> ",
... | "<meta property='og:title' content='Title Here' /> ",
"<meta property='og:type' content='article' /> ",
"<meta property='og:url' content='http://www.example.com/' /> ",
"<meta property='og:image' content='http://example.com/image.jpg' /> ",
"<meta property='og... | "<!-- Open Graph data --> ", | random_line_split |
logger.ts | // import * as DailyRotateFile from 'winston-daily-rotate-file';
// import { NullTransport } from 'winston-null';
// import * as winston from 'winston';
// import * as fs from 'fs';
// import { workspace } from "vscode";
// const logFolder: string | undefined = workspace.getConfiguration("hg").get<string>("serverLogFo... | // ]
// }
// else {
// transports = [
// new NullTransport()
// ]
// }
// export const logger = new winston.Logger({ transports });
/* */ | // level: 'debug'
// }) | random_line_split |
imgsearch.py | import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-ba... |
def image_resize(imgfile,width):
imgquery = cv2.imread(imgfile)
r = width / imgquery.shape[1]
dim = (int(width), int(imgquery.shape[0] * r))
small = cv2.resize(imgquery,dim)
return small
host = 'localhost'
sname = 'imgserv'
description = 'image classification'
mllib = 'caffe'
mltype = 'unsupervis... | yield iterable[ndx:min(ndx + n, l)] | conditional_block |
imgsearch.py | import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-ba... | cv2.waitKey(0)
for n in near_names:
cv2.imshow('res',image_resize(n,224.0))
cv2.waitKey(0)
dd.delete_service(sname,clear='') | near_names.append(s[str(n)])
print near_names
cv2.imshow('query',image_resize(args.search,224.0)) | random_line_split |
imgsearch.py | import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-ba... | (iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
def image_resize(imgfile,width):
imgquery = cv2.imread(imgfile)
r = width / imgquery.shape[1]
dim = (int(width), int(imgquery.shape[0] * r))
small = cv2.resize(imgquery,dim)
return smal... | batch | identifier_name |
imgsearch.py | import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-ba... |
host = 'localhost'
sname = 'imgserv'
description = 'image classification'
mllib = 'caffe'
mltype = 'unsupervised'
extract_layer = 'loss3/classifier'
#extract_layer = 'pool5/7x7_s1'
nclasses = 1000
layer_size = 1000 # default output code size
width = height = 224
binarized = False
dd = DD(host)
dd.set_return_format(dd... | imgquery = cv2.imread(imgfile)
r = width / imgquery.shape[1]
dim = (int(width), int(imgquery.shape[0] * r))
small = cv2.resize(imgquery,dim)
return small | identifier_body |
conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Qcloud COS SDK for Python 3 documentation build configuration file, created by
# cookiecutter pipproject
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... | # Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of so... | # -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
| random_line_split |
handlers.rs | use x11::xlib;
use window_system::WindowSystem;
use libc::{c_ulong};
pub struct KeyPressedHandler;
pub struct MapRequestHandler;
fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong {
let border_width = 2;
unsafe {
let border = xlib::XWhitePixel... | border_width,
border,background);
xlib::XSelectInput(window_system.display,
window,
xlib::SubstructureNotifyMask | xlib::SubstructureRedirectMask);
return window;... | x,
y,
width,
height, | random_line_split |
handlers.rs | use x11::xlib;
use window_system::WindowSystem;
use libc::{c_ulong};
pub struct KeyPressedHandler;
pub struct MapRequestHandler;
fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong {
let border_width = 2;
unsafe {
let border = xlib::XWhitePixel... |
else {
width = (window_system.info.width / 2) as u32;
height = window_system.info.height as u32;
x = width as i32;
}
// create frame as a new parent for the window to be mapped
let frame = create_some_window(window_system, width, height, x, y);
... | {
width = window_system.info.width as u32;
height = window_system.info.height as u32;
} | conditional_block |
handlers.rs | use x11::xlib;
use window_system::WindowSystem;
use libc::{c_ulong};
pub struct KeyPressedHandler;
pub struct | ;
fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong {
let border_width = 2;
unsafe {
let border = xlib::XWhitePixel(window_system.display,
xlib::XDefaultScreen(window_system.display));
let backgro... | MapRequestHandler | identifier_name |
Music.ts | function MusicDemo() | {
const bottomViewport = new Viewport(0, 1)
const buttons = [{
Label: "Classical",
Action: () => Music.Set(Content.Demos.Music.Classical)
}, {
Label: "Synth",
Action: () => Music.Set(Content.Demos.Music.Synth)
}, {
Label: "Easy L.",
Action: () => Music.Se... | identifier_body | |
Music.ts | function | () {
const bottomViewport = new Viewport(0, 1)
const buttons = [{
Label: "Classical",
Action: () => Music.Set(Content.Demos.Music.Classical)
}, {
Label: "Synth",
Action: () => Music.Set(Content.Demos.Music.Synth)
}, {
Label: "Easy L.",
Action: () => Music... | MusicDemo | identifier_name |
Music.ts | function MusicDemo() {
const bottomViewport = new Viewport(0, 1)
const buttons = [{
Label: "Classical",
Action: () => Music.Set(Content.Demos.Music.Classical)
}, {
Label: "Synth",
Action: () => Music.Set(Content.Demos.Music.Synth)
}, {
Label: "Easy L.",
A... | staticSprite.Loop(Content.Buttons.Narrow.Unpressed)
FontBig.Write(buttonGroup, button.Label, HorizontalAlignment.Middle, VerticalAlignment.Middle)
}
return () => {
Music.Stop()
bottomViewport.Delete()
}
} | button.Action()
})
buttonGroup.Move(IndexOf(buttons, button) * (WidthVirtualPixels - ButtonNarrowWidth) / (buttons.length - 1) + ButtonNarrowWidth / 2, HeightVirtualPixels - ButtonHeight / 2)
const staticSprite = new Sprite(buttonGroup) | random_line_split |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn main() | {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get_matches();
if let Some(matches) = matches.subcomman... | identifier_body | |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn main() {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get... | let n = s[4..8];
bases.entry((k, n)).
}
}
println!("Hello, world!");
} | // note: we could probably mix these.
let k = s[1];
// GXaa1234 - aa - the index of clip
let i = s[2..4];
// GX01bbbb - bbbb - the number of the video (composed of clips) | random_line_split |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn | () {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get_matches();
if let Some(matches) = matches.subcom... | main | identifier_name |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn main() {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get... |
let s = match p.to_str() {
Some(s) => s,
None => continue,
}
// P (x264) or X (x265)
// note: we could probably mix these.
let k = s[1];
// GXaa1234 - aa - the index of clip
let i = s[2..4];
... | {
continue;
} | conditional_block |
auth.repository.js | const jwt = require("jsonwebtoken");
module.exports = (UserModel, Config, CryptoHelper) => {
function _transformUser (user) {
return {
"id": user._id,
"name": user.name,
"isAdmin": user.isAdmin,
"created": user.createdAt,
"updated": user.updatedAt
}
}
async function signI... | const token = await jwt.sign(foundUser, Config.tokenSecret, {
expiresIn: Config.tokenExpires,
issuer: Config.tokenIssuer
});
// delete password before return the user
delete foundUser.passwordHash;
// return token and user
return {
token: token,
user: this._transformUser(... | if (userpassword !== CryptoHelper.decrypt(foundUser.passwordHash)) throw new Error("Authentication failed. Wrong password.");
// create a token | random_line_split |
auth.repository.js | const jwt = require("jsonwebtoken");
module.exports = (UserModel, Config, CryptoHelper) => {
function _transformUser (user) {
return {
"id": user._id,
"name": user.name,
"isAdmin": user.isAdmin,
"created": user.createdAt,
"updated": user.updatedAt
}
}
async function signI... |
return {
_transformUser,
signIn,
signUp
}
}
| {
// try to find the user
const foundUser = await UserModel.findOne({name: username}).lean();
// check if user is available
if (foundUser) throw new Error("Username is already registered. Please use another Username.");
// create new User object
const newUser = new UserModel({
name: userna... | identifier_body |
auth.repository.js | const jwt = require("jsonwebtoken");
module.exports = (UserModel, Config, CryptoHelper) => {
function _transformUser (user) {
return {
"id": user._id,
"name": user.name,
"isAdmin": user.isAdmin,
"created": user.createdAt,
"updated": user.updatedAt
}
}
async function | (username, userpassword) {
// search for username
const foundUser = await UserModel.findOne({ name: username }).lean();
// validate founduser
if (!foundUser) throw new Error("Authentication failed. User not found.")
if (userpassword !== CryptoHelper.decrypt(foundUser.passwordHash)) throw new Error(... | signIn | identifier_name |
mod.rs | use crate::{
commands::CommandHelpers,
entity::{EntityRef, Realm},
player_output::PlayerOutput,
};
mod enter_room_command;
pub use enter_room_command::enter_room;
pub fn | <F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Realm, EntityRef, CommandHelpers) -> Result<Vec<PlayerOutput>, String> + 'static,
{
Box::new(
move |realm, player_ref, helpers| match realm.player(player_ref) {
Some(player) if player... | wrap_admin_command | identifier_name |
mod.rs | use crate::{
commands::CommandHelpers,
entity::{EntityRef, Realm},
player_output::PlayerOutput,
};
mod enter_room_command;
pub use enter_room_command::enter_room;
pub fn wrap_admin_command<F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Real... | {
Box::new(
move |realm, player_ref, helpers| match realm.player(player_ref) {
Some(player) if player.is_admin() => match f(realm, player_ref, helpers) {
Ok(output) => output,
Err(mut message) => {
message.push('\n');
let mu... | identifier_body | |
mod.rs | use crate::{
commands::CommandHelpers,
entity::{EntityRef, Realm},
player_output::PlayerOutput,
};
mod enter_room_command;
pub use enter_room_command::enter_room;
pub fn wrap_admin_command<F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Real... | push_output_string!(output, player_ref, message);
output
}
},
_ => {
let mut output: Vec<PlayerOutput> = Vec::new();
push_output_str!(output, player_ref, "You are not an admin.");
output
... | let mut output: Vec<PlayerOutput> = Vec::new(); | random_line_split |
jquery.contextmenu.js | /// <reference path="../intellisense/jquery-1.2.6-vsdoc-cn.js" />
/* --------------------------------------------------
参数说明
option: {width:Number, items:Array, onShow:Function, rule:JSON}
成员语法(三种形式) -- para.items
-> {text:String, icon:String, type:String, alias:String, width:Number, items:Array} -- 菜单组
-> {te... | option = $.extend({ alias: "cmroot", width: 150 }, option);
var ruleName = null, target = null,
groups = {}, mitems = {}, actions = {}, showGroups = [],
itemTpl = "<div class='b-m-$[type]' unselectable=on><nobr unselectable=on><img src='$[icon]' align='absmiddle'/><span unselectable=on>$[t... | ion(option) {
| identifier_body |
jquery.contextmenu.js | /// <reference path="../intellisense/jquery-1.2.6-vsdoc-cn.js" />
/* --------------------------------------------------
参数说明
option: {width:Number, items:Array, onShow:Function, rule:JSON}
成员语法(三种形式) -- para.items
-> {text:String, icon:String, type:String, alias:String, width:Number, items:Array} -- 菜单组
-> {te... | }
var $root = $("#" + option.alias);
var root = null;
if ($root.length == 0) {
root = buildGroup.apply(gTemplet.clone()[0], [option]);
root.applyrule = applyRule;
root.showMenu = showMenu;
addItems(option.alias, option.items);
}
... | identifier_name | |
jquery.contextmenu.js | /// <reference path="../intellisense/jquery-1.2.6-vsdoc-cn.js" />
/* --------------------------------------------------
参数说明
option: {width:Number, items:Array, onShow:Function, rule:JSON}
成员语法(三种形式) -- para.items
-> {text:String, icon:String, type:String, alias:String, width:Number, items:Array} -- 菜单组
-> {te... | if ($root.length == 0) {
root = buildGroup.apply(gTemplet.clone()[0], [option]);
root.applyrule = applyRule;
root.showMenu = showMenu;
addItems(option.alias, option.items);
}
else {
root = $root[0];
}
var me = $... | var $root = $("#" + option.alias);
var root = null;
| random_line_split |
jquery.contextmenu.js | /// <reference path="../intellisense/jquery-1.2.6-vsdoc-cn.js" />
/* --------------------------------------------------
参数说明
option: {width:Number, items:Array, onShow:Function, rule:JSON}
成员语法(三种形式) -- para.items
-> {text:String, icon:String, type:String, alias:String, width:Number, items:Array} -- 菜单组
-> {te... | .items = null;
} //Endfor
gidx = items = null;
};
var overItem = function(e) {
//如果菜单项不可用
if (this.disable)
return false;
hideMenuPane.call(groups[this.gidx]);
//如果是菜单组
if (this.group)... | .type == "group") {
//菜单组
buildGroup.apply(gTemplet.clone()[0], [items[i]]);
arguments.callee(items[i].alias, items[i].items);
items[i].type = "arrow";
tmp = buildItem.apply(iTemplet.clone()[0], ... | conditional_block |
data_models.py | # Copyright 2014 Rackspace
#
# 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 agree... | (data_models.BaseDataModel):
def __init__(self, subnet_id=None, ip_address=None, subnet=None):
self.subnet_id = subnet_id
self.ip_address = ip_address
self.subnet = subnet
class AmphoraNetworkConfig(data_models.BaseDataModel):
def __init__(self, amphora=None, vip_subnet=None, vip_por... | FixedIP | identifier_name |
data_models.py | # Copyright 2014 Rackspace
#
# 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 agree... |
class Delta(data_models.BaseDataModel):
def __init__(self, amphora_id=None, compute_id=None,
add_nics=None, delete_nics=None):
self.compute_id = compute_id
self.amphora_id = amphora_id
self.add_nics = add_nics
self.delete_nics = delete_nics
class Network(data_m... | def __init__(self, id=None, compute_id=None, network_id=None,
fixed_ips=None, port_id=None):
self.id = id
self.compute_id = compute_id
self.network_id = network_id
self.port_id = port_id
self.fixed_ips = fixed_ips | identifier_body |
data_models.py | # Copyright 2014 Rackspace
#
# 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 agree... | self.vip_port = vip_port
self.vrrp_subnet = vrrp_subnet
self.vrrp_port = vrrp_port
self.ha_subnet = ha_subnet
self.ha_port = ha_port | vrrp_subnet=None, vrrp_port=None, ha_subnet=None,
ha_port=None):
self.amphora = amphora
self.vip_subnet = vip_subnet | random_line_split |
data_models.py | # Copyright 2014 Rackspace
#
# 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 agree... |
class FixedIP(data_models.BaseDataModel):
def __init__(self, subnet_id=None, ip_address=None, subnet=None):
self.subnet_id = subnet_id
self.ip_address = ip_address
self.subnet = subnet
class AmphoraNetworkConfig(data_models.BaseDataModel):
def __init__(self, amphora=None, vip_subn... | return fixed_ip.subnet_id | conditional_block |
index.js | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.Base.extend({ | var prompts = [{
type: 'input',
name: 'name',
message: 'Your project name',
//Defaults to the project's folder name if the input is skipped
default: this.appname
}];
return this.prompt(prompts).then(function (answers) {
this.props = answers;
this.log(answers.name);... | prompting: function () {
this.log(yosay(
'Welcome to the ' + chalk.red('generator-react-app-boilerplate') + ' generator!'
));
| random_line_split |
index.js | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.Base.extend({
prompting: function () {
this.log(yosay(
'Welcome to the ' + chalk.red('generator-react-app-boilerplate') + ' generator!'
));
var prompts = [{
... |
}.bind(this));
},
end: function() {
this.log("All Done!");
},
});
| {
this.installDependencies();
} | conditional_block |
future-reserved-words.ts | /*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3... |
}
function checkVariablesByScope(scope: Scope.Scope) {
scope.variables.filter(v => futureReservedWords.includes(v.name)).forEach(checkVariable);
scope.childScopes.forEach(childScope => {
checkVariablesByScope(childScope);
});
}
return {
'Program:exit': () => {
... | {
const def = variable.defs[0].name;
context.report({
node: def,
message:
`Rename "${variable.name}" identifier to prevent potential conflicts ` +
`with future evolutions of the JavaScript language.`,
});
} | conditional_block |
future-reserved-words.ts | /*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3... | (variable: Scope.Variable) {
if (variable.defs.length > 0) {
const def = variable.defs[0].name;
context.report({
node: def,
message:
`Rename "${variable.name}" identifier to prevent potential conflicts ` +
`with future evolutions of the JavaScript langua... | checkVariable | identifier_name |
future-reserved-words.ts | /*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3... |
function checkVariablesByScope(scope: Scope.Scope) {
scope.variables.filter(v => futureReservedWords.includes(v.name)).forEach(checkVariable);
scope.childScopes.forEach(childScope => {
checkVariablesByScope(childScope);
});
}
return {
'Program:exit': () => {
check... | {
if (variable.defs.length > 0) {
const def = variable.defs[0].name;
context.report({
node: def,
message:
`Rename "${variable.name}" identifier to prevent potential conflicts ` +
`with future evolutions of the JavaScript language.`,
});
}
... | identifier_body |
future-reserved-words.ts | /*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3... | function checkVariablesByScope(scope: Scope.Scope) {
scope.variables.filter(v => futureReservedWords.includes(v.name)).forEach(checkVariable);
scope.childScopes.forEach(childScope => {
checkVariablesByScope(childScope);
});
}
return {
'Program:exit': () => {
checkVa... | }
| random_line_split |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (r : rand::rng, n : uint) -> bool { under(r, n) == 0u }
// shuffle a vec in place
fn shuffle<T>(r : rand::rng, &v : ~[T]) {
let i = vec::len(v);
while i >= 2u {
// Loop invariant: elements with index >= i have been locked in place.
i -= 1u;
vec::swap(v, i, under(r, i + 1u)); // Lock ele... | unlikely | identifier_name |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | );
let mut a = ~[1, 2, 3];
shuffle(r, a);
log(error, a);
let i = 0u;
let v = ~[
{weight:1u, item:"low"},
{weight:8u, item:"middle"},
{weight:1u, item:"high"}
];
let w = weighted_vec(v);
while i < 1000u {
log(error, "Immed: " + weighted_choice(r, v));
... | { "likely" } | conditional_block |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(vec::len(v) != 0u);
let total = 0u;
for {weight: weight, item: _} in v {
total += weight;
}
assert!(total >= 0u);
let chosen = under(r, total);
let so_far = 0u;
for {weight: weight, item: item} in v {
so_far += weight;
if so_far > chosen {
retu... | // * weighted_vec is O(total weight) space
type weighted<T> = { weight: uint, item: T };
fn weighted_choice<T:copy>(r : rand::rng, v : ~[weighted<T>]) -> T { | random_line_split |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let r = rand::mk_rng();
log(error, under(r, 5u));
log(error, choice(r, ~[10, 20, 30]));
log(error, if unlikely(r, 5u) { "unlikely" } else { "likely" });
let mut a = ~[1, 2, 3];
shuffle(r, a);
log(error, a);
let i = 0u;
let v = ~[
{weight:1u, item:"low"},
{weight:... | identifier_body | |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct | {
pub key: u64,
pub disps: Vec<(u32, u32)>,
pub map: Vec<usize>,
}
pub fn generate_hash<H: PhfHash>(entries: &[H]) -> HashState {
let mut rng = XorShiftRng::from_seed(FIXED_SEED);
loop {
if let Some(s) = try_generate_hash(entries, &mut rng) {
return s;
}
}
}
fn try... | HashState | identifier_name |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct HashState {
pub k... |
fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> {
struct Bucket {
idx: usize,
keys: Vec<usize>,
}
struct Hashes {
g: u32,
f1: u32,
f2: u32,
}
let key = rng.gen();
let hashes: Vec<_> = entries.iter()
... | {
let mut rng = XorShiftRng::from_seed(FIXED_SEED);
loop {
if let Some(s) = try_generate_hash(entries, &mut rng) {
return s;
}
}
} | identifier_body |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct HashState {
pub k... | }
// Sort descending
buckets.sort_by(|a, b| a.keys.len().cmp(&b.keys.len()).reverse());
let table_len = entries.len();
let mut map = vec![None; table_len];
let mut disps = vec![(0u32, 0u32); buckets_len];
// store whether an element from the bucket being placed is
// located at a cert... | })
.collect::<Vec<_>>();
for (i, hash) in hashes.iter().enumerate() {
buckets[(hash.g % (buckets_len as u32)) as usize].keys.push(i); | random_line_split |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct HashState {
pub k... |
}
}
fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> {
struct Bucket {
idx: usize,
keys: Vec<usize>,
}
struct Hashes {
g: u32,
f1: u32,
f2: u32,
}
let key = rng.gen();
let hashes: Vec<_> = entries.iter()
... | {
return s;
} | conditional_block |
Tabs.tsx | import React, { useEffect, useRef, useState } from 'react';
import { cx } from '../../cx';
import './Tabs.css';
export type TabProps = {
children: React.ReactNode;
title: string;
};
const getTabId = (index: number, suffix?: string) =>
[`tab-${index}`, suffix].filter(Boolean).join('-');
export function Tabs({ ... |
};
return (
<div className="Tabs">
<div role="tablist" className="Tabs-header">
{React.Children.map<React.ReactChild, React.ReactElement<TabProps>>(
children,
(child, index) => {
const isSelected = currentTab === index;
return (
<button
... | {
setCurrentTab(
Math.min(currentTab + 1, React.Children.count(children) - 1)
);
} | conditional_block |
Tabs.tsx | import React, { useEffect, useRef, useState } from 'react';
import { cx } from '../../cx';
import './Tabs.css'; | };
const getTabId = (index: number, suffix?: string) =>
[`tab-${index}`, suffix].filter(Boolean).join('-');
export function Tabs({ children }) {
const firstRender = useRef(true);
const [currentTab, setCurrentTab] = useState(0);
const tabsRefs = useRef<HTMLElement[]>([]);
useEffect(() => {
if (!firstRen... |
export type TabProps = {
children: React.ReactNode;
title: string; | random_line_split |
convert_acewiki.py | #! /usr/bin/env python
# AceWiki data converter
# Author: Kaarel Kaljurand
# Version: 2012-02-23
#
# This script provides the conversion of a given AceWiki data file
# into other formats, e.g. JSON and GF.
#
# Examples:
#
# python convert_acewiki.py --in geo.acewikidata > Geo.json
# python convert_acewiki.py --in geo.... |
def out_gf_abs(data, name):
"""
Outputs the data as GF abstract syntax file with the given name.
"""
print template_abs.substitute(name = name)
for id in sorted(data):
if 'words' in data[id]:
type = data[id]['type']
[gf_type, gf_oper] = gf[type]
print 'w{}_{} : {} ;'.format(id, gf_type, gf_type)
pri... | """
Parses AceWiki data file into a Python data structure.
TODO: Currently does not change the token representation (i.e. <id1,id2>).
Assumes that article IDs are integers.
This way we get an ordering for articles which results in a stable output.
"""
data = {}
id = -1
f = open(path, 'r')
for line in f:
line... | identifier_body |
convert_acewiki.py | #! /usr/bin/env python
# AceWiki data converter
# Author: Kaarel Kaljurand
# Version: 2012-02-23
#
# This script provides the conversion of a given AceWiki data file
# into other formats, e.g. JSON and GF.
#
# Examples:
#
# python convert_acewiki.py --in geo.acewikidata > Geo.json
# python convert_acewiki.py --in geo.... |
# Commandline arguments parsing
parser = argparse.ArgumentParser(description='AceWiki data file converter')
parser.add_argument('-i', '--in', type=str, action='store', dest='file_in',
help='file that contains AceWiki data (OBLIGATORY)')
parser.add_argument('-n', '--name', type=str, action='store... | for s in data[id]['sentences']:
if s['type'] == 'c':
continue
print ' '.join([rewrite_token(data, x) for x in s['content']]) | conditional_block |
convert_acewiki.py | #! /usr/bin/env python
# AceWiki data converter
# Author: Kaarel Kaljurand
# Version: 2012-02-23
#
# This script provides the conversion of a given AceWiki data file
# into other formats, e.g. JSON and GF.
#
# Examples:
#
# python convert_acewiki.py --in geo.acewikidata > Geo.json
# python convert_acewiki.py --in geo.... |
def out_gf_abs(data, name):
"""
Outputs the data as GF abstract syntax file with the given name.
"""
print template_abs.substitute(name = name)
for id in sorted(data):
if 'words' in data[id]:
type = data[id]['type']
[gf_type, gf_oper] = gf[type]
print 'w{}_{} : {} ;'.format(id, gf_type, gf_type)
print... | random_line_split | |
convert_acewiki.py | #! /usr/bin/env python
# AceWiki data converter
# Author: Kaarel Kaljurand
# Version: 2012-02-23
#
# This script provides the conversion of a given AceWiki data file
# into other formats, e.g. JSON and GF.
#
# Examples:
#
# python convert_acewiki.py --in geo.acewikidata > Geo.json
# python convert_acewiki.py --in geo.... | (data, token):
"""
If the given token is a function word then
returns it lowercased (unless it is a variable),
otherwise
returns the wordform that corresponds to the ID-representation.
"""
m = pattern_token.match(token)
if m is None:
if token in ['X', 'Y', 'Z']:
return token
return token.lower()
else:
... | rewrite_token | identifier_name |
ngdevmode_debug_spec.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {Component} from '@angular/core';
import {getLContext} from '@an... | template: `
<ul>
<li *ngIf="true">item</li>
</ul>
`
})
class MyApp {
}
TestBed.configureTestingModule({declarations: [MyApp], imports: [CommonModule]});
const fixture = TestBed.createComponent(MyApp);
const rootLView = getLContext(fixture.na... |
onlyInIvy('Debug information exist in ivy only').describe('ngDevMode debug', () => {
describe('LViewDebug', () => {
supportsArraySubclassing && it('should name LView based on type', () => {
@Component({ | random_line_split |
ngdevmode_debug_spec.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {Component} from '@angular/core';
import {getLContext} from '@an... | {
}
TestBed.configureTestingModule({declarations: [MyApp], imports: [CommonModule]});
const fixture = TestBed.createComponent(MyApp);
const rootLView = getLContext(fixture.nativeElement)!.lView;
expect(rootLView.constructor.name).toEqual('LRootView');
const componentLView = getCom... | MyApp | identifier_name |
problem2.py | import matplotlib.pyplot as plt
import numpy as np |
mean = 0
variance = 1
sigma = math.sqrt(variance)
def drawSampleNormal(sampleSize):
samples = np.random.normal(mean, sigma, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed=True)
plt.plot(bins,mlab.normpdf(bins,mean,sigma))
plt.show()
plt.savefig("normal_" + str(sampleSize) + "_sam... | import matplotlib.mlab as mlab
import math
import scipy.special as sps | random_line_split |
problem2.py | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
import scipy.special as sps
mean = 0
variance = 1
sigma = math.sqrt(variance)
def | (sampleSize):
samples = np.random.normal(mean, sigma, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed=True)
plt.plot(bins,mlab.normpdf(bins,mean,sigma))
plt.show()
plt.savefig("normal_" + str(sampleSize) + "_samples.png")
plt.clf()
drawSampleNormal(20)
drawSampleNormal(50) ... | drawSampleNormal | identifier_name |
problem2.py | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
import scipy.special as sps
mean = 0
variance = 1
sigma = math.sqrt(variance)
def drawSampleNormal(sampleSize):
samples = np.random.normal(mean, sigma, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed... |
drawSampleGamma(20)
drawSampleGamma(50)
drawSampleGamma(100)
drawSampleGamma(500) | samples = np.random.gamma(alpha, beta, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed=True)
pdf = bins**(alpha-1)*(np.exp(-bins/beta) / (sps.gamma(alpha)*beta**alpha))
plt.plot(bins, pdf, linewidth=2, color='r')
plt.show()
plt.savefig("gamma_" + str(sampleSize) + "_samples.png")
... | identifier_body |
data-types.js | 'use strict';
const _ = require('lodash');
const moment = require('moment-timezone');
module.exports = BaseTypes => {
BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types';
/**
* types: [buffer_type, ...]
* @see documentation : https://mariadb.com/kb/en/libr... | extends BaseTypes.GEOMETRY {
constructor(type, srid) {
super(type, srid);
if (_.isEmpty(this.type)) {
this.sqlType = this.key;
}
else {
this.sqlType = this.type;
}
}
toSql() {
return this.sqlType;
}
}
class ENUM extends BaseTypes.ENUM {
toSql... | GEOMETRY | identifier_name |
data-types.js | 'use strict';
const _ = require('lodash');
const moment = require('moment-timezone');
module.exports = BaseTypes => {
BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types';
/**
* types: [buffer_type, ...]
* @see documentation : https://mariadb.com/kb/en/libr... | BaseTypes.FLOAT.types.mariadb = ['FLOAT'];
BaseTypes.TIME.types.mariadb = ['TIME'];
BaseTypes.DATEONLY.types.mariadb = ['DATE'];
BaseTypes.BOOLEAN.types.mariadb = ['TINY'];
BaseTypes.BLOB.types.mariadb = ['TINYBLOB', 'BLOB', 'LONGBLOB'];
BaseTypes.DECIMAL.types.mariadb = ['NEWDECIMAL'];
BaseTypes.UUID.typ... | BaseTypes.MEDIUMINT.types.mariadb = ['INT24'];
BaseTypes.INTEGER.types.mariadb = ['LONG'];
BaseTypes.BIGINT.types.mariadb = ['LONGLONG']; | random_line_split |
data-types.js | 'use strict';
const _ = require('lodash');
const moment = require('moment-timezone');
module.exports = BaseTypes => {
BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types';
/**
* types: [buffer_type, ...]
* @see documentation : https://mariadb.com/kb/en/libr... |
if (this._zerofill) {
definition += ' ZEROFILL';
}
return definition;
}
}
class DATE extends BaseTypes.DATE {
toSql() {
return `DATETIME${this._length ? `(${this._length})` : ''}`;
}
_stringify(date, options) {
date = this._applyTimezone(date, options);
... | {
definition += ' UNSIGNED';
} | conditional_block |
594422d373ee_fip_qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | op.create_table(
'qos_fip_policy_bindings',
sa.Column('policy_id',
sa.String(length=db_const.UUID_FIELD_SIZE),
sa.ForeignKey('qos_policies.id', ondelete='CASCADE'),
nullable=False),
sa.Column('fip_id',
sa.String(length=db_co... | identifier_body | |
594422d373ee_fip_qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | ():
op.create_table(
'qos_fip_policy_bindings',
sa.Column('policy_id',
sa.String(length=db_const.UUID_FIELD_SIZE),
sa.ForeignKey('qos_policies.id', ondelete='CASCADE'),
nullable=False),
sa.Column('fip_id',
sa.String(leng... | upgrade | identifier_name |
594422d373ee_fip_qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | sa.String(length=db_const.UUID_FIELD_SIZE),
sa.ForeignKey('floatingips.id', ondelete='CASCADE'),
nullable=False, unique=True)) | nullable=False),
sa.Column('fip_id', | random_line_split |
map_data.ts | MapData = function (dungeonConfig) {
return createMapData(dungeonConfig);
};
function | (dungeonConfig) {
var _width = ROT.RNG.getUniformInt(dungeonConfig.minWidth, dungeonConfig.maxWidth);
var _height = ROT.RNG.getUniformInt(dungeonConfig.minHeight, dungeonConfig.maxHeight);
var _tiles = new Array(_width);
for (var x = 0; x < _width; x++) {
_tiles[x] = new Array(_height);
}
var getWidth = fun... | createMapData | identifier_name |
map_data.ts | MapData = function (dungeonConfig) {
return createMapData(dungeonConfig);
};
function createMapData(dungeonConfig) {
var _width = ROT.RNG.getUniformInt(dungeonConfig.minWidth, dungeonConfig.maxWidth);
var _height = ROT.RNG.getUniformInt(dungeonConfig.minHeight, dungeonConfig.maxHeight);
var _tiles = new Array(_... |
var getWidth = function () {
return _width;
};
var getHeight = function () {
return _height;
};
var getTiles = function () {
return _tiles;
};
var addTile = function (tile, x, y) {
tile.setPosition(x, y);
_tiles[x][y] = tile;
};
var getTile = function (x, y) {
return _tiles[x][y];
};
var m... | {
_tiles[x] = new Array(_height);
} | conditional_block |
map_data.ts | MapData = function (dungeonConfig) {
return createMapData(dungeonConfig);
};
function createMapData(dungeonConfig) | {
var _width = ROT.RNG.getUniformInt(dungeonConfig.minWidth, dungeonConfig.maxWidth);
var _height = ROT.RNG.getUniformInt(dungeonConfig.minHeight, dungeonConfig.maxHeight);
var _tiles = new Array(_width);
for (var x = 0; x < _width; x++) {
_tiles[x] = new Array(_height);
}
var getWidth = function () {
ret... | identifier_body | |
map_data.ts | MapData = function (dungeonConfig) {
return createMapData(dungeonConfig);
};
function createMapData(dungeonConfig) {
var _width = ROT.RNG.getUniformInt(dungeonConfig.minWidth, dungeonConfig.maxWidth);
var _height = ROT.RNG.getUniformInt(dungeonConfig.minHeight, dungeonConfig.maxHeight);
var _tiles = new Array(_... |
var addTile = function (tile, x, y) {
tile.setPosition(x, y);
_tiles[x][y] = tile;
};
var getTile = function (x, y) {
return _tiles[x][y];
};
var map = {};
map.getWidth = getWidth;
map.getHeight = getHeight;
map.getTiles = getTiles;
map.addTile = addTile;
map.getTile = getTile;
return map;
} | return _tiles;
}; | random_line_split |
dropck_vec_cycle_checked.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
#[derive(Debug)]
struct C<'a> {
id: Id,
v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>,
}
impl<'a> HasId for Cell<Option<&'a C<'a>>> {
fn count(&self) -> usize {
match self.get() {
None => 1,
Some(c) => c.id.count(),
}
}
}
impl<'a> C<'a> {
fn new() -> C<'a> {
... | fn drop(&mut self) {
assert!(self.v.count() > 0);
} | random_line_split |
dropck_vec_cycle_checked.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> Id {
let c = s::next_count();
println!("building Id {}", c);
Id { orig_count: c, count: c }
}
pub fn count(&self) -> usize {
println!("Id::count on {} returns {}", self.orig_count, self.count);
self.count
}
}
impl Drop fo... | new | identifier_name |
tags_include.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | self._set_content(content)
response = self.get(LESSON_URL)
self._expect_content('Test Course', response)
def test_inclusion(self):
content = 'Hello, World!'
sub_path = os.path.join(
appengine_config.BUNDLE_ROOT, HTML_DIR, 'sub.html')
self.context.fs.put(s... | content = '{{ course_info.course.title }}' | random_line_split |
tags_include.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
with open(HTML_PATH, 'w') as fp:
fp.write(simple_content)
response = self.get(LESSON_URL)
os.unlink(HTML_PATH)
self._expect_content(simple_content, response)
def test_simple(self):
simple_content = 'Deep thunder rolled around their shores'
self._set_cont... | os.mkdir(HTML_DIR) | conditional_block |
tags_include.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | def setUp(self):
super(TagsInclude, self).setUp()
self.context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL,
COURSE_TITLE)
self.course = courses.Course(None, self.context)
self.unit = self.course.add_unit()
self.unit.title... | identifier_body | |
tags_include.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | (self, expected, response):
expected = '%s<div>%s</div>%s' % (PRE_INCLUDE, expected, POST_INCLUDE)
self.assertIn(expected, response.body)
def test_missing_file_gives_error(self):
self.lesson.objectives = GCB_INCLUDE % 'no_such_file.html'
self.course.save()
response = self.ge... | _expect_content | identifier_name |
html2html.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | use html5ever::driver::ParseOpts;
use html5ever::tree_builder::TreeBuilderOpts;
use html5ever::{parse, one_input, serialize};
fn main() {
let input = io::stdin().read_to_string().unwrap();
let dom: RcDom = parse(one_input(input), ParseOpts {
tree_builder: TreeBuilderOpts {
drop_doctype: tru... | use std::default::Default;
use html5ever::sink::rcdom::RcDom; | random_line_split |
html2html.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | {
let input = io::stdin().read_to_string().unwrap();
let dom: RcDom = parse(one_input(input), ParseOpts {
tree_builder: TreeBuilderOpts {
drop_doctype: true,
..Default::default()
},
..Default::default()
});
// The validator.nu HTML2HTML always prints a do... | identifier_body | |
html2html.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | () {
let input = io::stdin().read_to_string().unwrap();
let dom: RcDom = parse(one_input(input), ParseOpts {
tree_builder: TreeBuilderOpts {
drop_doctype: true,
..Default::default()
},
..Default::default()
});
// The validator.nu HTML2HTML always prints a... | main | identifier_name |
lib.rs | #![feature(no_std,core_intrinsics)]
#![no_std]
#[macro_export]
macro_rules! impl_fmt
{
(@as_item $($i:item)*) => {$($i)*};
($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t {
fn fmt(&$s... | $(impl_from!{ @as_item
impl$(<$($params)+>)* ::std::convert::From<$src> for $t {
fn from($v: $src) -> $t {
$($code)*
}
}
})+
};
(@match_ $( $(<($($params:tt)+)>)* Into<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl$(<$($params)+>)* ::std::convert:... | (@as_item $($i:item)*) => {$($i)*};
(@match_ $( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { | random_line_split |
lib.rs | #![feature(no_std,core_intrinsics)]
#![no_std]
#[macro_export]
macro_rules! impl_fmt
{
(@as_item $($i:item)*) => {$($i)*};
($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t {
fn fmt(&$s... |
#[macro_export]
macro_rules! type_name {
($t:ty) => ( $crate::type_name::<$t>() );
}
#[macro_export]
macro_rules! todo
{
( $s:expr ) => ( panic!( concat!("TODO: ",$s) ) );
( $s:expr, $($v:tt)* ) => ( panic!( concat!("TODO: ",$s), $($v)* ) );
}
/// Override libcore's `try!` macro with one that backs onto `From`
#[... | {
// SAFE: Intrinsic with no sideeffect
unsafe { ::core::intrinsics::type_name::<T>() }
} | identifier_body |
lib.rs | #![feature(no_std,core_intrinsics)]
#![no_std]
#[macro_export]
macro_rules! impl_fmt
{
(@as_item $($i:item)*) => {$($i)*};
($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t {
fn fmt(&$s... | <T: ?::core::marker::Sized>() -> &'static str {
// SAFE: Intrinsic with no sideeffect
unsafe { ::core::intrinsics::type_name::<T>() }
}
#[macro_export]
macro_rules! type_name {
($t:ty) => ( $crate::type_name::<$t>() );
}
#[macro_export]
macro_rules! todo
{
( $s:expr ) => ( panic!( concat!("TODO: ",$s) ) );
( $s:e... | type_name | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RAffxparser(RPackage):
| """Affymetrix File Parsing SDK
Package for parsing Affymetrix files (CDF, CEL, CHP, BPMAP, BAR). It
provides methods for fast and memory efficient parsing of Affymetrix
files using the Affymetrix' Fusion SDK. Both ASCII- and binary-based
files are supported. Currently, there are methods for... | identifier_body | |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RAffxparser(RPackage):
"""Affymetrix File Parsing SDK
Package for parsing Affymetr... | definition file (CDF) and a cell intensity file (CEL). These files can
be read either in full or in part. For example, probe signals from a few
probesets can be extracted very quickly from a set of CEL files into a
convenient list structure."""
homepage = "https://bioconductor.org/packa... | random_line_split | |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (RPackage):
"""Affymetrix File Parsing SDK
Package for parsing Affymetrix files (CDF, CEL, CHP, BPMAP, BAR). It
provides methods for fast and memory efficient parsing of Affymetrix
files using the Affymetrix' Fusion SDK. Both ASCII- and binary-based
files are supported. Currently, there... | RAffxparser | identifier_name |
FIPBruteForce.py | import ftplib
def connect(host, user, password):
|
def main():
# Variables
targetHostAddress = '10.0.0.24'
userName = 'bwayne'
passwordsFilePath = 'passwords.txt'
# Try to connect using anonymous credentials
print('[+] Using anonymous credentials for ' + targetHostAddress)
if connect(targetHostAddress, 'anonymous', 'test@test.com'):
... | try:
ftp = ftplib.FTP(host)
ftp.login(user, password)
ftp.quit()
return True
except:
return False | identifier_body |
FIPBruteForce.py | import ftplib
def connect(host, user, password):
try:
ftp = ftplib.FTP(host)
ftp.login(user, password)
ftp.quit()
return True
except:
return False
def main():
# Variables
targetHostAddress = '10.0.0.24'
userName = 'bwayne'
passwordsFilePath = 'passwords.... | print('[*] FTP log on failed on host ' + targetHostAddress + '\n' + 'username: ' + userName + '\n' + 'password: ' + password)
if __name__ == "__main__":
main() | exit(0)
else: | random_line_split |
FIPBruteForce.py | import ftplib
def connect(host, user, password):
try:
ftp = ftplib.FTP(host)
ftp.login(user, password)
ftp.quit()
return True
except:
return False
def | ():
# Variables
targetHostAddress = '10.0.0.24'
userName = 'bwayne'
passwordsFilePath = 'passwords.txt'
# Try to connect using anonymous credentials
print('[+] Using anonymous credentials for ' + targetHostAddress)
if connect(targetHostAddress, 'anonymous', 'test@test.com'):
print('... | main | identifier_name |
FIPBruteForce.py | import ftplib
def connect(host, user, password):
try:
ftp = ftplib.FTP(host)
ftp.login(user, password)
ftp.quit()
return True
except:
return False
def main():
# Variables
targetHostAddress = '10.0.0.24'
userName = 'bwayne'
passwordsFilePath = 'passwords.... |
else:
print('[*] FTP Anonymous log on failed on host ' + targetHostAddress)
# Try brute force using dictionary
# Open passwords file
passwordsFile = open(passwordsFilePath, 'r')
for line in passwordsFile.readlines():
password = line.strip('\r').strip('\n')
print('Testing: ... | print('[*] FTP Anonymous log on succeeded on host ' + targetHostAddress) | conditional_block |
tables.js | import DB from '../db';
import * as types from '../constants/tablesConstants';
import { stopFetching, internalInitTable } from './currentTable';
export function setCurrentTable(tableName) {
return {
type: types.SET_CURRENT_TABLE,
tableName
};
}
export function changeTableName(newTableName) {
return {
... |
export function truncateTable(tableName, restartIdentity) {
return (dispatch) => {
dispatch({
type: 'tables/TRUNCATE_TABLE'
});
DB.truncateTable(tableName, restartIdentity);
};
}
function internalGetTables(dispatch, clear) {
return new Promise((resolve, reject) => {
if (clear) {
dis... | {
return (dispatch) => {
dispatch({
type: 'tables/DROP_TABLE'
});
DB.dropTable(tableName);
};
} | identifier_body |
tables.js | import DB from '../db';
import * as types from '../constants/tablesConstants';
import { stopFetching, internalInitTable } from './currentTable';
export function setCurrentTable(tableName) {
return {
type: types.SET_CURRENT_TABLE,
tableName
};
}
export function changeTableName(newTableName) {
return {
... | }
export function createTable(tableName, i = -1) {
return dispatch => new Promise((resolve, reject) => {
// eslint-disable-next-line no-param-reassign
DB.createTable(tableName)
.then(
() => {
dispatch({
type: types.CREATE_TABLE,
tableName
});
... | newTableName
}; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.