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 |
|---|---|---|---|---|
models.py | from django.db import models
from .mixins import FileMixin
class BaseCategory(models.Model):
title = models.CharField(max_length=100, unique=True)
class Meta:
abstract = True
ordering = ('title',)
def __str__(self):
return self.title
class FileCategory(BaseCategory):
class... | class Image(FileMixin, models.Model):
category = models.ForeignKey(ImageCategory, blank=True, null=True)
title = models.CharField(max_length=100, db_index=True)
file = models.ImageField(
'Image', upload_to='assets/image', height_field='image_height', width_field='image_width'
)
image_height ... | random_line_split | |
models.py | from django.db import models
from .mixins import FileMixin
class BaseCategory(models.Model):
|
class FileCategory(BaseCategory):
class Meta(BaseCategory.Meta):
verbose_name_plural = 'file categories'
class File(FileMixin, models.Model):
category = models.ForeignKey(FileCategory)
title = models.CharField(max_length=100, db_index=True)
file = models.FileField(upload_to='assets/file')
... | title = models.CharField(max_length=100, unique=True)
class Meta:
abstract = True
ordering = ('title',)
def __str__(self):
return self.title | identifier_body |
models.py | from django.db import models
from .mixins import FileMixin
class BaseCategory(models.Model):
title = models.CharField(max_length=100, unique=True)
class Meta:
abstract = True
ordering = ('title',)
def __str__(self):
return self.title
class FileCategory(BaseCategory):
class... | (FileMixin, models.Model):
category = models.ForeignKey(FileCategory)
title = models.CharField(max_length=100, db_index=True)
file = models.FileField(upload_to='assets/file')
file_size = models.PositiveIntegerField(default=0, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
m... | File | identifier_name |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | }
| {
let python = if Command::new("python2.7").arg("--version").status().unwrap().success() {
"python2.7"
} else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let result =... | identifier_body |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let result = Command::new(python)
.env("PYTHONPATH", &mako)
.env("TEMPLATE", &template)
.arg("-c")
.... | {
"python2.7"
} | conditional_block |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | } else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let result = Command::new(python)
.env("PYTHONPATH", &mako)
.env("TEMPLATE", &template)
.arg("-c")
... | fn main() {
let python = if Command::new("python2.7").arg("--version").status().unwrap().success() {
"python2.7" | random_line_split |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | () {
let python = if Command::new("python2.7").arg("--version").status().unwrap().success() {
"python2.7"
} else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let resul... | main | identifier_name |
eventtypes.js | 'use strict';
/**
* Types of events
* @readonly
* @enum {number}
*/
var EventTypes = {
// Channel Events
/**
* A channel got connected
* @type {EventType}
*/
CONNECT: "connect",
/**
* A channel got disconnected
*/
DISCONNECT: "disconnect",
/**
* A cha... | * voteResponse
*/
VOTERESPONSE: "voteResponse",
/**
* finishPoll
*/
FINISHPOLL: "finishPoll",
/**
* gameMode
*/
GAMEMODE: "gameMode",
/**
* adultMode
*/
ADULTMODE: "adultMode",
/**
* commissionsAvailable
*/
COMMISSIONSAVAILABLE: "comm... | * pollVotes
*/
POLLVOTES: "pollVotes",
/** | random_line_split |
crypto_utils.ts |
* buffer. Returns the extracted type string or undefined if the
* buffer doesn't seem to be any sort of PEM format file.
*/
export function identifyPemType(rawKey: Buffer | string): undefined | string {
if (rawKey instanceof Buffer) {
rawKey = rawKey.toString("utf8");
}
const match = PEM_TYPE_RE... | // if the value you're encrypting is smaller). So the highest number of bits you can encrypt with a 1024-bit
// key is 936 bits because of this (unless you disable the padding by adding the OPENSSL_NO_PADDING flag,
// in which case you can go up to 1023-1024 bits). With a 2048-bit key it's 1960 bits instead.
export co... | // quantities without losing security), and that padding scheme takes a minimum of 11 bytes (it will be longer | random_line_split |
crypto_utils.ts | * buffer. Returns the extracted type string or undefined if the
* buffer doesn't seem to be any sort of PEM format file.
*/
export function identifyPemType(rawKey: Buffer | string): undefined | string {
if (rawKey instanceof Buffer) {
rawKey = rawKey.toString("utf8");
}
const match = PEM_TYPE_REG... | else {
pemType = pem;
assert(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
let b = (raw_key as Buffer).toString("base64");
let str = "-----BEGIN " + pemType + "-----\n";
while (b.length) {
str += b.substr(... | {
return raw_key instanceof Buffer ? raw_key.toString("utf8") : raw_key;
} | conditional_block |
crypto_utils.ts | format file.
*/
export function identifyPemType(rawKey: Buffer | string): undefined | string {
if (rawKey instanceof Buffer) {
rawKey = rawKey.toString("utf8");
}
const match = PEM_TYPE_REGEX.exec(rawKey);
return !match ? undefined : match[2];
}
export function convertPEMtoDER(raw_key: PEM): ... | coerceCertificatePem | identifier_name | |
crypto_utils.ts | _TYPE_REGEX.exec(rawKey);
return !match ? undefined : match[2];
}
export function convertPEMtoDER(raw_key: PEM): DER {
let match: any;
let pemType;
let base64str;
const parts: DER[] = [];
PEM_REGEX.lastIndex = 0;
// tslint:disable-next-line:no-conditional-assignment
while ((match = PE... | {
if (certificate instanceof Buffer) {
certificate = toPem(certificate, "CERTIFICATE");
}
assert(typeof certificate === "string");
return certificate;
} | identifier_body | |
pullCharityData.py | import urllib2
import wikipedia
import json
from bs4 import BeautifulSoup
if __name__ == '__main__':
| except:
print "Raise error/exception"
with open("charityData.json", "w") as outfile:
json.dump(charity_results, outfile)
| wikipedia.set_rate_limiting(True)
charity_list_url = 'List_of_charitable_foundations'
wikipage_list = wikipedia.page(charity_list_url)
charity_results = []
for charity_name in wikipage_list.links:
try:
wikipage_charity = wikipedia.page(charity_name)
name = charity_name
... | conditional_block |
UserInformationManagementFormPanel.js | var UserInformation_AccountStore = new Ext.data.Store({
fields:[
{name : 'Name'},
{name : 'ID'},
{name : 'Mail'},
{name : 'Roles'}
],
reader : AccountReader
});
var UserInformationItem = [
{
fieldLabel : 'User ID',
name : 'id',
readOnly : true
}, {
fieldLabel : 'User Name... | failure:function(response){
UserManagementMainLoadMaskHide();
Ext.example.msg('Server Error', 'Sorry, the connection is failure.');
}
});
}
});
Ext.reg('UserInformationForm', ezScrum.UserInformationForm); |
UserManagementMainLoadMaskHide();
}, | random_line_split |
UserInformationManagementFormPanel.js | var UserInformation_AccountStore = new Ext.data.Store({
fields:[
{name : 'Name'},
{name : 'ID'},
{name : 'Mail'},
{name : 'Roles'}
],
reader : AccountReader
});
var UserInformationItem = [
{
fieldLabel : 'User ID',
name : 'id',
readOnly : true
}, {
fieldLabel : 'User Name... | else {
Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(false);
this.allowBlank = false;
}
}
}
}, {
fieldLabel : 'E-mail Address',
name : 'email',
vtype : 'email',
allowBlank ... | {
Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(true);
this.allowBlank = true;
} | conditional_block |
keyword.rs | use liquid_core::Expression;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{
Display_filter, Filter, FilterParameters, FilterReflection, FromFilterParameters, ParseFilter,
};
use liquid_core::{Value, ValueView};
#[derive(Debug, FilterParameters)]
struct TestKeywordFilterParameters {
#[par... | ;
#[derive(Debug, FromFilterParameters, Display_filter)]
#[name = "kw"]
pub struct TestKeywordFilter {
#[parameters]
args: TestKeywordFilterParameters,
}
impl Filter for TestKeywordFilter {
fn evaluate(&self, _input: &dyn ValueView, runtime: &dyn Runtime) -> Result<Value> {
let args = self.args.ev... | TestKeywordFilterParser | identifier_name |
keyword.rs | use liquid_core::Expression;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{
Display_filter, Filter, FilterParameters, FilterReflection, FromFilterParameters, ParseFilter,
};
use liquid_core::{Value, ValueView};
#[derive(Debug, FilterParameters)]
struct TestKeywordFilterParameters {
#[par... | let result = if let Some(optional) = args.optional {
format!("<optional: {}; required: {}>", optional, required)
} else {
format!("<required: {}>", required)
};
Ok(Value::scalar(result))
}
} | random_line_split | |
keyword.rs | use liquid_core::Expression;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{
Display_filter, Filter, FilterParameters, FilterReflection, FromFilterParameters, ParseFilter,
};
use liquid_core::{Value, ValueView};
#[derive(Debug, FilterParameters)]
struct TestKeywordFilterParameters {
#[par... | ;
Ok(Value::scalar(result))
}
}
| {
format!("<required: {}>", required)
} | conditional_block |
viewer3d.js | from 'three';
import {parseData, updateScene} from './scene-creator';
import {disposeScene} from './three-memory-cleaner';
import OrbitControls from './libs/orbit-controls';
import diff from 'immutablediff';
import * as SharedStyle from '../../shared-style';
export default class Scene3DViewer extends React.Component ... | (nextProps) {
let {width, height} = nextProps;
let {camera, renderer, scene3D} = this;
let actions = {
areaActions: this.context.areaActions,
holesActions: this.context.holesActions,
itemsActions: this.context.itemsActions,
linesActions: this.context.linesActions,
projectActio... | componentWillReceiveProps | identifier_name |
viewer3d.js | from 'three';
import {parseData, updateScene} from './scene-creator';
import {disposeScene} from './three-memory-cleaner';
import OrbitControls from './libs/orbit-controls';
import diff from 'immutablediff';
import * as SharedStyle from '../../shared-style';
export default class Scene3DViewer extends React.Component ... | };
planData.plan.traverse((child) => {
console.log(child);
if (child instanceof Three.Mesh && !(child.geometry instanceof Three.BufferGeometry))
child.geometry = convertToBufferGeometry(child.geometry);
});
let output = planData.plan.toJSON();
output = JSON.str... | console.log("geometry = ", geometry);
return new Three.BufferGeometry().fromGeometry(geometry); | random_line_split |
viewer3d.js | from 'three';
import {parseData, updateScene} from './scene-creator';
import {disposeScene} from './three-memory-cleaner';
import OrbitControls from './libs/orbit-controls';
import diff from 'immutablediff';
import * as SharedStyle from '../../shared-style';
export default class Scene3DViewer extends React.Component ... |
};
this.renderer.domElement.addEventListener('mousedown', this.mouseDownEvent);
this.renderer.domElement.addEventListener('mouseup', this.mouseUpEvent);
this.renderer.domElement.style.display = 'block';
// add the output of the renderer to the html element
canvasWrapper.appendChild(this.rende... | {
raycaster.setFromCamera(mouse, camera);
let intersects = raycaster.intersectObjects(toIntersect, true);
if (intersects.length > 0 && !(isNaN(intersects[0].distance))) {
intersects[0].object.interact && intersects[0].object.interact();
} else {
this.context.project... | conditional_block |
request.js | function noReservedDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < reservedDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, reservedDays) !== -1) {
return [false];
}
}
return [true];
| dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"],
dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
monthNames: ["Januar", "Februar", ";ärz", "April", "Mai", "Juni", "Juli", "August", "... | }
$("#input_from").datepicker({
| random_line_split |
request.js | function noReservedDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < reservedDays.length; i++) |
return [true];
}
$("#input_from").datepicker({
dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"],
dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
monthNames: ["Januar", "F... | {
if ($.inArray((m + 1) + '-' + d + '-' + y, reservedDays) !== -1) {
return [false];
}
} | conditional_block |
request.js | function noReservedDays(date) |
$("#input_from").datepicker({
dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"],
dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
monthNames: ["Januar", "Februar", ";ärz", "April",... | {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < reservedDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, reservedDays) !== -1) {
return [false];
}
}
return [true];
} | identifier_body |
request.js | function | (date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < reservedDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, reservedDays) !== -1) {
return [false];
}
}
return [true];
}
$("#input_from").datepicker({
... | noReservedDays | identifier_name |
keyboardlayout.py | # Copyright (c) 2013 Jacob Mourelos
# Copyright (c) 2014 Shepilov Vladislav
# Copyright (c) 2014-2015 Sean Vig | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portio... | # Copyright (c) 2014 Tycho Andersen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights | random_line_split |
keyboardlayout.py | # Copyright (c) 2013 Jacob Mourelos
# Copyright (c) 2014 Shepilov Vladislav
# Copyright (c) 2014-2015 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Sof... |
def button_press(self, x, y, button):
if button == 1:
self.next_keyboard()
def next_keyboard(self):
"""Set the next layout in the list of configured keyboard layouts as
new current layout in use
If the current keyboard layout is not in the list, it will set as new... | base.InLoopPollText.__init__(self, **config)
self.add_defaults(KeyboardLayout.defaults) | identifier_body |
keyboardlayout.py | # Copyright (c) 2013 Jacob Mourelos
# Copyright (c) 2014 Shepilov Vladislav
# Copyright (c) 2014-2015 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Sof... | (self):
"""Set the next layout in the list of configured keyboard layouts as
new current layout in use
If the current keyboard layout is not in the list, it will set as new
layout the first one in the list.
"""
current_keyboard = self.keyboard
if current_keyboar... | next_keyboard | identifier_name |
keyboardlayout.py | # Copyright (c) 2013 Jacob Mourelos
# Copyright (c) 2014 Shepilov Vladislav
# Copyright (c) 2014-2015 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Sof... |
def next_keyboard(self):
"""Set the next layout in the list of configured keyboard layouts as
new current layout in use
If the current keyboard layout is not in the list, it will set as new
layout the first one in the list.
"""
current_keyboard = self.keyboard
... | self.next_keyboard() | conditional_block |
__init__.py | ''' The `Filter` hierarchy contains Transformer classes that take a `Stim`
of one type as input and return a `Stim` of the same type as output (but with
some changes to its data).
'''
from .audio import (AudioTrimmingFilter,
AudioResamplingFilter)
from .base import TemporalTrimmingFilter
from .ima... | ] | random_line_split | |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... |
}
len
};
input.consume(len);
}
}
// A Read computing a digest on the bytes read.
pub struct HasherRead<'a, R, H>
where
R: 'a + io::Read,
H: 'a + hash::Hasher,
{
read: &'a mut R, // underlying reader
hasher: &'a mut H, // hasher
}
impl<'a, R, H> HasherRea... | {
return Ok(false);
} | conditional_block |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... | } | random_line_split | |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... | (&mut self) -> io::Result<&[u8]> {
self.read.fill_buf()
}
fn consume(&mut self, amt: usize) {
self.read.consume(amt);
self.count += amt;
}
}
| fill_buf | identifier_name |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... |
fn consume(&mut self, amt: usize) {
self.read.consume(amt);
self.count += amt;
}
}
| {
self.read.fill_buf()
} | identifier_body |
message.rs | /// Takes a new message received by the relay, and parses out the header for it
///
/// The header protocol has the first 4 bytes make an integer which is the,
/// total size of the message, and a single byte which represents if zlib
/// compression is enabled for the rest of the message
pub fn new... | }
/// Possible types of messages received from relay (almost every message, excluding pongs,
/// will use HData)
#[derive(Debug)]
pub enum Type {
StrData(StrData),
HData(HData),
}
impl Message {
pub fn new(bytes: &[u8]) -> Result<Message, WeechatError> {
// First thing encoded is the identifier fo... | /// Data contained in this message
data_type: Type, | random_line_split |
message.rs | Takes a new message received by the relay, and parses out the header for it
///
/// The header protocol has the first 4 bytes make an integer which is the,
/// total size of the message, and a single byte which represents if zlib
/// compression is enabled for the rest of the message
pub fn new(byt... | (&self) -> Result<i32, WeechatError> {
match *self {
Object::Int(i) => Ok(i),
_ => Err(ParseError("Item is not a integer".to_string()))
}
}
/// Returns this data as a long if it is a long.
pub fn as_long(&self) -> Result<i64, WeechatError> {
matc... | as_integer | identifier_name |
message.rs | Takes a new message received by the relay, and parses out the header for it
///
/// The header protocol has the first 4 bytes make an integer which is the,
/// total size of the message, and a single byte which represents if zlib
/// compression is enabled for the rest of the message
pub fn new(byt... |
/// Returns this data as a string if it is a string.
pub fn as_str(&self) -> Result<Option<&str>, WeechatError> {
match *self {
Object::Str(Some(ref s)) => Ok(Some(s)),
Object::Str(None) => Ok(None),
_ => Err(ParseError("Item is not a b... | {
try!(self.as_pointer().map(|p| p.ok_or(ParseError("pointer is null".to_string()))))
} | identifier_body |
coordinate.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
# | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along w... | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
# | random_line_split |
coordinate.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | (self):
print "CoordinateEncoder:"
print " w: %d" % self.w
print " n: %d" % self.n
@classmethod
def read(cls, proto):
encoder = object.__new__(cls)
encoder.w = proto.w
encoder.n = proto.n
encoder.verbosity = proto.verbosity
encoder.name = proto.name
return encoder
def... | dump | identifier_name |
coordinate.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
@staticmethod
def _neighbors(coordinate, radius):
"""
Returns coordinates around given coordinate, within given radius.
Includes given coordinate.
@param coordinate (numpy.array) Coordinate whose neighbors to find
@param radius (float) Radius around `coordinate`
@return (numpy.array) Li... | """
See `nupic.encoders.base.Encoder` for more information.
@param inputData (tuple) Contains coordinate (numpy.array)
and radius (float)
@param output (numpy.array) Stores encoded SDR in this numpy array
"""
(coordinate, radius) = inputData
neighbors = self._neighb... | identifier_body |
coordinate.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
if (n <= 6 * w) or (not isinstance(n, int)):
raise ValueError("n must be an int strictly greater than 6*w. For "
"good results we recommend n be strictly greater "
"than 11*w")
self.w = w
self.n = n
self.verbosity = verbosity
self.encoders = Non... | raise ValueError("w must be an odd positive integer") | conditional_block |
User.js | const TextBasedChannel = require('./interfaces/TextBasedChannel');
const Constants = require('../util/Constants');
const { Presence } = require('./Presence');
const UserProfile = require('./UserProfile');
const Snowflake = require('../util/Snowflake');
const { Error } = require('../errors');
/**
* Represents a user o... | {
constructor(client, data) {
/**
* The client that created the instance of the user
* @name User#client
* @type {Client}
* @readonly
*/
Object.defineProperty(this, 'client', { value: client });
if (data) this.setup(data);
}
setup(data) {
/**
* The ID of the user
... | User | identifier_name |
User.js | const TextBasedChannel = require('./interfaces/TextBasedChannel');
const Constants = require('../util/Constants');
const { Presence } = require('./Presence');
const UserProfile = require('./UserProfile');
const Snowflake = require('../util/Snowflake');
const { Error } = require('../errors');
/**
* Represents a user o... |
// These are here only for documentation purposes - they are implemented by TextBasedChannel
/* eslint-disable no-empty-function */
send() {}
}
TextBasedChannel.applyToClass(User);
module.exports = User;
| {
return `<@${this.id}>`;
} | identifier_body |
User.js | const TextBasedChannel = require('./interfaces/TextBasedChannel');
const Constants = require('../util/Constants');
const { Presence } = require('./Presence');
const UserProfile = require('./UserProfile');
const Snowflake = require('../util/Snowflake');
const { Error } = require('../errors');
/**
* Represents a user o... | }
/**
* Get the amount of time the user has been typing in a channel for (in milliseconds), or -1 if they're not typing.
* @param {ChannelResolvable} channel The channel to get the time in
* @returns {number}
*/
typingDurationIn(channel) {
channel = this.client.resolver.resolveChannel(channel);
... | return channel._typing.has(this.id) ? new Date(channel._typing.get(this.id).since) : null; | random_line_split |
info-pane.js | (function ($) {
function | () {
var $this = this;
/**
*
*/
this.init = function() {
$this.cssClassFull = 'fewbricks-info-pane--full';
if(!$this.initMainElm()) {
return;
}
$this.initToggler();
$this.$mainElm.show();
... | FewbricksDevHelper | identifier_name |
info-pane.js | (function ($) {
function FewbricksDevHelper() |
/**
*
*/
this.initMainElm = function() {
$this.$mainElm = $('#fewbricks-info-pane');
if($this.$mainElm.length === 0) {
return false;
}
if(typeof fewbricksInfoPane !== 'undefined' && typeof fewbricksInfoPane.startHeight... | {
var $this = this;
/**
*
*/
this.init = function() {
$this.cssClassFull = 'fewbricks-info-pane--full';
if(!$this.initMainElm()) {
return;
}
$this.initToggler();
$this.$mainElm.show();
} | identifier_body |
info-pane.js | (function ($) {
function FewbricksDevHelper() {
var $this = this;
/**
*
*/
this.init = function() {
$this.cssClassFull = 'fewbricks-info-pane--full';
if(!$this.initMainElm()) |
$this.initToggler();
$this.$mainElm.show();
}
/**
*
*/
this.initMainElm = function() {
$this.$mainElm = $('#fewbricks-info-pane');
if($this.$mainElm.length === 0) {
return false;
}
i... | {
return;
} | conditional_block |
info-pane.js | (function ($) {
function FewbricksDevHelper() {
var $this = this;
/**
*
*/
this.init = function() {
$this.cssClassFull = 'fewbricks-info-pane--full';
if(!$this.initMainElm()) {
return;
}
$this.initToggler... | }
$(document).ready(function () {
(new FewbricksDevHelper()).init();
});
})(jQuery); | return $this.$mainElm.hasClass($this.cssClassFull);
}
| random_line_split |
transform.ts | /**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* | * limitations under the License.
*/
import {promises as fsPromises} from 'fs';
import minimist from 'minimist';
import posthtml from 'posthtml';
import transformModules from './modules/modules-transform';
import transformScriptPaths from './scripts/scripts-transform';
import transformStories from './stories/stories-... | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and | random_line_split |
transform.ts | /**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | (fileLocation: string): Promise<string> {
const source = await fsPromises.readFile(fileLocation, 'utf8');
const result = await posthtml(transforms).process(source);
return result.html;
}
| transform | identifier_name |
transform.ts | /**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | {
const source = await fsPromises.readFile(fileLocation, 'utf8');
const result = await posthtml(transforms).process(source);
return result.html;
} | identifier_body | |
transform.ts | /**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
export async function transform(fileLocation: string): Promise<string> {
const source = await fsPromises.readFile(fileLocation, 'utf8');
const result = await posthtml(transforms).process(source);
return result.html;
}
| {
transforms.unshift(transformModules);
} | conditional_block |
base_types.py | """
Contains base data structures for defining graph constrained group testing problem,
and interfaces to operate on them.
Basic structure to exchange graph constrained group testing problem definition is :class:`Problem`.
It consists of enumeration of faulty elements, graph of links between elements and natural langu... | (self, var):
self.variable_dict[var] = self.variable_dict.get(var, 0) + 1
def toDict(self):
return self.variable_dict
class Solver(ToDict):
SOLVER_TYPE_TAG = 'solver_type'
def __init__(self, problem_description, tester, *args, **kwargs):
raise NotImplementedError()
def solve... | inc_var | identifier_name |
base_types.py | """
Contains base data structures for defining graph constrained group testing problem,
and interfaces to operate on them.
Basic structure to exchange graph constrained group testing problem definition is :class:`Problem`.
It consists of enumeration of faulty elements, graph of links between elements and natural langu... |
ProblemGraph = collections.namedtuple("ProblemGraph", ["graph", "source", "sink"])
class ExperimentStatistics(object):
"""
Maintains statistics related with the experiment, for each problem and solver statistics object is gathered
"""
def __init__(self, rendererMapping):
self._renderers = ... | pass | identifier_body |
base_types.py | """
Contains base data structures for defining graph constrained group testing problem,
and interfaces to operate on them.
Basic structure to exchange graph constrained group testing problem definition is :class:`Problem`.
It consists of enumeration of faulty elements, graph of links between elements and natural langu... |
self.results = []
self.headers = set({})
def set_result(self, objectsMapping):
result = {}
for k, v in objectsMapping.iteritems():
rendered = self._render(k, v)
self._add_headers(rendered)
result.update(rendered)
self.results.append(res... | self._renderers[k] = lambda x: x.toDict() | conditional_block |
base_types.py | """
Contains base data structures for defining graph constrained group testing problem,
and interfaces to operate on them.
Basic structure to exchange graph constrained group testing problem definition is :class:`Problem`.
It consists of enumeration of faulty elements, graph of links between elements and natural langu... |
class SolverError(Exception):
pass
class GCGTSolver(Solver):
"""
Interface of classes implementing combinatorial group testing algorithm.
Problem description and tester object have to be inserted in constructor
"""
def __init__(self, problem_description, tester, *args, **kwargs):
"""... | :returns: set of nodes identified by algorithm as positive
:rtype: set
"""
raise NotImplementedError() | random_line_split |
base_behaviors.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 agreed to in writing, software
dist... |
def get_id_from_href(self, href):
"""Returns the id from reference.
The id must be the last item in the href.
:param href: The href containing the id.
:returns the id portion of the href
"""
item_id = None
if href and len(href) > 0:
base, item... | json_data = dict()
try:
json_data = response.json()
except ValueError as e:
self.LOG.exception(e)
self.LOG.error("Error converting response to JSON: %s", e.message)
self.LOG.error("Response Content: %s", response.content)
return json_data | identifier_body |
base_behaviors.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 agreed to in writing, software
dist... |
return item_id
| base, item_id = os.path.split(href) | conditional_block |
base_behaviors.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 agreed to in writing, software
dist... | json_data = response.json()
except ValueError as e:
self.LOG.exception(e)
self.LOG.error("Error converting response to JSON: %s", e.message)
self.LOG.error("Response Content: %s", response.content)
return json_data
def get_id_from_href(self, href):
... |
def get_json(self, response):
json_data = dict()
try: | random_line_split |
base_behaviors.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 agreed to in writing, software
dist... | (self, href):
"""Returns the id from reference.
The id must be the last item in the href.
:param href: The href containing the id.
:returns the id portion of the href
"""
item_id = None
if href and len(href) > 0:
base, item_id = os.path.split(href)
... | get_id_from_href | identifier_name |
coherence.rs | bool
{
debug!("impl_can_satisfy(\
impl1_def_id={:?}, \
impl2_def_id={:?})",
impl1_def_id,
impl2_def_id);
let selcx = &mut SelectionContext::intercrate(infcx);
infcx.probe(|_| {
overlap(selcx, impl1_def_id, impl2_def_id) || overlap(selcx, impl2_def_id, im... | <'a,'tcx>(selcx: &mut SelectionContext<'a,'tcx>,
impl_def_id: ast::DefId,
substs_fn: SubstsFn)
-> (ty::TraitRef<'tcx>,
Vec<PredicateObligation<'tcx>>)
{
let impl_su... | impl_trait_ref_and_oblig | identifier_name |
coherence.rs | bool
{
debug!("impl_can_satisfy(\
impl1_def_id={:?}, \
impl2_def_id={:?})",
impl1_def_id,
impl2_def_id);
let selcx = &mut SelectionContext::intercrate(infcx);
infcx.probe(|_| {
overlap(selcx, impl1_def_id, impl2_def_id) || overlap(selcx, impl2_def_id, im... | infer::Misc(DUMMY_SP),
a_trait_ref.to_poly_trait_ref(),
b_trait_ref.to_poly_trait_ref()) {
return false;
}
debug!("overlap: subtraitref check succeeded")... | {
debug!("overlap(a_def_id={:?}, b_def_id={:?})",
a_def_id,
b_def_id);
let (a_trait_ref, a_obligations) = impl_trait_ref_and_oblig(selcx,
a_def_id,
util::fresh_t... | identifier_body |
coherence.rs | bool
{
debug!("impl_can_satisfy(\
impl1_def_id={:?}, \
impl2_def_id={:?})",
impl1_def_id,
impl2_def_id);
let selcx = &mut SelectionContext::intercrate(infcx);
infcx.probe(|_| {
overlap(selcx, impl1_def_id, impl2_def_id) || overlap(selcx, impl2_def_id, im... | // uncovered type parameters.
let uncovered_tys = uncovered_tys(tcx, input_ty, infer_is_local);
for uncovered_ty in uncovered_tys {
if let Some(param) = uncovered_ty.walk().find(|t| is_type_parameter(t)) {
debug!("orphan_check_trait_ref: uncovered ... |
// First local input type. Check that there are no | random_line_split |
gingerAle.js | recipes['Fiery Ginger Ale (2L)'] = {
type: 'Fiery Ginger Ale (2L)',
volume: '2L',
brewTime: [
'2 days',
],
ingredients: [
'1.5 oz. finely grated fresh ginger (the younger the better; microplane suggested)',
'6 oz. table sugar', | 'StarSan soln.',
],
equipmentMisc: [
'2L PET bottle (i.e. plastic soda bottle)',
],
recipe: [
'Clean 2L PET bottle with StarSan soln.',
'Place ginger, sugar, and 1/2 cup of the water into a saucepan over medium-high heat. Stir until the sugar dissolves. Remove from heat, ... | '7.5 cups filtered water',
'1/8 teaspoon (should be around 750mg) champagne yeast (Red Star Premier Blanc formerly known as Pastuer Champagne)',
'2 tablespoons freshly squeezed lemon juice', | random_line_split |
main.rs | //! runec - Rune Console.
//!
//! Interactive shell that uses rune for user guided symbolic execution and
//! binary reasoning.
extern crate rune;
extern crate libsmt;
extern crate docopt;
extern crate rustc_serialize;
extern crate r2pipe;
extern crate r2api;
mod interact;
mod console;
use std::process::exit;
use do... | Usage:
runec [-p <path>] <file>
runec (-h | --help)
Options:
-h --help Show this screen.
-p Load a previous configuration of state
";
#[derive(Debug, Clone, RustcDecodable)]
struct Args {
flag_help: bool,
flag_project: bool,
arg_path... | random_line_split | |
main.rs | //! runec - Rune Console.
//!
//! Interactive shell that uses rune for user guided symbolic execution and
//! binary reasoning.
extern crate rune;
extern crate libsmt;
extern crate docopt;
extern crate rustc_serialize;
extern crate r2pipe;
extern crate r2api;
mod interact;
mod console;
use std::process::exit;
use do... | {
flag_help: bool,
flag_project: bool,
arg_path: Option<String>,
arg_file: Option<String>,
}
fn main() {
let args = Docopt::new(USAGE)
.and_then(|dopt| dopt.parse())
.unwrap_or_else(|e| e.exit());
if args.get_bool("-h") {
println!("{}", USAG... | Args | identifier_name |
main.rs | //! runec - Rune Console.
//!
//! Interactive shell that uses rune for user guided symbolic execution and
//! binary reasoning.
extern crate rune;
extern crate libsmt;
extern crate docopt;
extern crate rustc_serialize;
extern crate r2pipe;
extern crate r2api;
mod interact;
mod console;
use std::process::exit;
use do... | else {
is.add_const((key.clone(), val as u64));
}
},
Command::Exit => {
c.print_info("Thanks for using rune!");
exit(0);
},
Command::Invalid => {
c.print_error("Invalid command. Please tr... | {
is.set_start_addr(val as u64);
} | conditional_block |
users.authentication.server.controller.js | 'use strict';
var _ = require('lodash');
var errorHandler = require('../errors.server.controller');
var mongoose = require('mongoose');
var passport = require('passport');
var User = mongoose.model('User');
exports.signup = function(req, res) {
// For security measurement we remove the roles from the req.body objec... | if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
})(req, res, next);
};
exports.signout = function(req, res) {
req.logout();
res.redirect('/');
}; | random_line_split | |
users.authentication.server.controller.js | 'use strict';
var _ = require('lodash');
var errorHandler = require('../errors.server.controller');
var mongoose = require('mongoose');
var passport = require('passport');
var User = mongoose.model('User');
exports.signup = function(req, res) {
// For security measurement we remove the roles from the req.body objec... | else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
};
exports.signin = function(req, r... | {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} | conditional_block |
kakasi.py | #===============================================================================
import re
from untwisted.magic import sign
from channel import not_quiet
from runtime import later
import message
import util
import limit
import kakasi_lib
link, install, uninstall = util.LinkSet().triple()
#=========================... |
@link(('HELP', 'romaji'))
@link(('HELP', 'rj'))
def h_help_romaji(bot, reply, args):
reply('romaji TEXT')
reply('rj TEXT',
'Shows the Hepburn romanisation(s) of Japanese characters occurring in TEXT,'
' according to KAKASI <http://kakasi.namazu.org>. The command prefix may be'
' omitted, leaving j... | reply('romaji TEXT',
'Converts Japanese characters to romaji.') | identifier_body |
kakasi.py | #===============================================================================
import re
from untwisted.magic import sign
from channel import not_quiet
from runtime import later
import message
import util
import limit
import kakasi_lib
link, install, uninstall = util.LinkSet().triple()
#=========================... | (bot, reply, args):
reply('romaji TEXT',
'Converts Japanese characters to romaji.')
@link(('HELP', 'romaji'))
@link(('HELP', 'rj'))
def h_help_romaji(bot, reply, args):
reply('romaji TEXT')
reply('rj TEXT',
'Shows the Hepburn romanisation(s) of Japanese characters occurring in TEXT,'
' accordin... | h_help | identifier_name |
kakasi.py | #===============================================================================
import re
from untwisted.magic import sign
from channel import not_quiet
from runtime import later
import message
import util
import limit
import kakasi_lib
link, install, uninstall = util.LinkSet().triple()
#=========================... |
raw_reply = kakasi_lib.kakasi(msg)
if auto and len(raw_reply) > 200: return
reply = ('<%s> %s' % (id.nick, raw_reply)) if prefix and id else raw_reply
bot.send_msg(target, reply)
bot.drive('runtime.later', sign(
'PROXY_MSG', bot, id, target, raw_reply, **dict(kwds, no_kakasi=True)))
| return | conditional_block |
kakasi.py | #===============================================================================
import re
from untwisted.magic import sign
from channel import not_quiet
from runtime import later
import message
import util
import limit
import kakasi_lib
link, install, uninstall = util.LinkSet().triple()
#=========================... | reply = ('<%s> %s' % (id.nick, raw_reply)) if prefix and id else raw_reply
bot.send_msg(target, reply)
bot.drive('runtime.later', sign(
'PROXY_MSG', bot, id, target, raw_reply, **dict(kwds, no_kakasi=True))) | #===============================================================================
def kakasi(bot, id, target, msg, prefix=True, auto=False, **kwds):
if auto and not kakasi_lib.is_ja(msg): return
raw_reply = kakasi_lib.kakasi(msg)
if auto and len(raw_reply) > 200: return | random_line_split |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bytes!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = Buffere... | main | identifier_name |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
... | { proc_mode = true; } | conditional_block |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // run it("hell") and it("ello"), then return "llo"
fn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where
F: FnMut(&[u8]),
{
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(&bb[ii..(ii+nn)]);
ii += 1u;
}
return bb[(len - (nn - 1u))..len].to_vec()... | random_line_split | |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{:?} {:0.3}\n",
... | {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
} | identifier_body |
main.rs | #[macro_use] extern crate nickel;
extern crate config;
extern crate pulldown_cmark;
| use std::collections::HashMap;
use std::fs::File;
use std::io::{Read,BufReader, Error};
use config::reader;
use config::types::Config;
use pulldown_cmark::Parser;
use pulldown_cmark::html::push_html;
use nickel::*;
use nickel::extensions::Redirect;
fn main() {
let empty_default_config = Config::new(HashMap::new(... | use nickel::Nickel;
use std::path::Path; | random_line_split |
main.rs | #[macro_use] extern crate nickel;
extern crate config;
extern crate pulldown_cmark;
use nickel::Nickel;
use std::path::Path;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read,BufReader, Error};
use config::reader;
use config::types::Config;
use pulldown_cmark::Parser;
use pulldown_cmark::html::pus... | () {
let empty_default_config = Config::new(HashMap::new());
let configuration = reader::from_file(Path::new("Dokiofile")).unwrap_or(empty_default_config);
let listening_port = configuration.lookup_integer32_or("port", 3000);
let default_file = String::from(configuration.lookup_str_or("default_file", "... | main | identifier_name |
main.rs | #[macro_use] extern crate nickel;
extern crate config;
extern crate pulldown_cmark;
use nickel::Nickel;
use std::path::Path;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read,BufReader, Error};
use config::reader;
use config::types::Config;
use pulldown_cmark::Parser;
use pulldown_cmark::html::pus... | {
let file_path = format!(".{}", path.unwrap());
let file = File::open(Path::new(file_path.as_str()))?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
Ok(contents)
} | identifier_body | |
golden_outputs.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use goldenfile::Mint;
use std::{cell::RefCell, fmt::Debug, fs::File, io::Write, path::PathBuf};
pub const GOLDEN_DIR_PATH: &str = "goldens";
pub const EXT_NAME: &str = "exp";
pub(crate) struct GoldenOutputs {
#[allow(dead_code)]
... | () -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path
}
impl GoldenOutputs {
pub fn new(name: &str) -> Self {
let mut mint = Mint::new(golden_path());
let mut file_path = PathBuf::new();
file_path.push(name);
... | golden_path | identifier_name |
golden_outputs.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use goldenfile::Mint;
use std::{cell::RefCell, fmt::Debug, fs::File, io::Write, path::PathBuf};
pub const GOLDEN_DIR_PATH: &str = "goldens";
pub const EXT_NAME: &str = "exp";
pub(crate) struct GoldenOutputs {
#[allow(dead_code)]
... | fn golden_path() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path
}
impl GoldenOutputs {
pub fn new(name: &str) -> Self {
let mut mint = Mint::new(golden_path());
let mut file_path = PathBuf::new();
file_path.pus... | file: RefCell<File>,
}
| random_line_split |
golden_outputs.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use goldenfile::Mint;
use std::{cell::RefCell, fmt::Debug, fs::File, io::Write, path::PathBuf};
pub const GOLDEN_DIR_PATH: &str = "goldens";
pub const EXT_NAME: &str = "exp";
pub(crate) struct GoldenOutputs {
#[allow(dead_code)]
... |
impl GoldenOutputs {
pub fn new(name: &str) -> Self {
let mut mint = Mint::new(golden_path());
let mut file_path = PathBuf::new();
file_path.push(name);
let file = RefCell::new(
mint.new_goldenfile(file_path.with_extension(EXT_NAME))
.unwrap(),
)... | {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path
} | identifier_body |
test_nova.py | #!/usr/bin/env python
#
# Copyright (c) 2017 Hewlett Packard Enterprise, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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.apach... |
server1 = data.server['11111111-2222-3333-4444-555555555555']
server1_image = data.image[server1['image_id']]
class DwarfTestCase(utils.TestCase):
def setUp(self):
super(DwarfTestCase, self).setUp()
self.start_dwarf()
def tearDown(self):
self.stop_dwarf()
super(DwarfTestCa... | return os.path.join(os.path.dirname(__file__), 'data', filename) | identifier_body |
test_nova.py | #!/usr/bin/env python
#
# Copyright (c) 2017 Hewlett Packard Enterprise, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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.apach... | (stdout):
line = [l for l in stdout.split('\n') if l != '']
if ((line[0] == '-----BEGIN PRIVATE KEY-----' and
line[-1] == '-----END PRIVATE KEY-----')):
return stdout
return ''
def cwd(filename):
return os.path.join(os.path.dirname(__file__), 'data', filename)
server1 = data.server[... | verify_private_key | identifier_name |
test_nova.py | #!/usr/bin/env python
#
# Copyright (c) 2017 Hewlett Packard Enterprise, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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.apach... | def cwd(filename):
return os.path.join(os.path.dirname(__file__), 'data', filename)
server1 = data.server['11111111-2222-3333-4444-555555555555']
server1_image = data.image[server1['image_id']]
class DwarfTestCase(utils.TestCase):
def setUp(self):
super(DwarfTestCase, self).setUp()
self.sta... | random_line_split | |
test_nova.py | #!/usr/bin/env python
#
# Copyright (c) 2017 Hewlett Packard Enterprise, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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.apach... |
return ''
def cwd(filename):
return os.path.join(os.path.dirname(__file__), 'data', filename)
server1 = data.server['11111111-2222-3333-4444-555555555555']
server1_image = data.image[server1['image_id']]
class DwarfTestCase(utils.TestCase):
def setUp(self):
super(DwarfTestCase, self).setUp()... | return stdout | conditional_block |
fastaFormatter.py | #!/usr/bin/python
import sys
import os
import getopt
from textwrap import wrap
def main():
params = parseArgs()
if params.many2one:
seqs=dict()
for f in read_fasta(params.many2one):
seqs[f[0]] = f[1]
write_fasta(params.out, seqs)
elif params.one2many:
seqs=dict()
for f in read_fasta(params.one2many)... |
#Read samples as FASTA. Generator function
def read_fasta(fas):
if os.path.exists(fas):
with open(fas, 'r') as fh:
try:
contig = ""
seq = ""
for line in fh:
line = line.strip()
if not line:
continue
#print(line)
if line[0] == ">": #Found a header line
#If we already l... | with open(f, 'w') as fh:
try:
for samp in aln.keys():
if width:
ol = ">" + str(samp) + "\n"
chunks=wrap(aln[samp], width=width, break_on_hyphens=False, drop_whitespace=False)
for chunk in chunks:
ol=ol + str(chunk) + "\n"
else:
ol = ">" + str(samp) + "\n" + str(aln[samp]) + "\n"
... | identifier_body |
fastaFormatter.py | #!/usr/bin/python
import sys
import os
import getopt
from textwrap import wrap
def main(): | for f in read_fasta(params.many2one):
seqs[f[0]] = f[1]
write_fasta(params.out, seqs)
elif params.one2many:
seqs=dict()
for f in read_fasta(params.one2many):
seqs[f[0]] = f[1]
write_fasta(params.out, seqs, params.width)
#Function to write fasta-formatted sequences
def write_fasta(f, aln, width=None):
... | params = parseArgs()
if params.many2one:
seqs=dict() | random_line_split |
fastaFormatter.py | #!/usr/bin/python
import sys
import os
import getopt
from textwrap import wrap
def main():
params = parseArgs()
if params.many2one:
seqs=dict()
for f in read_fasta(params.many2one):
seqs[f[0]] = f[1]
write_fasta(params.out, seqs)
elif params.one2many:
seqs=dict()
for f in read_fasta(params.one2many)... |
elif opt=="many2one" or opt=="M":
self.many2one=arg
elif opt=="width" or opt=="w":
self.width=int(arg)
elif opt=="out" or opt=="o":
self.out=arg
else:
assert False, "Unhandled option %r"%opt
#Check manditory options are set
if not self.one2many and not self.many2one:
self.display_he... | self.one2many=arg | conditional_block |
fastaFormatter.py | #!/usr/bin/python
import sys
import os
import getopt
from textwrap import wrap
def main():
params = parseArgs()
if params.many2one:
seqs=dict()
for f in read_fasta(params.many2one):
seqs[f[0]] = f[1]
write_fasta(params.out, seqs)
elif params.one2many:
seqs=dict()
for f in read_fasta(params.one2many)... | (fas):
if os.path.exists(fas):
with open(fas, 'r') as fh:
try:
contig = ""
seq = ""
for line in fh:
line = line.strip()
if not line:
continue
#print(line)
if line[0] == ">": #Found a header line
#If we already loaded a contig, yield that contig and
#start loading ... | read_fasta | identifier_name |
field_textblockinput.js | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2013-2014 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
/**
* @license
* @fileoverview Visual blocks editor for App Inventor
* FieldTextBlockInput is a subclass of FieldTextInput
*
* @a... |
if(this.sourceBlock_ && this.sourceBlock_.outputConnection){
this.sourceBlock_.outputConnection.setCheck(this.sourceBlock_.outputConnection.check_)
}
Blockly.Field.prototype.setText.call(this, text);
}; | {
var validated = this.changeHandler_(text);
// If the new text is invalid, validation returns null.
// In this case we still want to display the illegal result.
if (validated !== null && validated !== undefined) {
text = validated;
}
} | conditional_block |
field_textblockinput.js | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2013-2014 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
/**
* @license
* @fileoverview Visual blocks editor for App Inventor
* FieldTextBlockInput is a subclass of FieldTextInput
*
* @a... | }; | random_line_split | |
run_tests.py | #!/usr/bin/env python
import os
import subprocess
import os.path as p
import sys
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
DIR_OF_YCMD_THIRD_PARTY = p.join( DIR_OF_THIRD_PARTY, 'ycmd', 'third_party' )
python_path = []
for folder in os.lis... | ():
print( 'Running flake8' )
subprocess.check_call( [
'flake8',
'--select=F,C9',
'--max-complexity=10',
p.join( DIR_OF_THIS_SCRIPT, 'python' )
] )
def ParseArguments():
parser = argparse.ArgumentParser()
parser.add_argument( '--skip-build', action = 'store_true',
help... | RunFlake8 | identifier_name |
run_tests.py | #!/usr/bin/env python
import os
import subprocess
import os.path as p
import sys
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
DIR_OF_YCMD_THIRD_PARTY = p.join( DIR_OF_THIRD_PARTY, 'ycmd', 'third_party' )
python_path = []
for folder in os.lis... | Main() | conditional_block | |
run_tests.py | #!/usr/bin/env python
import os
import subprocess
import os.path as p
import sys
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
DIR_OF_YCMD_THIRD_PARTY = p.join( DIR_OF_THIRD_PARTY, 'ycmd', 'third_party' )
python_path = []
for folder in os.lis... |
def ParseArguments():
parser = argparse.ArgumentParser()
parser.add_argument( '--skip-build', action = 'store_true',
help = 'Do not build ycmd before testing.' )
return parser.parse_known_args()
def BuildYcmdLibs( args ):
if not args.skip_build:
subprocess.check_call( [
sy... | print( 'Running flake8' )
subprocess.check_call( [
'flake8',
'--select=F,C9',
'--max-complexity=10',
p.join( DIR_OF_THIS_SCRIPT, 'python' )
] ) | identifier_body |
run_tests.py | #!/usr/bin/env python
import os
import subprocess
import os.path as p
import sys
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
DIR_OF_YCMD_THIRD_PARTY = p.join( DIR_OF_THIRD_PARTY, 'ycmd', 'third_party' )
python_path = []
for folder in os.lis... | BuildYcmdLibs( parsed_args )
NoseTests( extra_args )
if __name__ == "__main__":
Main() | def Main():
( parsed_args, extra_args ) = ParseArguments()
RunFlake8() | random_line_split |
calculator.rs | //! `Calculator` is an easy to use generic method of evaluating string expressions.
use super::*;
use polynomial::Polynomial;
/// `CalculationError` wraps parsing and evaluation errors
#[derive(Debug, PartialEq)]
pub enum CalculationError {
/// `ParsingError` returned from `TokensProcessor`
ParsingError(ParsingEr... | (e: ParsingError) -> CalculationError {
CalculationError::ParsingError(e)
}
}
/// Wraps `EvaluationError` in `CalculationError`
impl From<EvaluationError> for CalculationError {
fn from(e: EvaluationError) -> CalculationError {
CalculationError::EvaluationError(e)
}
}
/// Calculator is the easiest way o... | from | identifier_name |
calculator.rs | //! `Calculator` is an easy to use generic method of evaluating string expressions.
use super::*;
use polynomial::Polynomial;
/// `CalculationError` wraps parsing and evaluation errors
#[derive(Debug, PartialEq)]
pub enum CalculationError {
/// `ParsingError` returned from `TokensProcessor`
ParsingError(ParsingEr... | CalculationError::ParsingError(e)
}
}
/// Wraps `EvaluationError` in `CalculationError`
impl From<EvaluationError> for CalculationError {
fn from(e: EvaluationError) -> CalculationError {
CalculationError::EvaluationError(e)
}
}
/// Calculator is the easiest way of evaluating string expressions
/// into... | /// Wraps `ParsingError` in `CalculationError`
impl From<ParsingError> for CalculationError {
fn from(e: ParsingError) -> CalculationError { | random_line_split |
calculator.rs | //! `Calculator` is an easy to use generic method of evaluating string expressions.
use super::*;
use polynomial::Polynomial;
/// `CalculationError` wraps parsing and evaluation errors
#[derive(Debug, PartialEq)]
pub enum CalculationError {
/// `ParsingError` returned from `TokensProcessor`
ParsingError(ParsingEr... |
}
/// Calculator is the easiest way of evaluating string expressions
/// into a `Polynomial` value.
///
/// A struct which is a calculator (implements this trait) can easily
/// perform evaluation using given `StringProcessor`, `TokensProcessor`
/// and `TokensReducer`.
pub trait Calculator<T, P, E>
where T: String... | {
CalculationError::EvaluationError(e)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.