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 |
|---|---|---|---|---|
result.rs | mod checked {
// For .ln() and .sqrt()
use std::num::Float;
// Mathematical "errors" we want to catch
#[deriving(Show)]
pub enum MathError {
DivisionByZero,
NegativeLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64,... | else {
Ok(x.ln())
}
}
}
// `op(x, y)` === `sqrt(ln(x / y))`
fn op(x: f64, y: f64) -> f64 {
// This is a three level match pyramid!
match checked::div(x, y) {
Err(why) => panic!("{}", why),
Ok(ratio) => match checked::ln(ratio) {
Err(why) => panic!("{}", why)... | {
Err(MathError::NegativeLogarithm)
} | conditional_block |
result.rs | mod checked {
// For .ln() and .sqrt()
use std::num::Float;
// Mathematical "errors" we want to catch
#[deriving(Show)]
pub enum MathError {
DivisionByZero,
NegativeLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64,... | {
// Will this fail?
println!("{}", op(1.0, 10.0));
} | identifier_body | |
result.rs | mod checked {
// For .ln() and .sqrt()
use std::num::Float;
// Mathematical "errors" we want to catch
#[deriving(Show)]
pub enum MathError {
DivisionByZero,
NegativeLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64,... | (x: f64) -> MathResult {
if x < 0.0 {
Err(MathError::NegativeSquareRoot)
} else {
Ok(x.sqrt())
}
}
pub fn ln(x: f64) -> MathResult {
if x < 0.0 {
Err(MathError::NegativeLogarithm)
} else {
Ok(x.ln())
}
}
}
// `... | sqrt | identifier_name |
long-line.js | 'use strict';
var observatory = require('../lib/observatory');
var faker = require('faker');
var q = require('q');
function | (ms) {
var deferred = q.defer();
setTimeout(deferred.resolve, faker.random.number(ms || 2000));
return deferred.promise;
}
function createRandomTask() {
var task = observatory.add('These lines will need to wrap abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyzABCDEFGHIJK... | delay | identifier_name |
long-line.js | 'use strict';
var observatory = require('../lib/observatory');
var faker = require('faker');
var q = require('q');
function delay(ms) {
var deferred = q.defer();
setTimeout(deferred.resolve, faker.random.number(ms || 2000));
return deferred.promise;
}
function createRandomTask() |
function randomlyAddMore() {
createRandomTask();
delay()
.then(function(){
createRandomTask();
});
}
console.log(' ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽');
console.log(' Running Really long lines ');
console.log(' ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺');
randomly... | {
var task = observatory.add('These lines will need to wrap abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
var percent = 0;
function down... | identifier_body |
long-line.js | 'use strict';
var observatory = require('../lib/observatory');
var faker = require('faker');
var q = require('q');
function delay(ms) {
var deferred = q.defer();
setTimeout(deferred.resolve, faker.random.number(ms || 2000));
return deferred.promise;
}
function createRandomTask() {
var task = observa... | return delay(100).then(download);
}
download();
}
function randomlyAddMore() {
createRandomTask();
delay()
.then(function(){
createRandomTask();
});
}
console.log(' ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽');
console.log(' Running Really long lines ');
con... |
if (percent === 100) {
return task.done();
}
| random_line_split |
long-line.js | 'use strict';
var observatory = require('../lib/observatory');
var faker = require('faker');
var q = require('q');
function delay(ms) {
var deferred = q.defer();
setTimeout(deferred.resolve, faker.random.number(ms || 2000));
return deferred.promise;
}
function createRandomTask() {
var task = observa... |
return delay(100).then(download);
}
download();
}
function randomlyAddMore() {
createRandomTask();
delay()
.then(function(){
createRandomTask();
});
}
console.log(' ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽');
console.log(' Running Really long lines ');
c... | {
return task.done();
} | conditional_block |
exampleLoaderTemplate.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exampleLoaderTemplate.ui'
#
# Created: Sat Dec 17 23:46:27 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
... | Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.loadBtn.setText(QtGui.QApplication.translate("Form", "Load Example", None, QtGui.QApplication.UnicodeUTF8)) | identifier_body | |
exampleLoaderTemplate.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exampleLoaderTemplate.ui'
#
# Created: Sat Dec 17 23:46:27 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
... | self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.loadBtn.setT... | self.codeView.setFont(font)
self.codeView.setObjectName(_fromUtf8("codeView")) | random_line_split |
exampleLoaderTemplate.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exampleLoaderTemplate.ui'
#
# Created: Sat Dec 17 23:46:27 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
... | (self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.loadBtn.setText(QtGui.QApplication.translate("Form", "Load Example", None, QtGui.QApplication.UnicodeUTF8))
| retranslateUi | identifier_name |
ArticleShare.tsx | import {
Box,
EnvelopeIcon,
FacebookIcon,
Flex,
Tooltip,
TwitterIcon,
} from "@artsy/palette"
import { FC } from "react"
import { getENV } from "v2/Utils/getENV"
interface ArticleShareProps {
description: string | null
pathname: string | null
}
export const ArticleShare: FC<ArticleShareProps> = ({
d... | getENV("APP_URL"),
pathname && pathname.startsWith("/") ? pathname : `/${pathname || ""}`,
].join("")
return (
<Flex>
<Tooltip content="Share via email">
<Box
as="a"
display="flex"
aria-label="Share via email"
mr={1}
// @ts-ignore
... | pathname,
}) => {
const description = _description ?? "Artsy Editorial"
const url = [ | random_line_split |
angular-numeraljs.min.js | /**
* AngularJS filter for Numeral.js: number formatting as a filter |
"use strict";!function(a,b){"object"==typeof exports?module.exports=b(require("numeral")):"function"==typeof define&&define.amd?define(["numeral"],function(c){return a.ngNumeraljs=b(c)}):a.ngNumeraljs=b(a.numeral)}(this,function(a){return angular.module("ngNumeraljs",[]).provider("$numeraljsConfig",function(){var b={}... | * @version v2.0.1 - 2017-05-06
* @link https://github.com/baumandm/angular-numeraljs
* @author Dave Bauman <baumandm@gmail.com>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/ | random_line_split |
photo_shadow.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... |
else:
im = im.resize((size,im.size[1]*size/im.size[0]))
newimg = Image.new('RGB', (im.size[0]+8,im.size[1]+8), (255,255,255) )
draw = ImageDraw.Draw(newimg)
draw.rectangle((6, im.size[1]-5, im.size[0], im.size[1]+5), fill=(90,90,90))
draw.rectangle((im.size[0]-5, 6, im.size[0]+5, im.size[1... | im = im.resize((im.size[0]*size/im.size[1], size)) | conditional_block |
photo_shadow.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that i... | # | random_line_split |
photo_shadow.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... |
def __convert(from_file, to_file, size=95):
from PIL import Image, ImageDraw, ImageFilter
im = Image.open(from_file)
if float(im.size[1]/im.size[0])>2:
im = im.resize((im.size[0]*size/im.size[1], size))
else:
im = im.resize((size,im.size[1]*size/im.size[0]))
newimg = Image.new('RGB... | size = 95
__convert(from_file, to_file, size=95) | identifier_body |
photo_shadow.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | (from_file, to_file, size=95):
from PIL import Image, ImageDraw, ImageFilter
im = Image.open(from_file)
if float(im.size[1]/im.size[0])>2:
im = im.resize((im.size[0]*size/im.size[1], size))
else:
im = im.resize((size,im.size[1]*size/im.size[0]))
newimg = Image.new('RGB', (im.size[0]+... | __convert | identifier_name |
row-detail.directive.ngfactory.ts | /**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
import * as import0 from '../../../../src/components/row-detail/row-detail.directive';
import * as import1 from '@angular/core/src/change... |
}
ngDoCheck(view:import2.AppView<any>,el:any,throwOnChange:boolean):boolean {
var changed:any = this._changed;
this._changed = false;
return changed;
}
checkHost(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any,throwOnChange:boolean):void {
}
handleEvent(eventName:string,$eve... | {
this._changed = true;
this.context.template = currValue;
this._expr_1 = currValue;
} | conditional_block |
row-detail.directive.ngfactory.ts | /**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
import * as import0 from '../../../../src/components/row-detail/row-detail.directive';
import * as import1 from '@angular/core/src/change... | }
}
check_template(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void {
if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_1,currValue))) {
this._changed = true;
this.context.template = currValue;
this._expr_1 = currValue;
}
}
ngDoCheck(view:import2.AppVie... | this.context.rowHeight = currValue;
this._expr_0 = currValue; | random_line_split |
row-detail.directive.ngfactory.ts | /**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
import * as import0 from '../../../../src/components/row-detail/row-detail.directive';
import * as import1 from '@angular/core/src/change... | {
/*private*/ _eventHandler:Function;
context:import0.DatatableRowDetailDirective;
/*private*/ _changed:boolean;
/*private*/ _expr_0:any;
/*private*/ _expr_1:any;
subscription0:any;
constructor() {
this._changed = false;
this.context = new import0.DatatableRowDetailDirective();
this._expr_0 =... | Wrapper_DatatableRowDetailDirective | identifier_name |
row-detail.directive.ngfactory.ts | /**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
import * as import0 from '../../../../src/components/row-detail/row-detail.directive';
import * as import1 from '@angular/core/src/change... |
ngOnDestroy():void {
(this.subscription0 && this.subscription0.unsubscribe());
}
check_rowHeight(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void {
if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_0,currValue))) {
this._changed = true;
this.context.rowHeight = cu... | {
} | identifier_body |
primitives.rs | extern crate libc;
extern crate cpython;
extern crate rustypy;
use cpython::Python;
#[test]
fn primitives() |
let arg = true;
let answ = basics.rust_bind_bool_func(arg);
assert_eq!(false, answ);
let arg1 = String::from("String from Rust, ");
let arg2 = 10;
let answ = basics.other_prefix_tuple1((arg1, arg2));
assert_eq!((String::from("String from Rust, added this in Python!"), 20),
a... | {
use test_package::rustypy_pybind::PyModules;
let gil = Python::acquire_gil();
let py = gil.python();
let module: PyModules = PyModules::new(&py);
let basics = module.basics.primitives;
let arg = 1;
let answ = basics.rust_bind_int_func(arg);
assert_eq!(2, answ);
let arg = 0.5;
... | identifier_body |
primitives.rs | extern crate libc;
extern crate cpython;
extern crate rustypy;
use cpython::Python;
#[test]
fn | () {
use test_package::rustypy_pybind::PyModules;
let gil = Python::acquire_gil();
let py = gil.python();
let module: PyModules = PyModules::new(&py);
let basics = module.basics.primitives;
let arg = 1;
let answ = basics.rust_bind_int_func(arg);
assert_eq!(2, answ);
let arg = 0.5;... | primitives | identifier_name |
primitives.rs | extern crate libc;
extern crate cpython;
extern crate rustypy;
use cpython::Python;
#[test]
fn primitives() {
use test_package::rustypy_pybind::PyModules;
let gil = Python::acquire_gil();
let py = gil.python();
let module: PyModules = PyModules::new(&py);
let basics = module.basics.primitives;
... | answ);
let arg = true;
let answ = basics.rust_bind_bool_func(arg);
assert_eq!(false, answ);
let arg1 = String::from("String from Rust, ");
let arg2 = 10;
let answ = basics.other_prefix_tuple1((arg1, arg2));
assert_eq!((String::from("String from Rust, added this in Python!"),... |
let arg = String::from("String from Rust, ");
let answ = basics.rust_bind_str_func(arg);
assert_eq!(String::from("String from Rust, added this in Python!"), | random_line_split |
actions.py | def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
}
de... |
if test_repo.services:
model.data.result = RESULT_FAILED % ('Services model is not removed')
if not j.core.jobcontroller.db.runs.find(repo=test_repo.model.key):
model.data.result = RESULT_FAILED % ('Jobs are deleted after repository destroy')
except:
model.data.resul... | model.data.result = RESULT_FAILED % ('Actors model is not removed') | conditional_block |
actions.py | def init_actions_(service, args):
|
def test(job):
"""
Tests parsing of a bp with/without default values
"""
import sys
RESULT_OK = 'OK : %s'
RESULT_FAILED = 'FAILED : %s'
RESULT_ERROR = 'ERROR : %s %%s' % job.service.name
model = job.service.model
model.data.result = RESULT_OK % job.service.name
test_repo_p... | """
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
} | identifier_body |
actions.py | def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
}
de... | (job):
"""
Tests parsing of a bp with/without default values
"""
import sys
RESULT_OK = 'OK : %s'
RESULT_FAILED = 'FAILED : %s'
RESULT_ERROR = 'ERROR : %s %%s' % job.service.name
model = job.service.model
model.data.result = RESULT_OK % job.service.name
test_repo_path = j.sal.fs.... | test | identifier_name |
actions.py |
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
}
def test(job):
"""
Tests parsing of a... | def init_actions_(service, args):
""" | random_line_split | |
parseSTIX.py | '''
* Copyright (C) 2015 Tripwire, Inc.
*
* 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 wr... | os.makedirs(directory + '/' + sourceIP)
#Get CVE from STIX
stix_package = STIXPackage.from_xml(file)
for target in stix_package.exploit_targets:
for vuln in target.vulnerabilities:
print "CVE: " + vuln.cve_id
print "DESC:" + str(vuln.description)
vulnObject=str(vuln.description)
cve = vul... | directory='Results'
#Create results directory to store the raw output
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.exists(directory + '/' + sourceIP): | random_line_split |
parseSTIX.py | '''
* Copyright (C) 2015 Tripwire, Inc.
*
* 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 wr... |
#Get CVE from STIX
stix_package = STIXPackage.from_xml(file)
for target in stix_package.exploit_targets:
for vuln in target.vulnerabilities:
print "CVE: " + vuln.cve_id
print "DESC:" + str(vuln.description)
vulnObject=str(vuln.description)
cve = vuln.cve_id
if len(cve) > 0:
if len(vuln... | os.makedirs(directory + '/' + sourceIP) | conditional_block |
unique-pat-2.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 ... | } | random_line_split | |
unique-pat-2.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!(match bar::u(box Foo{a: 10, b: 40}) {
bar::u(box Foo{a: a, b: b}) => { a + (b as isize) }
_ => { 66 }
} == 50);
} | identifier_body | |
unique-pat-2.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 ... | { u(Box<Foo>), w(isize), }
pub fn main() {
assert!(match bar::u(box Foo{a: 10, b: 40}) {
bar::u(box Foo{a: a, b: b}) => { a + (b as isize) }
_ => { 66 }
} == 50);
}
| bar | identifier_name |
assignFilterToLayersAlgorithm.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
DsgTools
A QGIS plugin
Brazilian Army Cartographic Production Tools
-------------------
begin : 2019-04-26
git sha ... | ]
self.addParameter(
QgsProcessingParameterEnum(
self.BEHAVIOR,
self.tr('Behavior'),
options=self.modes,
defaultValue=0
)
)
self.addOutput(
QgsProcessingOutputMultipleLayer... | random_line_split | |
assignFilterToLayersAlgorithm.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
DsgTools
A QGIS plugin
Brazilian Army Cartographic Production Tools
-------------------
begin : 2019-04-26
git sha ... |
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr('Layer Management Algorithms')
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
... | """
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr('Assign Filter to Layers') | identifier_body |
assignFilterToLayersAlgorithm.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
DsgTools
A QGIS plugin
Brazilian Army Cartographic Production Tools
-------------------
begin : 2019-04-26
git sha ... |
filterExpression = self.adaptFilter(lyr, inputFilterExpression, behavior)
lyr.setSubsetString(filterExpression)
feedback.setProgress(current * stepSize)
return {self.OUTPUT: inputLyrList}
def adaptFilter(self, lyr, inputFilter, behavior):
"""
Adapts fil... | break | conditional_block |
assignFilterToLayersAlgorithm.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
DsgTools
A QGIS plugin
Brazilian Army Cartographic Production Tools
-------------------
begin : 2019-04-26
git sha ... | (self, string):
return QCoreApplication.translate('AssignFilterToLayersAlgorithm', string)
def createInstance(self):
return AssignFilterToLayersAlgorithm() | tr | identifier_name |
IgnoredExceptionsTest.py | ##########################################################################
#
# Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF TH... | # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | random_line_split |
IgnoredExceptionsTest.py | ##########################################################################
#
# Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | ( self ) :
def f( toRaise, toIgnore ) :
with IECore.IgnoredExceptions( toIgnore ) :
raise toRaise
self.assertRaises( RuntimeError, f, RuntimeError, KeyError )
self.assertRaises( RuntimeError, f, RuntimeError, ( KeyError, IndexError ) )
f( KeyError, KeyError )
f( KeyError, ( KeyError, IndexEr... | test | identifier_name |
IgnoredExceptionsTest.py | ##########################################################################
#
# Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | unittest.main() | conditional_block | |
IgnoredExceptionsTest.py | ##########################################################################
#
# Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... |
p = IECore.Parameterised( "" )
with IECore.IgnoredExceptions( Exception ) :
p["d"]
def testNoExceptions( self ) :
with IECore.IgnoredExceptions( Exception ) :
pass
if __name__ == "__main__":
unittest.main()
| def test( self ) :
def f( toRaise, toIgnore ) :
with IECore.IgnoredExceptions( toIgnore ) :
raise toRaise
self.assertRaises( RuntimeError, f, RuntimeError, KeyError )
self.assertRaises( RuntimeError, f, RuntimeError, ( KeyError, IndexError ) )
f( KeyError, KeyError )
f( KeyError, ( KeyError,... | identifier_body |
NewProjectModal.py | import os.path
from typing import *
from click import Context, get_current_context
from pros.common import ui
from pros.common.ui.interactive import application, components, parameters
from pros.conductor import Conductor
from .parameters import NonExistentProjectParameter
class | (application.Modal[None]):
targets = parameters.OptionParameter('v5', ['v5', 'cortex'])
kernel_versions = parameters.OptionParameter('latest', ['latest'])
install_default_libraries = parameters.BooleanParameter(True)
project_name = parameters.Parameter(None)
advanced_collapsed = parameters.BooleanP... | NewProjectModal | identifier_name |
NewProjectModal.py | import os.path
from typing import *
from click import Context, get_current_context
from pros.common import ui
from pros.common.ui.interactive import application, components, parameters
from pros.conductor import Conductor
from .parameters import NonExistentProjectParameter
class NewProjectModal(application.Modal[No... | self.directory = NonExistentProjectParameter(directory)
cb = self.targets.on_changed(self.target_changed, asynchronous=True)
cb(self.targets)
def target_changed(self, new_target):
templates = self.conductor.resolve_templates('kernel', target=new_target.value)
if len(templat... | self.click_ctx = ctx or get_current_context() | random_line_split |
NewProjectModal.py | import os.path
from typing import *
from click import Context, get_current_context
from pros.common import ui
from pros.common.ui.interactive import application, components, parameters
from pros.conductor import Conductor
from .parameters import NonExistentProjectParameter
class NewProjectModal(application.Modal[No... |
self.redraw()
def confirm(self, *args, **kwargs):
assert self.can_confirm
self.exit()
project = self.conductor.new_project(
path=self.directory.value,
target=self.targets.value,
version=self.kernel_versions.value,
no_default_libs=not ... | self.kernel_versions.options = ['latest'] + sorted({t.version for t in templates}, reverse=True) | conditional_block |
NewProjectModal.py | import os.path
from typing import *
from click import Context, get_current_context
from pros.common import ui
from pros.common.ui.interactive import application, components, parameters
from pros.conductor import Conductor
from .parameters import NonExistentProjectParameter
class NewProjectModal(application.Modal[No... |
@property
def can_confirm(self):
return self.directory.is_valid() and self.targets.is_valid() and self.kernel_versions.is_valid()
def build(self) -> Generator[components.Component, None, None]:
yield components.DirectorySelector('Project Directory', self.directory)
yield component... | assert self.can_confirm
self.exit()
project = self.conductor.new_project(
path=self.directory.value,
target=self.targets.value,
version=self.kernel_versions.value,
no_default_libs=not self.install_default_libraries.value,
project_name=self.proj... | identifier_body |
main.py | #!/bin/python2
import os, gzip, StringIO, time, csv, datetime
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from wtforms import Form, DecimalField, validators
class UpdateForm(Form):
weight = DecimalField('Weight', [validators.DataRequired()])
f... | (data):
values = []
for t in types:
values.append(str(data[t]))
filename = CSV_FILENAME
timestr = time.strftime("%Y%m%d-%H%M%S")
with open(filename, "a") as fh:
fh.write(','.join(values) + "," + timestr + "\n")
@app.route('/', methods=['GET', 'POST'])
def update():
form = Updat... | updateData | identifier_name |
main.py | #!/bin/python2
import os, gzip, StringIO, time, csv, datetime
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from wtforms import Form, DecimalField, validators
class UpdateForm(Form):
weight = DecimalField('Weight', [validators.DataRequired()])
f... | app.run(host='0.0.0.0') | conditional_block | |
main.py | #!/bin/python2
import os, gzip, StringIO, time, csv, datetime
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from wtforms import Form, DecimalField, validators
class UpdateForm(Form):
weight = DecimalField('Weight', [validators.DataRequired()])
f... |
@app.route('/', methods=['GET', 'POST'])
def update():
form = UpdateForm(request.form)
if request.method == 'POST' and form.validate():
updateData(form.data)
return redirect('stats')
return render_template('update.html', form=form)
if __name__ == "__main__":
app.run(host='0.0.0.0')
| values = []
for t in types:
values.append(str(data[t]))
filename = CSV_FILENAME
timestr = time.strftime("%Y%m%d-%H%M%S")
with open(filename, "a") as fh:
fh.write(','.join(values) + "," + timestr + "\n") | identifier_body |
main.py | #!/bin/python2
import os, gzip, StringIO, time, csv, datetime
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename | weight = DecimalField('Weight', [validators.DataRequired()])
fat = DecimalField('Body fat', [validators.DataRequired()])
water = DecimalField('Body water', [validators.DataRequired()])
muscle = DecimalField('Muscle', [validators.DataRequired()])
bonemass = DecimalField('Bone mass', [validators.DataR... | from wtforms import Form, DecimalField, validators
class UpdateForm(Form): | random_line_split |
board.rs | #[derive(Debug, Copy, Clone, PartialEq)]
pub enum PieceColor {
White,
Black,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GamePiece {
pub color: PieceColor,
pub crowned: bool,
}
impl GamePiece {
pub fn new(color: PieceColor) -> GamePiece {
GamePiece {
color,
... |
jumps.into_iter()
}
pub fn move_targets_from(&self) -> impl Iterator<Item = Coordinate> {
let mut moves = Vec::new();
let Coordinate(x, y) = *self;
if x >= 1 {
moves.push(Coordinate(x - 1, y + 1));
}
moves.push(Coordinate(x + 1, y + 1));
if y... | {
jumps.push(Coordinate(x - 2, y + 2));
} | conditional_block |
board.rs | #[derive(Debug, Copy, Clone, PartialEq)]
pub enum PieceColor {
White,
Black,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GamePiece {
pub color: PieceColor,
pub crowned: bool,
}
impl GamePiece {
pub fn new(color: PieceColor) -> GamePiece {
GamePiece {
color,
... | (from: (usize, usize), to: (usize, usize)) -> Move {
Move {
from: Coordinate(from.0, from.1),
to: Coordinate(to.0, to.1),
}
}
}
| new | identifier_name |
board.rs | #[derive(Debug, Copy, Clone, PartialEq)]
pub enum PieceColor {
White,
Black,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GamePiece {
pub color: PieceColor,
pub crowned: bool,
}
impl GamePiece {
pub fn new(color: PieceColor) -> GamePiece {
GamePiece {
color,
... |
}
| {
Move {
from: Coordinate(from.0, from.1),
to: Coordinate(to.0, to.1),
}
} | identifier_body |
board.rs | #[derive(Debug, Copy, Clone, PartialEq)]
pub enum PieceColor {
White,
Black,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GamePiece {
pub color: PieceColor,
pub crowned: bool,
}
impl GamePiece {
pub fn new(color: PieceColor) -> GamePiece {
GamePiece {
color,
... |
#[derive(Debug, Clone, PartialEq, Copy)]
pub struct Coordinate(pub usize, pub usize);
impl Coordinate {
pub fn on_board(self) -> bool {
let Coordinate(x, y) = self;
x <= 7 && y <= 7
}
pub fn jump_targets_from(&self) -> impl Iterator<Item = Coordinate> {
let mut jumps = Vec::new();
... | }
}
} | random_line_split |
test_models.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil import relativedelta
from odoo import fields, models, api
class LeadTest(models.Model):
_name = "base.automation.lead.test"
_description = "Automated Rule Test"
name = fields.Char(string='Sub... | (models.Model):
_name = "base.automation.line.test"
_description = "Automated Rule Line Test"
name = fields.Char()
lead_id = fields.Many2one('base.automation.lead.test', ondelete='cascade')
user_id = fields.Many2one('res.users')
| LineTest | identifier_name |
test_models.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil import relativedelta
from odoo import fields, models, api
class LeadTest(models.Model):
_name = "base.automation.lead.test"
_description = "Automated Rule Test"
name = fields.Char(string='Sub... |
else:
record.deadline = fields.Datetime.from_string(record.create_date) + relativedelta.relativedelta(days=3)
class LineTest(models.Model):
_name = "base.automation.line.test"
_description = "Automated Rule Line Test"
name = fields.Char()
lead_id = fields.Many2one('base.au... | record.deadline = False | conditional_block |
test_models.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil import relativedelta
from odoo import fields, models, api
class LeadTest(models.Model):
_name = "base.automation.lead.test"
_description = "Automated Rule Test"
name = fields.Char(string='Sub... | name = fields.Char()
lead_id = fields.Many2one('base.automation.lead.test', ondelete='cascade')
user_id = fields.Many2one('res.users') | _description = "Automated Rule Line Test"
| random_line_split |
test_models.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil import relativedelta
from odoo import fields, models, api
class LeadTest(models.Model):
| for record in self:
if not record.priority:
record.deadline = False
else:
record.deadline = fields.Datetime.from_string(record.create_date) + relativedelta.relativedelta(days=3)
class LineTest(models.Model):
_name = "base.automation.line.test"
_d... | _name = "base.automation.lead.test"
_description = "Automated Rule Test"
name = fields.Char(string='Subject', required=True, index=True)
user_id = fields.Many2one('res.users', string='Responsible')
state = fields.Selection([('draft', 'New'), ('cancel', 'Cancelled'), ('open', 'In Progress'),
... | identifier_body |
APSync_module.py | # A template for APSync process based modules
from multiprocessing import Process, Event
import threading
import time
import signal, select
import traceback
import setproctitle
from APSyncFramework.utils.common_utils import PeriodicEvent
from APSyncFramework.utils.json_utils import ping, json_wrap_with_target
from APSy... |
print self.name, 'main finished'
def main(self):
pass
def in_queue_handling(self, lock=None):
while not self.needs_unloading.is_set():
(inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1)
for s in inputready:
... | try:
self.main()
except:
print ("FATAL: module ({0}) exited while multiprocessing".format(self.name))
traceback.print_exc()
# TODO: logging here | conditional_block |
APSync_module.py | # A template for APSync process based modules
from multiprocessing import Process, Event
import threading
import time
import signal, select
import traceback
import setproctitle
from APSyncFramework.utils.common_utils import PeriodicEvent
from APSyncFramework.utils.json_utils import ping, json_wrap_with_target
from APSy... | (self, in_queue, out_queue, name, description = None):
super(APModule, self).__init__()
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
self.daemon = True
self.config_list= [] # overwrite this list
self.config_changed... | __init__ | identifier_name |
APSync_module.py | # A template for APSync process based modules
from multiprocessing import Process, Event
import threading
import time
import signal, select
import traceback
import setproctitle
from APSyncFramework.utils.common_utils import PeriodicEvent
from APSyncFramework.utils.json_utils import ping, json_wrap_with_target
from APSy... | else:
# do something useful with the data...
self.process_in_queue_data(data)
self.ping.trigger()
print self.name, 'in queue finished'
def process_in_queue_data(self, data):
pass
def log(self, message,... | if isinstance(data, Unload):
self.unload() | random_line_split |
APSync_module.py | # A template for APSync process based modules
from multiprocessing import Process, Event
import threading
import time
import signal, select
import traceback
import setproctitle
from APSyncFramework.utils.common_utils import PeriodicEvent
from APSyncFramework.utils.json_utils import ping, json_wrap_with_target
from APSy... |
def unload_callback(self):
''' overload to perform any module specific cleanup'''
pass
def run(self):
if self.in_queue_thread is not None:
self.in_queue_thread.start()
while not self.needs_unloading.is_set():
try:
self.ma... | print self.name, 'called unload'
self.unload_callback()
self.needs_unloading.set() | identifier_body |
bytecode.rs | use std::io::{Error, LineWriter, Write};
type Offset = usize;
/// Subset of values that can be initialised when a chunk is created.
/// They will be turned into proper values when the VM accesses them.
#[derive(Debug)]
pub enum Constant {
Number(f64),
Bool(bool),
Nil,
String(String),
}
type Line = usiz... | } else {
line = chunk.lines[i];
try!(write!(out, "{:4}", line));
}
try!(write!(out, " "));
try!{disassemble_instruction(instruction, chunk, out)};
}
Ok(())
} | // Using the OpCode enum all the opcodes have the same size.
// It is not space-efficient, but for now it's fine
try!(write!(out, "{:04}", i));
if line == chunk.lines[i] {
try!(write!(out, " |")); | random_line_split |
bytecode.rs | use std::io::{Error, LineWriter, Write};
type Offset = usize;
/// Subset of values that can be initialised when a chunk is created.
/// They will be turned into proper values when the VM accesses them.
#[derive(Debug)]
pub enum Constant {
Number(f64),
Bool(bool),
Nil,
String(String),
}
type Line = usiz... | {
instructions: Vec<OpCode>,
values: Vec<Constant>,
lines: Vec<Line>,
}
impl Chunk {
pub fn get(&self, index: usize) -> OpCode {
self.instructions[index]
}
pub fn get_value(&self, index: usize) -> &Constant {
&self.values[index]
}
/// Adds a new instruction to the chu... | Chunk | identifier_name |
view.py | # Webhooks for external integrations.
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.models import get_client
from zerver.lib.actions import check_send_stream_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import... | (deploy_number, deploy_url, build_number, build_url, server_name, result)
else: # should never get here
content = u"%s: %s\n" % (event, result)
content += "!avatar(%s) [`%s`](%s): %s" % (author_email, commit_id[:7],
commit_url, message)... | deploy_number = payload["number"]
server_name = payload["server_name"]
content = u"[deploy %s](%s) of [build %s](%s) on server %s: %s\n" % \ | random_line_split |
view.py | # Webhooks for external integrations.
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.models import get_client
from zerver.lib.actions import check_send_stream_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import... | (request, user_profile,
payload=REQ(argument_type='body'),
stream=REQ(default='builds')):
# type: (HttpRequest, UserProfile, Dict[str, Any], str) -> HttpResponse
# semaphore only gives the last commit, even if there were multiple commits
# since the last ... | api_semaphore_webhook | identifier_name |
view.py | # Webhooks for external integrations.
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.models import get_client
from zerver.lib.actions import check_send_stream_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import... |
content += "!avatar(%s) [`%s`](%s): %s" % (author_email, commit_id[:7],
commit_url, message)
subject = u"%s/%s" % (project_name, branch_name)
check_send_stream_message(user_profile, request.client, stream, subject, content)
return json_success()
| content = u"%s: %s\n" % (event, result) | conditional_block |
view.py | # Webhooks for external integrations.
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.models import get_client
from zerver.lib.actions import check_send_stream_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import... | content = u"[deploy %s](%s) of [build %s](%s) on server %s: %s\n" % \
(deploy_number, deploy_url, build_number, build_url, server_name, result)
else: # should never get here
content = u"%s: %s\n" % (event, result)
content += "!avatar(%s) [`%s`](%s): %s" % (author_email, comm... | branch_name = payload["branch_name"]
project_name = payload["project_name"]
result = payload["result"]
event = payload["event"]
commit_id = payload["commit"]["id"]
commit_url = payload["commit"]["url"]
author_email = payload["commit"]["author_email"]
message = payload["commit"]["message"]
... | identifier_body |
systemjs.config.js | /**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
// map tells the System loader where to look for things
var map = {
'compiled': 'compiled', // 'dist',
'@angular': 'node_modules/@... | }
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
};
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex ... | random_line_split | |
systemjs.config.js | /**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
// map tells the System loader where to look for things
var map = {
'compiled': 'compiled', // 'dist',
'@angular': 'node_modules/@... |
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
};
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : pac... | {
packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
} | identifier_body |
systemjs.config.js | /**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
// map tells the System loader where to look for things
var map = {
'compiled': 'compiled', // 'dist',
'@angular': 'node_modules/@... | (pkgName) {
packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
};
// Most environments should use UMD; some (Karm... | packIndex | identifier_name |
conftest.py | """
Uses sphinx's pytest fixture to run builds
usage:
.. code-block:: python
from ipypublish.sphinx.tests import get_test_source_dir
@pytest.mark.sphinx(
buildername='html',
srcdir=get_test_source_dir('notebook'))
def test_basic(app, status, warning, get_sphinx_app_output):
app.... | ():
""" remove all build directories from the test folder
"""
srcdirs = pathlib.Path(get_test_source_dir())
for entry in srcdirs.iterdir(): # type: pathlib.Path
if entry.is_dir() and entry.joinpath("_build").exists():
shutil.rmtree(str(entry.joinpath("_build")))
@pytest.fixture
de... | remove_sphinx_builds | identifier_name |
conftest.py | """
Uses sphinx's pytest fixture to run builds
usage:
.. code-block:: python
from ipypublish.sphinx.tests import get_test_source_dir
@pytest.mark.sphinx(
buildername='html',
srcdir=get_test_source_dir('notebook'))
def test_basic(app, status, warning, get_sphinx_app_output):
app.... |
@pytest.fixture
def get_sphinx_app_output():
def read(
app,
buildername="html",
filename="contents.html",
encoding="utf-8",
extract_body=False,
remove_scripts=False,
):
outpath = path(os.path.join(str(app.srcdir), "_build", buildername, filename))
... | """ remove all build directories from the test folder
"""
srcdirs = pathlib.Path(get_test_source_dir())
for entry in srcdirs.iterdir(): # type: pathlib.Path
if entry.is_dir() and entry.joinpath("_build").exists():
shutil.rmtree(str(entry.joinpath("_build"))) | identifier_body |
conftest.py | """
Uses sphinx's pytest fixture to run builds
usage:
.. code-block:: python
from ipypublish.sphinx.tests import get_test_source_dir
@pytest.mark.sphinx(
buildername='html',
srcdir=get_test_source_dir('notebook'))
def test_basic(app, status, warning, get_sphinx_app_output):
app.... |
@pytest.fixture
def get_sphinx_app_output():
def read(
app,
buildername="html",
filename="contents.html",
encoding="utf-8",
extract_body=False,
remove_scripts=False,
):
outpath = path(os.path.join(str(app.srcdir), "_build", buildername, filename))
... | if entry.is_dir() and entry.joinpath("_build").exists():
shutil.rmtree(str(entry.joinpath("_build"))) | conditional_block |
conftest.py | """
Uses sphinx's pytest fixture to run builds
usage:
.. code-block:: python
from ipypublish.sphinx.tests import get_test_source_dir
@pytest.mark.sphinx(
buildername='html',
srcdir=get_test_source_dir('notebook'))
def test_basic(app, status, warning, get_sphinx_app_output):
app.... |
parameters available to parse to ``@pytest.mark.sphinx``:
- buildername='html'
- srcdir=None
- testroot='root' (only used if srcdir not set)
- freshenv=False
- confoverrides=None
- status=None
- warning=None
- tags=None
- docutilsconf=None
"""
import os
import shutil
import re
import pytest
from sphinx.testing.path... | assert 'build succeeded' in status.getvalue() # Build succeeded
warnings = warning.getvalue().strip()
assert warnings == ""
output = get_sphinx_app_output(app, buildername='html') | random_line_split |
letter_frequency.rs | // Implements http://rosettacode.org/wiki/Letter_frequency
#[cfg(not(test))]
use std::io::fs::File;
#[cfg(not(test))]
use std::io::BufferedReader;
use std::collections::HashMap;
fn count_chars<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> {
let mut map: HashMap<char, uint> = HashMap::new();
for lett... |
#[test]
fn test_empty() {
let map = count_chars("".chars());
assert!(map.len() == 0);
}
#[test]
fn test_basic() {
let map = count_chars("aaaabbbbc".chars());
assert!(map.len() == 3);
assert!(*map.get(&'a') == 4);
assert!(*map.get(&'b') == 4);
assert!(*map.get(&'c') == 1);
}
| {
let file = File::open(&Path::new("resources/unixdict.txt"));
let mut reader = BufferedReader::new(file);
println!("{}", count_chars(reader.chars().map(|c| c.unwrap())));
} | identifier_body |
letter_frequency.rs | // Implements http://rosettacode.org/wiki/Letter_frequency
#[cfg(not(test))]
use std::io::fs::File;
#[cfg(not(test))]
use std::io::BufferedReader;
use std::collections::HashMap;
fn | <T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> {
let mut map: HashMap<char, uint> = HashMap::new();
for letter in chars {
map.insert_or_update_with(letter, 1, |_, count| *count += 1);
}
map
}
#[cfg(not(test))]
fn main() {
let file = File::open(&Path::new("resources/unixdict.txt"))... | count_chars | identifier_name |
letter_frequency.rs | // Implements http://rosettacode.org/wiki/Letter_frequency
#[cfg(not(test))]
use std::io::fs::File;
#[cfg(not(test))]
use std::io::BufferedReader;
use std::collections::HashMap;
fn count_chars<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> {
let mut map: HashMap<char, uint> = HashMap::new();
for lett... | let file = File::open(&Path::new("resources/unixdict.txt"));
let mut reader = BufferedReader::new(file);
println!("{}", count_chars(reader.chars().map(|c| c.unwrap())));
}
#[test]
fn test_empty() {
let map = count_chars("".chars());
assert!(map.len() == 0);
}
#[test]
fn test_basic() {
let map... | }
#[cfg(not(test))]
fn main() { | random_line_split |
MessageHeader.js | import cx from 'classnames'
import _ from 'lodash'
import React, { PropTypes } from 'react'
import {
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A message can contain a header.
*/
function MessageHeader(props) {
const { children, className, ... | }
MessageHeader.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.itemShorthand,
}
M... | type: META.TYPES.COLLECTION, | random_line_split |
MessageHeader.js | import cx from 'classnames'
import _ from 'lodash'
import React, { PropTypes } from 'react'
import {
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A message can contain a header.
*/
function MessageHeader(props) |
MessageHeader._meta = {
name: 'MessageHeader',
parent: 'Message',
type: META.TYPES.COLLECTION,
}
MessageHeader.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: Pr... | {
const { children, className, content } = props
const classes = cx('header', className)
const rest = getUnhandledProps(MessageHeader, props)
const ElementType = getElementType(MessageHeader, props)
return (
<ElementType {...rest} className={classes}>
{_.isNil(children) ? content : children}
</... | identifier_body |
MessageHeader.js | import cx from 'classnames'
import _ from 'lodash'
import React, { PropTypes } from 'react'
import {
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A message can contain a header.
*/
function | (props) {
const { children, className, content } = props
const classes = cx('header', className)
const rest = getUnhandledProps(MessageHeader, props)
const ElementType = getElementType(MessageHeader, props)
return (
<ElementType {...rest} className={classes}>
{_.isNil(children) ? content : children... | MessageHeader | identifier_name |
local_settings.py | import os
import pymongo
import imp
# django stuff
reference_data_dir = '../data/reference_data'
#DEBUG = True
#COMPRESS_ENABLED = False
GENERATED_FILES_DIR = os.path.join(os.path.dirname(__file__), 'generated_files')
MEDIA_ROOT = os.path.join(GENERATED_FILES_DIR , 'media/')
DATABASES = {
'default': {
... |
DEFAULT_CONTROL_COHORT = 'controls'
CONTROL_COHORTS = [
{
'slug': 'controls',
'vcf': '',
},
]
UPLOADED_PEDIGREE_FILE_RECIPIENTS = []
COVERAGE_DB = _conn['xbrowse_coverage']
PROJECT_DATASTORE_DB = _conn['xbrowse_proj_store']
CNV_STORE_DB_NAME = 'xbrowse_cnvs'
CUSTOM_POPULATIONS_DB = _conn['... | random_line_split | |
Defaults-test.tsx | /*
* SonarQube
* Copyright (C) 2009-2019 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 of the License, o... | });
it('should render several qualifiers for default organization', () => {
const sample = { ...SAMPLE, defaultFor: ['TRK', 'VW'] };
const organization: T.Organization = { isDefault: true, key: 'org', name: 'org' };
const output = shallow(<Defaults organization={organization} template={sample} />);
expect(outp... | it('should render several qualifiers', () => {
const sample = { ...SAMPLE, defaultFor: ['TRK', 'VW'] };
const output = shallow(<Defaults organization={undefined} template={sample} />);
expect(output).toMatchSnapshot(); | random_line_split |
Versioning.js | let path = require('path');
let objectValues = require('lodash').values;
let File = require('./File');
class Versioning {
/**
* Create a new Versioning instance.
*
* @param {Array} manualFiles
* @param {object} manifest
* @param {string} publicPath
*/
constructor(manualFiles = []... | () {
this.manualFiles.forEach(file => file.version());
return this;
}
/**
* The user may optionally add extra files to be
* versioned. Here, we'll manually add those to
* Mix's manifest file.
*/
addManualFilesToManifest() {
this.manualFiles.forEach(file => this... | writeHashedFiles | identifier_name |
Versioning.js | let path = require('path');
let objectValues = require('lodash').values;
let File = require('./File');
class Versioning {
/**
* Create a new Versioning instance.
*
* @param {Array} manualFiles
* @param {object} manifest
* @param {string} publicPath
*/
constructor(manualFiles = []... |
/**
* Create all hashed files requested by the user,
* when they called mix.version(['file']);
*/
writeHashedFiles() {
this.manualFiles.forEach(file => file.version());
return this;
}
/**
* The user may optionally add extra files to be
* versioned. Here, we'... | });
});
return this;
} | random_line_split |
Versioning.js | let path = require('path');
let objectValues = require('lodash').values;
let File = require('./File');
class Versioning {
/**
* Create a new Versioning instance.
*
* @param {Array} manualFiles
* @param {object} manifest
* @param {string} publicPath
*/
constructor(manualFiles = []... |
/**
* Replace all old hashed files with the new versions.
*/
prune() {
this.writeHashedFiles().addManualFilesToManifest();
let cachedFiles = objectValues(this.manifest.cache);
let currentFiles = objectValues(this.manifest.get());
cachedFiles
.filter(fil... | {
this.manualFiles.forEach(file => this.manifest.add(file));
} | identifier_body |
loading.js | import './chunk-1fafdf15.js';
import { merge } from './helpers.js';
import { V as VueInstance } from './chunk-bd4264c6.js';
import { r as registerComponent, a as registerComponentProgrammatic, u as use } from './chunk-cca88db8.js';
import './chunk-b9bdb0e4.js';
import { L as Loading } from './chunk-1d4d79a1.js';
export... | propsData: propsData
});
}
};
var Plugin = {
install: function install(Vue) {
localVueInstance = Vue;
registerComponent(Vue, Loading);
registerComponentProgrammatic(Vue, 'loading', LoadingProgrammatic);
}
};
use(Plugin);
export default Plugin;
export { LoadingProgrammatic }; | var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : localVueInstance || VueInstance;
var LoadingComponent = vm.extend(Loading);
return new LoadingComponent({
el: document.createElement('div'), | random_line_split |
htmllinkelement.rs | : MutNullableDom<CSSStyleSheet>,
/// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts>
parser_inserted: Cell<bool>,
/// The number of loads that this link element has triggered (could be more
/// than one because of imports) and have not yet finished.
pending_loads: C... | handle_favicon_url | identifier_name | |
htmllinkelement.rs | loads have failed.
any_failed_load: Cell<bool>,
/// A monotonically increasing counter that keeps track of which stylesheet to apply.
request_generation_id: Cell<RequestGenerationId>,
}
impl HTMLLinkElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
docu... | {
let msg = EmbedderMsg::NewFavicon(url.clone());
window.send_to_embedder(msg);
} | conditional_block | |
htmllinkelement.rs | cast(), &local_name!("rel"));
match attr.local_name() {
&local_name!("href") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
} else if is_favicon(&rel) {
let sizes = get_attr(self.upcast(), &local... | {
reflect_cross_origin_attribute(self.upcast::<Element>())
} | identifier_body | |
htmllinkelement.rs | use crate::stylesheet_loader::{StylesheetContextSource, StylesheetLoader, StylesheetOwner};
use cssparser::{Parser as CssParser, ParserInput};
use dom_struct::dom_struct;
use embedder_traits::EmbedderMsg;
use html5ever::{LocalName, Prefix};
use net_traits::ReferrerPolicy;
use servo_arc::Arc;
use std::borrow::ToOwned;
u... | random_line_split | ||
default_draw_state.rs | use draw_state::state::*;
use DrawState;
static DEFAULT_DRAW_STATE: &'static DrawState =
&DrawState {
primitive: Primitive {
front_face: FrontFace::CounterClockwise,
method: RasterMethod::Fill(
CullFace::Nothing
),
offset: None,
},
... | () -> &'static DrawState {
DEFAULT_DRAW_STATE
}
| default_draw_state | identifier_name |
default_draw_state.rs | use draw_state::state::*;
use DrawState;
static DEFAULT_DRAW_STATE: &'static DrawState =
&DrawState {
primitive: Primitive {
front_face: FrontFace::CounterClockwise,
method: RasterMethod::Fill(
CullFace::Nothing
),
offset: None,
},
... | {
DEFAULT_DRAW_STATE
} | identifier_body | |
default_draw_state.rs | use draw_state::state::*;
use DrawState;
static DEFAULT_DRAW_STATE: &'static DrawState =
&DrawState {
primitive: Primitive {
front_face: FrontFace::CounterClockwise,
method: RasterMethod::Fill(
CullFace::Nothing
),
offset: None,
},
... | } | random_line_split | |
dispatch.py | # Copyright 2017-2020 The GPflow Contributors. 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 appli... | conditional._gpflow_internal_register = conditional.register
# type-ignore below is because mypy doesn't like it when we assign to a function.
conditional.register = deprecated( # type: ignore
reason="Registering new implementations of conditional() is deprecated. "
"Instead, create your own subclass of gpflo... | from deprecated import deprecated
from ..utilities import Dispatcher
conditional = Dispatcher("conditional") | random_line_split |
__init__.py | """Hello World API implemented using Google Cloud Endpoints.
Defined here are the ProtoRPC messages needed to define Schemas for methods
as well as those methods defined in an API.
"""
import endpoints
from protorpc import messages, message_types, remote # TODO remove messages and message types when possible
from go... | reminders = message_types.DateTimeField(6, repeated=True)
# Task : is a note
# Note
sub_notes = messages.MessageField('Note', 7, repeated=True)
# Image : is a file
# File
# A URL to a file. The file can probably be served by the datastore.
files = messages.BytesField(8, ... | color = messages.BytesField(4, default='#ffffff')
# Attach
# Due Date
due_date = message_types.DateTimeField(5)
# Reminder | random_line_split |
__init__.py | """Hello World API implemented using Google Cloud Endpoints.
Defined here are the ProtoRPC messages needed to define Schemas for methods
as well as those methods defined in an API.
"""
import endpoints
from protorpc import messages, message_types, remote # TODO remove messages and message types when possible
from go... | (self, note):
note.owner = endpoints.get_current_user()
note.put()
return note
@Note.query_method(user_required=True,
query_fields=('limit', 'order', 'pageToken'),
path='notes', http_method='GET', name='notes.list')
def notes_list(self, quer... | note_add | identifier_name |
__init__.py | """Hello World API implemented using Google Cloud Endpoints.
Defined here are the ProtoRPC messages needed to define Schemas for methods
as well as those methods defined in an API.
"""
import endpoints
from protorpc import messages, message_types, remote # TODO remove messages and message types when possible
from go... |
"""
class NoteMessage(messages.Message):
title = messages.StringField(1)
content = messages.StringField(2)
# Hotness
hotness = messages.IntegerField(3, default=0)
# Color
color = messages.BytesField(4, default='#ffffff')
# Attach
# Due Date
due_date = message_types.DateTimeFiel... | title = ndb.StringProperty()
content = ndb.StringProperty()
date_created = ndb.DateTimeProperty(auto_now_add=True)
owner = ndb.UserProperty() | identifier_body |
lib.rs | to test for performance and correctness.
//!
//! # Examples
//! ```
//! use dexter::*;
//! struct ExamplePublisher;
//!
//! impl Publisher<Vec<char>, String, String> for ExamplePublisher {
//! fn publish(&mut self, result: ExperimentResult<String, String>) {
//! println!("{:#?}", result);
//! }
//!
//!... | ///
/// Returns the result of the current subject closure.
pub fn carry_out<Pub: Publisher<P, Cr, Nr>>(mut self, mut param: P, publisher: &mut Pub) -> Cr {
if !publisher.enabled() {
return (self.current)(¶m);
}
if let Some(mut setup) = self.setup {
param =... | self.ignore_if = Some(Box::new(ignore_if));
self
}
/// Carry out the experiment given a parameter and a publisher. | random_line_split |
lib.rs | to test for performance and correctness.
//!
//! # Examples
//! ```
//! use dexter::*;
//! struct ExamplePublisher;
//!
//! impl Publisher<Vec<char>, String, String> for ExamplePublisher {
//! fn publish(&mut self, result: ExperimentResult<String, String>) {
//! println!("{:#?}", result);
//! }
//!
//!... | ;
let comparison = publisher.compare(¤t_val.as_ref().unwrap(), &new_val.as_ref().unwrap());
publisher.publish(ExperimentResult::new(
self.name,
SubjectResult::new(current_duration as f64 * 1e-9, ¤t_val.as_ref().unwrap()),
SubjectResult::new(new_duration ... | {
false
} | conditional_block |
lib.rs | to test for performance and correctness.
//!
//! # Examples
//! ```
//! use dexter::*;
//! struct ExamplePublisher;
//!
//! impl Publisher<Vec<char>, String, String> for ExamplePublisher {
//! fn publish(&mut self, result: ExperimentResult<String, String>) {
//! println!("{:#?}", result);
//! }
//!
//!... | <S>(mut self, setup: S) -> Self
where S: FnMut(P) -> P + 'a {
self.setup = Some(Box::new(setup));
self
}
/// Adds a check step that will disable the experiment in certain cases.
///
/// If the passed closure returns false when passed the experiment's parameter, then the
... | setup | identifier_name |
in_queue.test.ts | /*
* Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice... | asyncQueue.push(['setVisitorCookieTimeout', { p: 7 }]);
asyncQueue.push(['trackPageView']);
expect(output).toEqual(7);
});
it('Set UserId to String, null and undefined', () => {
asyncQueue.push(['setUserId', 'snow123']);
expect(userId).toEqual('snow123');
asyncQueue.push(['setUserId', null... | it('Make a proxy, Function originally stored in asyncQueue is executed when asyncQueue becomes an AsyncQueueProxy', () => {
expect(output).toEqual(15);
});
it('Add to asyncQueue after conversion, Function added to asyncQueue after it becomes an AsyncQueueProxy is executed', () => { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.