file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
url.validator.ts | import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
export function urlValidator(control: AbstractControl): ValidationErrors {
if (Validators.required(control) != null) {
return null;
} | } |
const v: string = control.value;
/* tslint:disable */
return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.... | random_line_split |
url.validator.ts | import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
export function | (control: AbstractControl): ValidationErrors {
if (Validators.required(control) != null) {
return null;
}
const v: string = control.value;
/* tslint:disable */
return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?... | urlValidator | identifier_name |
url.validator.ts | import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
export function urlValidator(control: AbstractControl): ValidationErrors {
if (Validators.required(control) != null) |
const v: string = control.value;
/* tslint:disable */
return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\... | {
return null;
} | conditional_block |
new_task.rs | use lapin::{options::*, types::FieldTable, BasicProperties, Connection, ConnectionProperties};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().skip(1).collect();
let message = match args.len() {
0 => b"hello".to_vec(),
_ => args.joi... | } | random_line_split | |
new_task.rs | use lapin::{options::*, types::FieldTable, BasicProperties, Connection, ConnectionProperties};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> | {
let args: Vec<_> = std::env::args().skip(1).collect();
let message = match args.len() {
0 => b"hello".to_vec(),
_ => args.join(" ").into_bytes(),
};
let addr = "amqp://127.0.0.1:5672";
let conn = Connection::connect(addr, ConnectionProperties::default()).await?;
let channel = ... | identifier_body | |
new_task.rs | use lapin::{options::*, types::FieldTable, BasicProperties, Connection, ConnectionProperties};
#[tokio::main]
async fn | () -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().skip(1).collect();
let message = match args.len() {
0 => b"hello".to_vec(),
_ => args.join(" ").into_bytes(),
};
let addr = "amqp://127.0.0.1:5672";
let conn = Connection::connect(addr, ConnectionProp... | main | identifier_name |
buffer.ts | // Specifically test buffer module regression.
import {
Buffer as ImportedBuffer,
SlowBuffer as ImportedSlowBuffer,
transcode,
TranscodeEncoding,
constants,
kMaxLength,
kStringMaxLength,
Blob,
} from 'buffer';
const utf8Buffer = new Buffer('test');
const base64Buffer = new Buffer('', 'b... | ;
buf = Buffer.from(pseudoString);
buf = Buffer.from(pseudoString, "utf-8");
// $ExpectError
Buffer.from(pseudoString, 1, 2);
const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } };
buf = Buffer.from(pseudoArrayBuf, 1, 1);
}
// Class Method: Buffer.alloc(size[, fill[, encoding]])
{... | return "Hello"; }} | identifier_body |
buffer.ts | // Specifically test buffer module regression.
import {
Buffer as ImportedBuffer,
SlowBuffer as ImportedSlowBuffer,
transcode,
TranscodeEncoding,
constants,
kMaxLength,
kStringMaxLength,
Blob,
} from 'buffer';
const utf8Buffer = new Buffer('test');
const base64Buffer = new Buffer('', 'b... | ) { return Buffer.from([1, 2, 3]); } };
let buf: Buffer = Buffer.from(pseudoBuf);
const pseudoString = { valueOf() { return "Hello"; }};
buf = Buffer.from(pseudoString);
buf = Buffer.from(pseudoString, "utf-8");
// $ExpectError
Buffer.from(pseudoString, 1, 2);
const pseudoArrayBuf = { valueO... | alueOf( | identifier_name |
buffer.ts | // Specifically test buffer module regression.
import {
Buffer as ImportedBuffer,
SlowBuffer as ImportedSlowBuffer,
transcode,
TranscodeEncoding,
constants,
kMaxLength,
kStringMaxLength,
Blob,
} from 'buffer';
const utf8Buffer = new Buffer('test');
const base64Buffer = new Buffer('', 'b... | blob.type; // $ExpectType string
blob.arrayBuffer(); // $ExpectType Promise<ArrayBuffer>
blob.text(); // $ExpectType Promise<string>
blob.slice(); // $ExpectType Blob
blob.slice(1); // $ExpectType Blob
blob.slice(1, 2); // $ExpectType Blob
blob.slice(1, 2, 'other'); // $ExpectType Blob
}; | type: 'application/javascript',
encoding: 'base64',
});
blob.size; // $ExpectType number | random_line_split |
buffer.ts | // Specifically test buffer module regression.
import {
Buffer as ImportedBuffer,
SlowBuffer as ImportedSlowBuffer,
transcode,
TranscodeEncoding,
constants,
kMaxLength,
kStringMaxLength,
Blob,
} from 'buffer';
const utf8Buffer = new Buffer('test');
const base64Buffer = new Buffer('', 'b... |
// write* methods return offsets.
const b = new Buffer(16);
let result: number = b.writeUInt32LE(0, 0);
result = b.writeUInt16LE(0, 4);
result = b.writeUInt8(0, 6);
result = b.writeInt8(0, 7);
result = b.writeDoubleLE(0, 8);
result = b.write('asd');
result = b.write('asd', 'hex');
result = b.write('asd', 123, 'hex');
... |
a.writeUInt8(3, 4);
}
| conditional_block |
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# 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... | "author": "OdooMRP team,"
"AvanzOSC,"
"Serv. Tecnol. Avanzados - Pedro M. Baeza",
"website": "http://www.odoomrp.com",
"contributors": [
"Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>",
"Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
"Ana Juaristi <... | "depends": [
"stock",
"product_packaging_through_attributes",
], | random_line_split |
backbonemixin.js | /* Taken from a very informative blogpost by Eldar Djafarov:
* http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/
*/
(function() {
'use strict';
module.exports = {
/* Forces an update when the underlying Backbone model instance has
* changed. Users will have to implement getBackboneModels().... | * valueLink={this.bindTo(model, attribute)} */
return {
value: model.get(key),
requestChange: function(value){
model.set(key, value);
}.bind(this)
};
}
};
})(); | },
bindTo: function(model, key){
/* Allows for two-way databinding for Backbone models.
* Use by passing it as a 'valueLink' property, e.g.: | random_line_split |
backbonemixin.js | /* Taken from a very informative blogpost by Eldar Djafarov:
* http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/
*/
(function() {
'use strict';
module.exports = {
/* Forces an update when the underlying Backbone model instance has
* changed. Users will have to implement getBackboneModels().... |
},
bindTo: function(model, key){
/* Allows for two-way databinding for Backbone models.
* Use by passing it as a 'valueLink' property, e.g.:
* valueLink={this.bindTo(model, attribute)} */
return {
value: model.get(key),
requestChange: function(value){
m... | {
var updater = function() {
try {
this.forceUpdate();
} catch(e) {
// This means the component is already being updated somewhere
// else, so we just silently go on with our business.
// This is most likely due to some AJAX callback that alrea... | conditional_block |
planets.js | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercia... |
return outerRadius;
}
| {
outerRadius = planets[planet]["radius"];
if (planet === SATURN) {
outerRadius =+ saturnOuterRadius;
} else if (planet === URANUS) {
outerRadius =+ uranusOuterRadius;
} else if (planet === SUN) {
outerRadius = planets[planet]["radius"] / 100;
... | conditional_block |
planets.js | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercia... |
function getOuterRadius(planet) {
var outerRadius = solarDistance;
if (planet !== SOLAR_SYSTEM) {
outerRadius = planets[planet]["radius"];
if (planet === SATURN) {
outerRadius =+ saturnOuterRadius;
} else if (planet === URANUS) {
outerRadius =+ uranusOuterRadius... | {
// Planet Data
// radius - planet radius
// tilt - planet axis angle
// N1/2 - longitude of the ascending node
// i1/2 - inclination to the ecliptic (plane of the Earth's orbit)
// w1/2 - argument of perihelion
// a1/2 - semi-major axis, or mean distance from Sun
// e1/2 - eccentricit... | identifier_body |
planets.js | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercia... | a1: 30.05826, a2: 0.00000003313, e1: 0.008606, e2: 0.00000000215,
M1: 260.2471, M2: 0.005995147, period: 0.6713, x: 0, y: 0, z: 0,
roll: 0, centerOfOrbit: SUN
};
planets.push(neptune);
var moon = {
radius: 1.5424, tilt: 28.32, N1: 125.1228, N2: -0.0529538083,
i1: 5.14... | i1: 1.7700, i2: -0.000000255, w1: 272.8461, w2: 0.000006027, | random_line_split |
planets.js | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercia... | () {
// Planet Data
// radius - planet radius
// tilt - planet axis angle
// N1/2 - longitude of the ascending node
// i1/2 - inclination to the ecliptic (plane of the Earth's orbit)
// w1/2 - argument of perihelion
// a1/2 - semi-major axis, or mean distance from Sun
// e1/2 - eccentri... | loadPlanetData | identifier_name |
index.js | 'use strict';
var define = require('define-property');
var Target = require('expand-target');
var utils = require('expand-utils');
var use = require('use');
/**
* Create a new Task with the given `options`
*
* ```js
* var task = new Task({cwd: 'src'});
* task.addTargets({
* site: {src: ['*.hbs']},
* blog: ... | this.addTarget(key, val);
} else {
this[key] = val;
}
}
}
return this;
};
/**
* Add a single target to the task, while also normalizing src-dest mappings and
* expanding glob patterns in the target.
*
* ```js
* task.addTarget('foo', {
* src: 'templates/*.hbs',
* dest: 'si... | if (utils.isTarget(val)) { | random_line_split |
index.js | 'use strict';
var define = require('define-property');
var Target = require('expand-target');
var utils = require('expand-utils');
var use = require('use');
/**
* Create a new Task with the given `options`
*
* ```js
* var task = new Task({cwd: 'src'});
* task.addTargets({
* site: {src: ['*.hbs']},
* blog: ... |
}
}
return this;
};
/**
* Add a single target to the task, while also normalizing src-dest mappings and
* expanding glob patterns in the target.
*
* ```js
* task.addTarget('foo', {
* src: 'templates/*.hbs',
* dest: 'site'
* });
*
* // other configurations are possible
* task.addTarget('foo', {
... | {
this[key] = val;
} | conditional_block |
index.js | 'use strict';
var define = require('define-property');
var Target = require('expand-target');
var utils = require('expand-utils');
var use = require('use');
/**
* Create a new Task with the given `options`
*
* ```js
* var task = new Task({cwd: 'src'});
* task.addTargets({
* site: {src: ['*.hbs']},
* blog: ... | (options) {
if (!(this instanceof Task)) {
return new Task(options);
}
utils.is(this, 'task');
use(this);
this.options = options || {};
if (utils.isTask(options)) {
this.options = {};
this.addTargets(options);
return this;
}
}
/**
* Add targets to the task, while also normalizing src-d... | Task | identifier_name |
index.js | 'use strict';
var define = require('define-property');
var Target = require('expand-target');
var utils = require('expand-utils');
var use = require('use');
/**
* Create a new Task with the given `options`
*
* ```js
* var task = new Task({cwd: 'src'});
* task.addTargets({
* site: {src: ['*.hbs']},
* blog: ... |
/**
* Add targets to the task, while also normalizing src-dest mappings and
* expanding glob patterns in each target.
*
* ```js
* task.addTargets({
* site: {src: '*.hbs', dest: 'templates/'},
* docs: {src: '*.md', dest: 'content/'}
* });
* ```
* @param {Object} `task` Task object where each key is a tar... | {
if (!(this instanceof Task)) {
return new Task(options);
}
utils.is(this, 'task');
use(this);
this.options = options || {};
if (utils.isTask(options)) {
this.options = {};
this.addTargets(options);
return this;
}
} | identifier_body |
Clue.js | import React from 'react';
import styled from 'styled-components';
import Item from './Item';
import parchment from '../assets/parchment.png';
import chest from '../assets/chest.png';
const Container = styled.div`
background: url(${parchment});
position: relative;
height: 286px;
width: 303px;
align-self: center;... | <Chest />
</Container>
);
export default Clue; | <Item key={reward.id} id={reward.id} amount={reward.amount} />
))}
</Items> | random_line_split |
Touch.ts | /*
* Touch
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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
*... |
if('ontouchstart' in window)
{
Touch._IOS_disable(stage);
}
else if(window.navigator['msPointerEnabled'] || window.navigator["pointerEnabled"])
{
Touch._IE_disable(stage);
}
}
// Private static methods:
/**
* @method _IOS_enable
* @protected
* @param {Stage} stage
* @static
**/
public... | {
return;
} | conditional_block |
Touch.ts | /*
* Touch
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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
*... | (stage, id, e, x, y)
{
if(!stage.__touch.pointers[id])
{
return;
}
stage._handlePointerMove(id, e, x, y);
}
/**
* @method _handleEnd
* @param {Stage} stage
* @param {String|Number} id
* @param {Object} e
* @protected
**/
public static _handleEnd(stage, id, e)
{
// TODO: cancel should be h... | _handleMove | identifier_name |
Touch.ts | /*
* Touch
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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
*... | else
{
canvas.addEventListener("pointerdown", f, false);
window.addEventListener("pointermove", f, false);
window.addEventListener("pointerup", f, false);
window.addEventListener("pointercancel", f, false);
if(stage.__touch.preventDefault)
{
canvas.style.touchAction = "none";
}
}
stage... | } | random_line_split |
Touch.ts | /*
* Touch
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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
*... |
/**
* Enables touch interaction for the specified EaselJS {{#crossLink "Stage"}}{{/crossLink}}. Currently supports iOS
* (and compatible browsers, such as modern Android browsers), and IE10/11. Supports both single touch and
* multi-touch modes. Extends the EaselJS {{#crossLink "MouseEvent"}}{{/crossLink}} mod... | {
return ('ontouchstart' in window) // iOS
|| (window.navigator['msPointerEnabled'] && window.navigator['msMaxTouchPoints'] > 0) // IE10
|| (window.navigator['pointerEnabled'] && window.navigator['maxTouchPoints'] > 0); // IE11+
} | identifier_body |
__init__.py | # Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implemen... | exec "import %s as cat" % category
microcode += cat.microcode | conditional_block | |
__init__.py | # Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implemen... | # notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior writ... | # redistributions in binary form must reproduce the above copyright | random_line_split |
shortSort.js | /** | * @param {integer} end - pixel to end at
*/
Jimp.prototype.shortsort = function shortsort(dir, start, end, cb) {
var width = this.bitmap.width,
height = this.bitmap.height,
data = new Uint32Array(this.bitmap.data),
cut, mm;
if (nullOrUndefined(start) && nullOrUndefined(end)) {
mm = randMinMax(0, width * height... | * shortsort
* @param {integer} start - pixel to start at | random_line_split |
devscan.py | #!/usr/bin/env python
#
# Copyright (C) Citrix Systems Inc.
#
# 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; version 2.1 only.
#
# This program is distributed in the hope that it will ... |
for key in vdis:
obj = vdis[key]
d = dom.createElement("BlockDevice")
e.appendChild(d)
for attr in ['path','numpaths','SCSIid','vendor','serial','size','adapter','channel','id','lun','hba','mpp']:
try:
aval = getattr(obj, attr)
... | vdis[obj.SCSIid] = obj | conditional_block |
devscan.py | #!/usr/bin/env python
#
# Copyright (C) Citrix Systems Inc.
#
# 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; version 2.1 only.
#
# This program is distributed in the hope that it will ... |
return dom.toprettyxml()
def check_iscsi(adapter):
ret = False
str = "host%s" % adapter
try:
filename = os.path.join('/sys/class/scsi_host',str,'proc_name')
f = open(filename, 'r')
if f.readline().find("iscsi_tcp") != -1:
ret = True
except:
pass
retu... | 'ipaddress', 'port_speed',
'port_state']) | random_line_split |
devscan.py | #!/usr/bin/env python
#
# Copyright (C) Citrix Systems Inc.
#
# 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; version 2.1 only.
#
# This program is distributed in the hope that it will ... | (device_dir):
devs = glob.glob(os.path.join(device_dir, 'block/*'))
if len(devs):
# prune path to extract the device name
return os.path.basename(devs[0])
else:
return INVALID_DEVICE_NAME
def _extract_dev(device_dir, procname, host, target):
"""Returns device name and creates di... | _get_block_device_name_with_kernel_3x | identifier_name |
devscan.py | #!/usr/bin/env python
#
# Copyright (C) Citrix Systems Inc.
#
# 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; version 2.1 only.
#
# This program is distributed in the hope that it will ... |
def match_hbadevs(s, filterstr):
driver_name = _get_driver_name(s)
if match_host(s) and not match_blacklist(driver_name) \
and ( filterstr == "any" or match_filterstr(filterstr, driver_name) ):
return driver_name
else:
return ""
def match_blacklist(driver_name):
return re.... | devs = scsiutil.cacheSCSIidentifiers()
mppdict = {}
for dev in devs:
item = devs[dev]
if item[1] == id:
arr = scsiutil._genArrayIdentifier(dev)
if not len(arr):
continue
try:
cmd = ['/usr/sbin/mppUtil', '-a']
for... | identifier_body |
class_redis_cache_test.js | var class_redis_cache_test =
[
[ "__construct", "class_redis_cache_test.html#ae22c12eb0d136f444b6c9c0735f70382", null ],
[ "testArray", "class_redis_cache_test.html#a76100cea2dba0b01bfffb70a193dfb9f", null ],
[ "testGet", "class_redis_cache_test.html#afb35249bbbb21b7eac20b12d6f5a8739", null ],
[ "testHa... | [ "testRemove", "class_redis_cache_test.html#a10b3034f21731f5a6507dbb5207097cf", null ]
]; | [ "testLeveledArray", "class_redis_cache_test.html#a56c8a7551fcbda565b8f81bd9a9e3b57", null ],
[ "testReinitializedGet", "class_redis_cache_test.html#addb63e1b14cdbfcdc65837dff633f7f2", null ],
[ "testReinitializedHas", "class_redis_cache_test.html#a39dc99ba8e9efe29f3939ecbe99210be", null ], | random_line_split |
beta_bernoulli_map.py | #!/usr/bin/env python
"""
A simple coin flipping example. The model is written in TensorFlow.
Inspired by Stan's toy example.
Probability model
Prior: Beta
Likelihood: Bernoulli
Inference: Maximum a posteriori
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_f... |
ed.set_seed(42)
model = BetaBernoulli()
data = {'x': np.array([0, 1, 0, 0, 0, 0, 0, 0, 0, 1])}
params = tf.sigmoid(tf.Variable(tf.random_normal([1])))
inference = ed.MAP(model, data, params=params)
inference.run(n_iter=100, n_print=10)
| log_prior = beta.logpdf(zs, a=1.0, b=1.0)
log_lik = tf.pack([tf.reduce_sum(bernoulli.logpmf(xs['x'], z))
for z in tf.unpack(zs)])
return log_lik + log_prior | identifier_body |
beta_bernoulli_map.py | #!/usr/bin/env python
"""
A simple coin flipping example. The model is written in TensorFlow.
Inspired by Stan's toy example.
Probability model
Prior: Beta
Likelihood: Bernoulli
Inference: Maximum a posteriori
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_f... | self.n_vars = 1
def log_prob(self, xs, zs):
log_prior = beta.logpdf(zs, a=1.0, b=1.0)
log_lik = tf.pack([tf.reduce_sum(bernoulli.logpmf(xs['x'], z))
for z in tf.unpack(zs)])
return log_lik + log_prior
ed.set_seed(42)
model = BetaBernoulli()
data = {'x': np.array([0, 1, 0, 0, ... | class BetaBernoulli:
"""p(x, z) = Bernoulli(x | z) * Beta(z | 1, 1)"""
def __init__(self): | random_line_split |
beta_bernoulli_map.py | #!/usr/bin/env python
"""
A simple coin flipping example. The model is written in TensorFlow.
Inspired by Stan's toy example.
Probability model
Prior: Beta
Likelihood: Bernoulli
Inference: Maximum a posteriori
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_f... | :
"""p(x, z) = Bernoulli(x | z) * Beta(z | 1, 1)"""
def __init__(self):
self.n_vars = 1
def log_prob(self, xs, zs):
log_prior = beta.logpdf(zs, a=1.0, b=1.0)
log_lik = tf.pack([tf.reduce_sum(bernoulli.logpmf(xs['x'], z))
for z in tf.unpack(zs)])
return log_lik + log_prior
... | BetaBernoulli | identifier_name |
serialization.ts | /*
* Copyright 2019 ThoughtWorks, 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 agr... | encrypted_password?: string;
}
export interface ScmAttributesJSON extends BaseAttributesJSON, UsernamePasswordJSON {
destination?: string;
}
export interface GitMaterialAttributesJSON extends ScmAttributesJSON {
url: string;
branch: string;
}
export interface SvnMaterialAttributesJSON extends ScmAttributesJS... | username?: string;
password?: string; | random_line_split |
03.py | #!/usr/bin/env python
# Python 3 required
# THIS TAKES WAAAAY TO LONG. ONLY SOLVED IT BY LETTING IT RUN
# OVERNIGHT ACCIDENTALLY :/
import locale
import sys
import math
import timeit
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59... |
for i in range(PRIMES[-1], int(math.sqrt(num)), 2):
if num % i == 0:
return False
return True
def is_prime2(num):
k = 3
while k*k <= num:
if num % k == 0:
return False
k += 2
return True
def main():
num = int(sys.argv[1])
print("Factoring %s" % locale.format("%d", num, grouping=True))
if num... | if i >= num:
break
if num % i == 0:
#print ("%d is divisible by %d" % (num, i))
return False | conditional_block |
03.py | #!/usr/bin/env python
# Python 3 required
# THIS TAKES WAAAAY TO LONG. ONLY SOLVED IT BY LETTING IT RUN
# OVERNIGHT ACCIDENTALLY :/
import locale
import sys
import math
import timeit
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59... | ():
num = int(sys.argv[1])
print("Factoring %s" % locale.format("%d", num, grouping=True))
if num % 2 == 0:
prime_factors = [2]
else:
prime_factors = []
pager = 0
for i in range(3, num, 2):
if num % i == 0:
print ("Factor: %s" % locale.format("%d", i, grouping=True))
if is_prime2(i):
prime_fac... | main | identifier_name |
03.py | #!/usr/bin/env python
# Python 3 required
# THIS TAKES WAAAAY TO LONG. ONLY SOLVED IT BY LETTING IT RUN
# OVERNIGHT ACCIDENTALLY :/
import locale |
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199]
def is_prime(num):
for i in PRIMES:
if i >= num:
break
if num % i == 0:... | import sys
import math
import timeit
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') | random_line_split |
03.py | #!/usr/bin/env python
# Python 3 required
# THIS TAKES WAAAAY TO LONG. ONLY SOLVED IT BY LETTING IT RUN
# OVERNIGHT ACCIDENTALLY :/
import locale
import sys
import math
import timeit
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59... |
def is_prime2(num):
k = 3
while k*k <= num:
if num % k == 0:
return False
k += 2
return True
def main():
num = int(sys.argv[1])
print("Factoring %s" % locale.format("%d", num, grouping=True))
if num % 2 == 0:
prime_factors = [2]
else:
prime_factors = []
pager = 0
for i in range(3, num, 2):
... | for i in PRIMES:
if i >= num:
break
if num % i == 0:
#print ("%d is divisible by %d" % (num, i))
return False
for i in range(PRIMES[-1], int(math.sqrt(num)), 2):
if num % i == 0:
return False
return True | identifier_body |
app.py | #!/usr/bin/python2.5
#
# Copyright 2009 Google 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... | (self):
xml = self._robot.GetProfileJson()
response = webob.Response(content_type='application/json', body=xml)
response.cache_control = 'Private' # XXX
return response
def jsonrpc(self, req):
json_body = req.body
logging.info('Incoming: %s', json_body)
context, events = robot_abstract.... | profile | identifier_name |
app.py | #!/usr/bin/python2.5
#
# Copyright 2009 Google 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... |
def __call__(self, environ, start_response):
req = webob.Request(environ)
if req.path_info == '/_wave/capabilities.xml' and req.method == 'GET':
response = self.capabilities()
elif req.path_info == '/_wave/robot/profile' and req.method == 'GET':
response = self.profile()
elif req.path_in... | json_body = req.body
logging.info('Incoming: %s', json_body)
context, events = robot_abstract.ParseJSONBody(json_body)
for event in events:
self._robot.HandleEvent(event, context)
json_response = robot_abstract.SerializeContext(
context, self._robot.version)
logging.info('Outgoing: %... | identifier_body |
app.py | #!/usr/bin/python2.5
#
# Copyright 2009 Google 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... |
return response(environ, start_response)
| response = webob.exc.HTTPNotFound() | conditional_block |
app.py | #!/usr/bin/python2.5
#
# Copyright 2009 Google 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... |
class RobotMiddleware(object):
"""WSGI middleware that routes /_wave/ requests to a robot wsgi app."""
def __init__(self, robot_app, main_app):
self._robot_app = robot_app
self._main_app = main_app
def __call__(self, environ, start_response):
path = environ['PATH_INFO']
if path.startswith('/_wa... | random_line_split | |
users.js | var express = require('express');
var config = require('../profile.json');
var router = express.Router();
// var Accounts = require(config.models_factary)("account");
var main = require(config.main_mp2);
var login = require(config.login_mp);
var customer = require(config.customer_mp);
router.get('/', main.authorize_s... | module.exports = router; | random_line_split | |
test_with_shap.py | import numpy as np
import xgboost as xgb
import pytest
try:
import shap
except ImportError:
shap = None
pass
pytestmark = pytest.mark.skipif(shap is None, reason="Requires shap package")
# Check integration is not broken from xgboost side
# Changes in binary format may cause problems
def test_with_shap(... | from sklearn.datasets import fetch_california_housing
X, y = fetch_california_housing(return_X_y=True)
dtrain = xgb.DMatrix(X, label=y)
model = xgb.train({"learning_rate": 0.01}, dtrain, 10)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
margin = model.predict(dtrai... | identifier_body | |
test_with_shap.py | import numpy as np
import xgboost as xgb
import pytest
try: | pass
pytestmark = pytest.mark.skipif(shap is None, reason="Requires shap package")
# Check integration is not broken from xgboost side
# Changes in binary format may cause problems
def test_with_shap():
from sklearn.datasets import fetch_california_housing
X, y = fetch_california_housing(return_X_y=True)... | import shap
except ImportError:
shap = None | random_line_split |
test_with_shap.py | import numpy as np
import xgboost as xgb
import pytest
try:
import shap
except ImportError:
shap = None
pass
pytestmark = pytest.mark.skipif(shap is None, reason="Requires shap package")
# Check integration is not broken from xgboost side
# Changes in binary format may cause problems
def | ():
from sklearn.datasets import fetch_california_housing
X, y = fetch_california_housing(return_X_y=True)
dtrain = xgb.DMatrix(X, label=y)
model = xgb.train({"learning_rate": 0.01}, dtrain, 10)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
margin = model.predi... | test_with_shap | identifier_name |
defaults-ja_JP.js | /*!
* Bootstrap-select v1.12.4 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2017 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Regist... |
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: '何もが選択した',
noneResultsText: '\'{0}\'が結果を返さない',
countSelectedText: '{0}/{1}が選択した',
maxOptionsText: ['限界は達した({n}{var}最大)', '限界をグループは達した({n}{var}最大)', ['アイテム', 'アイテム']],
selectAllText: '全部を選択する',
desele... | {
factory(root["jQuery"]);
} | conditional_block |
defaults-ja_JP.js | /*!
* Bootstrap-select v1.12.4 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2017 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Regist... | return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery... | random_line_split | |
instance_image_action.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
'''-------------------------------------------------------------------------
Copyright IBM Corp. 2015, 2015 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 obta... | (action.Action):
is_global = True # store in global container
def __init__(self, context):
self.clients = Clients(context)
self._image_id = None
self._name = None
self._resource_id = None
self.data_block_size_bytes = CONF.backup_image_object_size
# s... | InstanceImageAction | identifier_name |
instance_image_action.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
'''-------------------------------------------------------------------------
Copyright IBM Corp. 2015, 2015 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 obta... | 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
Limitations under the License.
---------... |
http://www.apache.org/licenses/LICENSE-2.0
| random_line_split |
instance_image_action.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
'''-------------------------------------------------------------------------
Copyright IBM Corp. 2015, 2015 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 obta... |
try:
swift_conn.put_object(container_name,
global_container_image_id + "_" +
str(chunks),
data,
content_length=len(data))
... | break | conditional_block |
instance_image_action.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
'''-------------------------------------------------------------------------
Copyright IBM Corp. 2015, 2015 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 obta... |
def generate_template(self, context, template_gen):
instance = InstanceResource(self._image_id, self._name, resource_id=self._resource_id)
template_gen.add_instance(instance)
def failover(self, context, resource_id, resource_data, container_name):
return self._import_from_swift... | LOG.debug("protecting instance (image copied) %s" % (resource_id))
instance = self.clients.nova().servers.get(resource_id)
self._image_id = instance.image['id']
self._name = instance.name
self._resource_id = resource_id
instance_copy_execution =\
ae.ActionExe... | identifier_body |
lib.rs | // Copyright 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-MIT or ... |
#[no_mangle]
pub unsafe extern "C" fn memmove(dest: *mut u8, src: *u8, n: uint) -> *mut u8 {
if src < dest as *u8 { // copy from end
let mut i = n;
while i != 0 {
i -= 1;
*(offset(dest as *u8, i as int) as *mut u8) = *offset(src, i as int);
}
} else { // copy fro... | *(offset(dest as *u8, i as int) as *mut u8) = *offset(src, i as int);
i += 1;
}
return dest;
} | random_line_split |
lib.rs | // Copyright 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-MIT or ... |
return dest;
}
#[no_mangle]
pub unsafe extern "C" fn memset(s: *mut u8, c: i32, n: uint) -> *mut u8 {
let mut i = 0;
while i < n {
*(offset(s as *u8, i as int) as *mut u8) = c as u8;
i += 1;
}
return s;
}
#[no_mangle]
pub unsafe extern "C" fn memcmp(s1: *u8, s2: *u8, n: uint) -> i... | { // copy from beginning
let mut i = 0;
while i < n {
*(offset(dest as *u8, i as int) as *mut u8) = *offset(src, i as int);
i += 1;
}
} | conditional_block |
lib.rs | // Copyright 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-MIT or ... |
#[test] fn work_on_windows() { } // FIXME #10872 needed for a happy windows
| {
let mut i = 0;
while i < n {
let a = *offset(s1, i as int);
let b = *offset(s2, i as int);
if a != b {
return (a - b) as i32
}
i += 1;
}
return 0;
} | identifier_body |
lib.rs | // Copyright 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-MIT or ... | (dest: *mut u8, src: *u8, n: uint) -> *mut u8 {
if src < dest as *u8 { // copy from end
let mut i = n;
while i != 0 {
i -= 1;
*(offset(dest as *u8, i as int) as *mut u8) = *offset(src, i as int);
}
} else { // copy from beginning
let mut i = 0;
whi... | memmove | identifier_name |
clock.rs | use std::fmt;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};
pub struct Clock {
init: isize,
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
}
fn spawn_updater_thread(
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
main_signal: Arc... | });
}
impl Clock {
// starts stopped
pub fn new(init: isize, main_signal: Arc<Condvar>) -> Clock {
let time_left = Arc::new(Mutex::new(init));
let running = Arc::new(Mutex::new(false));
spawn_updater_thread(time_left.clone(), running.clone(), main_signal);
Clock {
... | let sleep_start = Instant::now();
thread::sleep(Duration::from_millis(10));
let slept_for = Instant::now().duration_since(sleep_start);
*time_left.lock().unwrap() -= slept_for.subsec_nanos() as isize / 10000000; | random_line_split |
clock.rs | use std::fmt;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};
pub struct Clock {
init: isize,
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
}
fn spawn_updater_thread(
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
main_signal: Arc... |
if *time_left.lock().unwrap() <= 0 {
main_signal.notify_all();
}
let sleep_start = Instant::now();
thread::sleep(Duration::from_millis(10));
let slept_for = Instant::now().duration_since(sleep_start);
*time_left.lock().unwrap() -= slept_for.subsec_nanos() as ... | {
thread::sleep(Duration::from_millis(10));
continue;
} | conditional_block |
clock.rs | use std::fmt;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};
pub struct Clock {
init: isize,
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
}
fn spawn_updater_thread(
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
main_signal: Arc... |
pub fn time_remaining(&self) -> isize {
*self.time_left.lock().unwrap()
}
}
impl fmt::Display for Clock {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let csecs = self.time_remaining();
let secs = csecs / 100;
if secs <= 0 {
let min = -secs / 60;
... | {
*self.running.lock().unwrap() = true;
} | identifier_body |
clock.rs | use std::fmt;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};
pub struct Clock {
init: isize,
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
}
fn spawn_updater_thread(
time_left: Arc<Mutex<isize>>,
running: Arc<Mutex<bool>>,
main_signal: Arc... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
let csecs = self.time_remaining();
let secs = csecs / 100;
if secs <= 0 {
let min = -secs / 60;
write!(f, "-{:01}:{:02}", min, (-secs) - min * 60)
} else {
let min = secs / 60;
write!(f, "{:0... | fmt | identifier_name |
profiling.py | ##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
# | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | random_line_split | |
profiling.py | ##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
else:
with open(self.profileOutput, 'w') as stream:
s = pstats.Stats(p, stream=stream)
s.strip_dirs()
s.sort_stats(-1)
s.print_stats()
AppProfiler.profilers["cprofile-cpu"] = CProfileCPURunner
| p.dump_stats(self.profileOutput) | conditional_block |
profiling.py | ##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | (self, reactor):
"""
Run reactor under the cProfile profiler.
"""
try:
import cProfile
import pstats
except ImportError, e:
self._reportImportError("cProfile", e)
p = cProfile.Profile(time.clock)
p.runcall(reactor.run)
... | run | identifier_name |
profiling.py | ##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
AppProfiler.profilers["cprofile-cpu"] = CProfileCPURunner
| """
Run reactor under the cProfile profiler.
"""
try:
import cProfile
import pstats
except ImportError, e:
self._reportImportError("cProfile", e)
p = cProfile.Profile(time.clock)
p.runcall(reactor.run)
if self.saveStats:
... | identifier_body |
html_elems.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@... |
def toHtml(self):
return u"%s%s%s" % (self.openTagHtml(), self.data.toHtml(), self.closeTagHtml())
def hasContents(self):
return self.data.toHtml() != ""
class HtmlParagraph(HtmlElem):
def __init__(self, data, attrs=None):
HtmlElem.__init__(self, 'p', data, attrs)
class HtmlL... | return u"</%s>" % self.tag | identifier_body |
html_elems.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@... |
def setAttr(self, name, value):
self.attrs[name] = value
def getAttrsHtml(self):
html = u''
for k, v in self.attrs.items():
html += u' %s="%s"' % (k, v)
return html
def openTagHtml(self):
return u"<%s%s>" % (self.tag, self.getAttrsHtml())
def close... | return self.data.data | random_line_split |
html_elems.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@... | (self, tag, data, attrs=None):
self.tag = tag
self.data = data if isinstance(data, HtmlContent) else HtmlContent(data)
self.attrs = attrs if attrs is not None else dict()
if 'tag' in self.attrs:
self.setTag(self.attrs['tag'])
del self.attrs['tag']
def setTag(... | __init__ | identifier_name |
html_elems.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@... |
return not empty
if hasattr(self.data, 'hasContents'):
return self.data.hasContents()
return len(self.data) > 0
class HtmlElem(object):
def __init__(self, tag, data, attrs=None):
self.tag = tag
self.data = data if isinstance(data, HtmlContent) else HtmlC... | if item.hasContents():
empty = False
break | conditional_block |
chario.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | () -> TestCharIO {
TestCharIO {
data: RefCell::new(TestCharIOData {
last_char: '\0',
putc_calls: 0,
}),
}
}
fn get_last_char(&self) -> char {
self.data.borrow().last_char
}
fn get_and_reset_putc_calls(&self) -> uint {
let current = self.data.... | new | identifier_name |
chario.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
self.putc(i as char);
}
}
/// Outputs an integer.
fn puti(&self, i: u32) {
self.putint(i, 10);
}
/// Outputs an integer as a hex string.
fn puth(&self, i: u32) {
self.putint(i, 16);
}
}
#[cfg(test)]
pub mod test {
use core::cell::RefCell;
use drivers::chario::CharIO;
pub stru... | {
break;
} | conditional_block |
chario.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | pub fn new() -> TestCharIO {
TestCharIO {
data: RefCell::new(TestCharIOData {
last_char: '\0',
putc_calls: 0,
}),
}
}
fn get_last_char(&self) -> char {
self.data.borrow().last_char
}
fn get_and_reset_putc_calls(&self) -> uint {
let curren... | data.last_char = value;
}
}
impl TestCharIO { | random_line_split |
chario.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
#[test]
fn puti_should_store_a_number_as_char() {
let io = TestCharIO::new();
io.puti(3);
assert!(io.get_last_char() == '3');
io.puti(9);
assert!(io.get_last_char() == '9');
io.puti(10);
assert!(io.get_last_char() == '0');
io.puti(11);
assert!(io.get_last_char() == '1');
}
... | {
let io = TestCharIO::new();
io.putc('a');
assert!(io.get_last_char() == 'a');
io.putc('z');
assert!(io.get_last_char() == 'z');
} | identifier_body |
movie-result.directive.js | angular.module('movieApp')
.directive('movieResult', function () {
var directive = {
restrict: 'E',
replace: true,
scope: { | '<div class="col-sm-4">',
'<img ng-src="{{result.Poster}}" alt="{{result.Title}}" width="220px">',
'</div>',
'<div class="col-sm-8">',
'<h3>{{result.Title}}</h3>',
'<p>{{result.Plot}}</p>',
'<p><strong>Director:</strong> {{result.Director}}</p>',
'<p><strong>Actors:</strong> {{resul... | result: '=result'
},
template: [
'<div class="row">', | random_line_split |
solution_comparator.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Authors: Jean-Emile DARTOIS <jean-emile.dartois@b-com.com>
#
# 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/... | (self, sol1, sol2):
raise NotImplementedError()
| compare | identifier_name |
solution_comparator.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Authors: Jean-Emile DARTOIS <jean-emile.dartois@b-com.com>
#
# 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/... | raise NotImplementedError() | identifier_body | |
solution_comparator.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Authors: Jean-Emile DARTOIS <jean-emile.dartois@b-com.com>
#
# 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/... | def compare(self, sol1, sol2):
raise NotImplementedError() | random_line_split | |
views.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2012, 2013, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your... | (f):
"""Perform standard operation to check record availability for user."""
@wraps(f)
def decorated(recid, *args, **kwargs):
from invenio.modules.access.mailcookie import \
mail_cookie_create_authorize_action
from invenio.modules.access.local_config import VIEWRESTRCOLL
... | request_record | identifier_name |
views.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2012, 2013, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your... |
# FIXME create better streaming support
file_ = cStringIO.StringIO(document.open('rb').read())
file_.seek(0)
return send_file(file_, mimetype='application/octet-stream',
attachment_filename=filename)
return send_file(document['uri']... | return redirect(document.get('uri')) | conditional_block |
views.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2012, 2013, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your... | @request_record
@register_menu(blueprint, 'record.files', _('Files'), order=8,
endpoint_arguments_constructor=lambda:
dict(recid=request.view_args.get('recid')),
visible_when=visible_collection_tabs('files'))
def files(recid):
"""Return overview of attached files."""
... | random_line_split | |
views.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2012, 2013, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your... |
@blueprint.route('/<int:recid>/keywords', methods=['GET', 'POST'])
@request_record
@register_menu(blueprint, 'record.keywords', _('Keywords'), order=4,
endpoint_arguments_constructor=lambda:
dict(recid=request.view_args.get('recid')),
visible_when=visible_collection_tabs(... | """Display citations."""
from invenio.legacy.bibrank.citation_searcher import calculate_cited_by_list,\
get_self_cited_by, calculate_co_cited_with_list
citations = dict(
citinglist=calculate_cited_by_list(recid),
selfcited=get_self_cited_by(recid),
co_cited=calculate_co_cited_wit... | identifier_body |
api.js | var fs = require("fs");
var moment = require("moment");
/*
* Serve JSON to our AngularJS client
*/
// For a real app, you'd make database requests here.
// For this example, "data" acts like an in-memory "database"
// GET
exports.posts = function (req, res) {
fs.readFile("data/data.txt", 'utf-8', function (error, ... | }
});
}; | res.json(false);
}) | random_line_split |
oppia-short-response-code-repl.component.ts | // Copyright 2019 The Oppia 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 required by ap... | selector: 'oppia-short-response-code-repl',
templateUrl: './code-repl-short-response.component.html',
styleUrls: []
})
export class ShortResponseCodeRepl implements OnInit {
// These properties are initialized using Angular lifecycle hooks
// and we need to do non-null assertion, for more information see
//... |
@Component({ | random_line_split |
oppia-short-response-code-repl.component.ts | // Copyright 2019 The Oppia 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 required by ap... | implements OnInit {
// These properties are initialized using Angular lifecycle hooks
// and we need to do non-null assertion, for more information see
// https://github.com/oppia/oppia/wiki/Guide-on-defining-types#ts-7-1
@Input('answer') answerWithValue!: string;
answer!: string;
constructor(private htmlE... | ShortResponseCodeRepl | identifier_name |
create_hour_per_day_chart.py | import os
import plotly.plotly as py
from plotly.graph_objs import *
import config
py.sign_in(config.plotly_user, config.plotly_pass)
dates = []
count_dates = []
counts = []
hours = []
with open(os.path.normpath(config.filename), 'r') as f:
rows = f.readlines()
# get summary of dates in file
for line in ro... |
trace1 = Bar(x=bins,y=hours)
data = Data([trace1])
layout = Layout(
title = config.plotly_graph_title,
xaxis=XAxis(
title='Date',
autorange=True
),
yaxis=YAxis(
title='Number of Hours',
autorange=True
)
)
fig = Figure(data=data, layout=layout)
# do the graph mag... | hours.append(count/float(12)) | conditional_block |
create_hour_per_day_chart.py | import os
import plotly.plotly as py
from plotly.graph_objs import *
import config
py.sign_in(config.plotly_user, config.plotly_pass)
| count_dates = []
counts = []
hours = []
with open(os.path.normpath(config.filename), 'r') as f:
rows = f.readlines()
# get summary of dates in file
for line in rows:
lines = line.strip().split(',')
just_date = lines[0].split(' ')
dates.append(just_date[0])
bins = sorted(list(se... | dates = [] | random_line_split |
demo.ts | import Pouchy from '..'
import memory from 'pouchdb-adapter-memory'
require('perish')
Pouchy.plugin(memory)
type DemoMovieSchema = {
title: string
stars: number
}
async function runDemo () |
runDemo()
| {
const pouch = new Pouchy<DemoMovieSchema>({
name: 'demodb'
})
const saved = await pouch.save({
title: 'LOTR',
stars: 3
})
console.log(saved)
const all = await pouch.all()
all.forEach((doc, i) => console.log(`doc "${i}":`, doc))
const updated = await pouch.save({
...saved,
title: 'L... | identifier_body |
demo.ts | import Pouchy from '..'
import memory from 'pouchdb-adapter-memory'
require('perish')
Pouchy.plugin(memory) |
type DemoMovieSchema = {
title: string
stars: number
}
async function runDemo () {
const pouch = new Pouchy<DemoMovieSchema>({
name: 'demodb'
})
const saved = await pouch.save({
title: 'LOTR',
stars: 3
})
console.log(saved)
const all = await pouch.all()
all.forEach((doc, i) => console.lo... | random_line_split | |
demo.ts | import Pouchy from '..'
import memory from 'pouchdb-adapter-memory'
require('perish')
Pouchy.plugin(memory)
type DemoMovieSchema = {
title: string
stars: number
}
async function | () {
const pouch = new Pouchy<DemoMovieSchema>({
name: 'demodb'
})
const saved = await pouch.save({
title: 'LOTR',
stars: 3
})
console.log(saved)
const all = await pouch.all()
all.forEach((doc, i) => console.log(`doc "${i}":`, doc))
const updated = await pouch.save({
...saved,
title... | runDemo | identifier_name |
code-threads.component.ts | import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
import { Diff, Thread } from '@/core/proto';
import { CommentExpandedMap } from '@/shared/thread';
import { DiscussionService } from '../discussion.service';
import { ThreadStateService } from '../thread-state.service';
// The ... |
}
saveStave(thread: Thread, commentExpandedMap: CommentExpandedMap): void {
this.threadStateService.saveState(thread, commentExpandedMap);
this.expandEmitter.emit();
}
private initThreads(): void {
this.isQueue = false;
this.fileGroupList = this.getSortedGroups(this.threads.slice());
this... | {
this.refreshThreads();
} | conditional_block |
code-threads.component.ts | import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
import { Diff, Thread } from '@/core/proto';
import { CommentExpandedMap } from '@/shared/thread';
import { DiscussionService } from '../discussion.service';
import { ThreadStateService } from '../thread-state.service';
// The ... | implements OnChanges, OnInit {
// Threads are divided into groups by filenames
fileGroupList: Thread[][] = [];
// Did firebase send any update, when freeze mode was active?
isQueue: boolean = false;
@Input() threads: Thread[];
@Input() diff: Diff;
@Output() expandEmitter = new EventEmitter<void>();
c... | CodeThreadsComponent | identifier_name |
code-threads.component.ts | import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
import { Diff, Thread } from '@/core/proto';
import { CommentExpandedMap } from '@/shared/thread';
import { DiscussionService } from '../discussion.service';
import { ThreadStateService } from '../thread-state.service';
// The ... |
private initThreads(): void {
this.isQueue = false;
this.fileGroupList = this.getSortedGroups(this.threads.slice());
this.threads.forEach((thread: Thread) => {
this.threadStateService.createLink(thread);
});
}
private refreshThreads(): void {
if (!this.threadStateService.getFreezeMode... | {
this.threadStateService.saveState(thread, commentExpandedMap);
this.expandEmitter.emit();
} | identifier_body |
code-threads.component.ts | import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
import { Diff, Thread } from '@/core/proto';
import { CommentExpandedMap } from '@/shared/thread';
import { DiscussionService } from '../discussion.service';
import { ThreadStateService } from '../thread-state.service';
// The ... | // How it looks: https://i.imgur.com/MobdMJl.jpg
@Component({
selector: 'code-threads',
templateUrl: './code-threads.component.html',
styleUrls: ['./code-threads.component.scss'],
providers: [DiscussionService],
})
export class CodeThreadsComponent implements OnChanges, OnInit {
// Threads are divided into gr... | random_line_split | |
extend.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import re
import os
import sys
from inspect import isclass
class Extend(object):
|
def extend(language=None, override=None, name=None):
"""
User obj definition decorator
how to use:
@extend(language, override, name)
class MyClass(parent)
the decorator return an instance of Extend that
contains the class defined.
if langage is empty:
extend base class
else:
extend editor functionnal... | def __init__(self, **kwargs):
self.lang = kwargs["lang"]
self.override = kwargs["over"]
self.name = kwargs["name_"]
self.obj = kwargs["obj_"] | identifier_body |
extend.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import re
import os
import sys
from inspect import isclass
class Extend(object): | self.name = kwargs["name_"]
self.obj = kwargs["obj_"]
def extend(language=None, override=None, name=None):
"""
User obj definition decorator
how to use:
@extend(language, override, name)
class MyClass(parent)
the decorator return an instance of Extend that
contains the class defined.
if langage is empt... | def __init__(self, **kwargs):
self.lang = kwargs["lang"]
self.override = kwargs["over"] | random_line_split |
extend.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import re
import os
import sys
from inspect import isclass
class Extend(object):
def __init__(self, **kwargs):
self.lang = kwargs["lang"]
self.override = kwargs["over"]
self.name = kwargs["name_"]
self.obj = kwargs["obj_"]
def extend(language=None, override=None, ... | (obj):
path = os.path.abspath(place)
if os.path.exists(path):
sys.path.append(path)
regex = re.compile(r"(^.+)\.py$")
extensions_list = [regex.sub(r"\1", elt) for elt in os.listdir(path) if regex.search(elt)]
user_extensions = []
for ext in extensions_list:
tmp = __import__(ext)
tmp = reload(... | decorator | identifier_name |
extend.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import re
import os
import sys
from inspect import isclass
class Extend(object):
def __init__(self, **kwargs):
self.lang = kwargs["lang"]
self.override = kwargs["over"]
self.name = kwargs["name_"]
self.obj = kwargs["obj_"]
def extend(language=None, override=None, ... |
else: # obj is class definition
for ext in user_extensions:
if isclass(ext.obj) and issubclass(ext.obj, obj):
return ext.obj
return obj
return decorator
| obj_name = obj.__name__
def wrapper(self, **kwargs):
funs = {ext.lang: ext.obj for ext in user_extensions if ext.override and ext.name == obj_name}
if hasattr(self, "lang") and self.lang in funs: funs[self.lang](self, **kwargs)
else: obj(self, **kwargs)
return wrapper | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.