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 |
|---|---|---|---|---|
core.js | define(["jquery", "underscore", "backbone"], function ($,_,Backbone) {
/* *****************************************************************************************************************
Prototype Inheritance
*********************************************************************************************************... | () { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); };
return (_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id());
},
/**
Generate a scoped UUID by pre-pending a prefix
**/
urn: function(prefix) {
return (prefix || core[idAttribute])+"#"+this.uuid();
},
... | _id | identifier_name |
vfs.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... | def libtree(lib):
"""Generates a filesystem-like directory tree for the files
contained in `lib`. Filesystem nodes are (files, dirs) named
tuples in which both components are dictionaries. The first
maps filenames to Item ids. The second maps directory names to
child node tuples.
"""
root = ... | random_line_split | |
vfs.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... |
return root
| dest = item.destination(fragment=True)
parts = util.components(dest)
_insert(root, parts, item.id) | conditional_block |
vfs.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... | (node, path, itemid):
"""Insert an item into a virtual filesystem node."""
if len(path) == 1:
# Last component. Insert file.
node.files[path[0]] = itemid
else:
# In a directory.
dirname = path[0]
rest = path[1:]
if dirname not in node.dirs:
node.di... | _insert | identifier_name |
vfs.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... | """Generates a filesystem-like directory tree for the files
contained in `lib`. Filesystem nodes are (files, dirs) named
tuples in which both components are dictionaries. The first
maps filenames to Item ids. The second maps directory names to
child node tuples.
"""
root = Node({}, {})
for i... | identifier_body | |
DeviceStream.js | import React, { Component, PropTypes } from 'react'
import { Card, CardHeader, CardText } from 'material-ui/Card'
import Avatar from 'material-ui/Avatar'
import randomMC from 'random-material-color'
import SelectField from 'material-ui/SelectField'
import MenuItem from 'material-ui/MenuItem'
import Graph from '../Graph... | <Card>
<CardHeader
title={this.props.id}
subtitle={childNode}
avatar={<Avatar backgroundColor={this.state.color}>
{this.props.lastUpdate ? this.props.lastUpdate.value: '' }</Avatar>}
/>
<CardText>
<SelectField value={this.props.limit}
... | random_line_split | |
DeviceStream.js | import React, { Component, PropTypes } from 'react'
import { Card, CardHeader, CardText } from 'material-ui/Card'
import Avatar from 'material-ui/Avatar'
import randomMC from 'random-material-color'
import SelectField from 'material-ui/SelectField'
import MenuItem from 'material-ui/MenuItem'
import Graph from '../Graph... |
render () {
const childNode = <p>Last updated {this.props.lastUpdate ? this.props.lastUpdate.date: '' }: unit: {this.props.unit}</p>
return (
<Card>
<CardHeader
title={this.props.id}
subtitle={childNode}
avatar={<Avatar backgroundColor={this.state.color}>
... | {
this.setState({color: randomMC.getColor()})
} | identifier_body |
DeviceStream.js | import React, { Component, PropTypes } from 'react'
import { Card, CardHeader, CardText } from 'material-ui/Card'
import Avatar from 'material-ui/Avatar'
import randomMC from 'random-material-color'
import SelectField from 'material-ui/SelectField'
import MenuItem from 'material-ui/MenuItem'
import Graph from '../Graph... | () {
this.setState({color: randomMC.getColor()})
}
render () {
const childNode = <p>Last updated {this.props.lastUpdate ? this.props.lastUpdate.date: '' }: unit: {this.props.unit}</p>
return (
<Card>
<CardHeader
title={this.props.id}
subtitle={childNode}
av... | componentWillMount | identifier_name |
forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from wtforms_sqlalchemy... | (self):
return RenderMode.markdown
class TrackGroupForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()])
description = IndicoMarkdownField(_('Description'), editor=True)
| program_render_mode | identifier_name |
forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from wtforms_sqlalchemy... | title = StringField(_('Title'), [DataRequired()])
description = IndicoMarkdownField(_('Description'), editor=True) | identifier_body | |
forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from wtforms_sqlalchemy... | code = StringField(_('Code'))
track_group = QuerySelectField(_('Track group'), default='', allow_blank=True, get_label='title',
description=_('Select a track group to which this track should belong'))
default_session = QuerySelectField(_('Default session'), default='', all... | from indico.web.forms.fields import IndicoMarkdownField
class TrackForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()]) | random_line_split |
update_replace_rollback.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | (expected_count):
test.assertEqual(expected_count,
len(reality.resources_by_logical_name('C')))
example_template = Template({
'A': RsrcDef({'a': 'initial'}, []),
'B': RsrcDef({}, []),
'C': RsrcDef({'!a': GetAtt('A', 'a')}, ['B']),
'D': RsrcDef({'c': GetRes('C')}, []),
'E': ... | check_c_count | identifier_name |
update_replace_rollback.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | engine.delete_stack('foo')
engine.noop(12)
engine.call(verify, Template({})) | random_line_split | |
update_replace_rollback.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
example_template = Template({
'A': RsrcDef({'a': 'initial'}, []),
'B': RsrcDef({}, []),
'C': RsrcDef({'!a': GetAtt('A', 'a')}, ['B']),
'D': RsrcDef({'c': GetRes('C')}, []),
'E': RsrcDef({'ca': GetAtt('C', '!a')}, []),
})
engine.create_stack('foo', example_template)
engine.noop(5)
engine.call(verif... | test.assertEqual(expected_count,
len(reality.resources_by_logical_name('C'))) | identifier_body |
qNickInputWidget.py | from PyQt4.QtCore import Qt
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget
import qtUtils
fr... | (self, image, imageWidth, connectClickedSlot, nick='', parent=None):
QWidget.__init__(self, parent)
self.connectClickedSlot = connectClickedSlot
# Image
self.image = QLabel(self)
self.image.setPixmap(QPixmap(qtUtils.getAbsoluteImagePath(image)).scaledToWidth(imageWidth, Qt.Smoo... | __init__ | identifier_name |
qNickInputWidget.py | from PyQt4.QtCore import Qt
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget
import qtUtils
fr... | self.connectButton.resize(self.connectButton.sizeHint())
self.connectButton.setAutoDefault(False)
self.connectButton.clicked.connect(self.__connectClicked)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(self.nickLabel)
hbox.addWidget(self.nickEdit)
... | # Connect button
self.connectButton = QPushButton("Connect", self) | random_line_split |
qNickInputWidget.py | from PyQt4.QtCore import Qt
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget
import qtUtils
fr... | nick = str(self.nickEdit.text()).lower()
# Validate the given nick
nickStatus = utils.isValidNick(nick)
if nickStatus == errors.VALID_NICK:
self.connectClickedSlot(nick)
elif nickStatus == errors.INVALID_NICK_CONTENT:
QMessageBox.warning(self, errors.TITLE_INVALI... | identifier_body | |
qNickInputWidget.py | from PyQt4.QtCore import Qt
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget
import qtUtils
fr... |
elif nickStatus == errors.INVALID_EMPTY_NICK:
QMessageBox.warning(self, errors.TITLE_EMPTY_NICK, errors.EMPTY_NICK)
| QMessageBox.warning(self, errors.TITLE_INVALID_NICK, errors.INVALID_NICK_LENGTH) | conditional_block |
controller_analyze.py | import base64
import csv
import io
import multiprocessing
import numpy as np
import sys
from collections import defaultdict
from io import StringIO
from pathlib import Path
# Import matplotlib ourselves and make it use agg (not any GUI anything)
# before the analyze module pulls it in.
import matplotlib
matplotlib.use... | (trackrels):
for trackrel in trackrels:
try:
_do_analyze(trackrel)
except ValueError:
# often 'wrong number of columns' due to truncated file from killed experiment
pass # nothing to be done here; we're processing in the background
@post('/analyze_selection/')
... | _analyze_selection | identifier_name |
controller_analyze.py | import base64
import csv
import io
import multiprocessing
import numpy as np
import sys
from collections import defaultdict
from io import StringIO
from pathlib import Path
# Import matplotlib ourselves and make it use agg (not any GUI anything)
# before the analyze module pulls it in.
import matplotlib
matplotlib.use... | saveplot("{}.14.heat.perphase.png".format(trackrel))
plotter.plot_heatmap(plot_type='per-minute')
saveplot("{}.15.heat.perminute.png".format(trackrel))
plotter.plot_trace()
saveplot("{}.20.plot.svg".format(trackrel))
@post('/analyze/')
def post_analyze():
trackrel = request.query.trackrel
... | plotter.plot_heatmap(plot_type='per-phase') | random_line_split |
controller_analyze.py | import base64
import csv
import io
import multiprocessing
import numpy as np
import sys
from collections import defaultdict
from io import StringIO
from pathlib import Path
# Import matplotlib ourselves and make it use agg (not any GUI anything)
# before the analyze module pulls it in.
import matplotlib
matplotlib.use... |
all_keys.remove('Track file') # will be added as first column
all_keys = sorted(list(all_keys))
all_keys[:0] = ['Track file'] # prepend 'Track file' header
if do_csv:
output = StringIO()
writer = csv.DictWriter(output, fieldnames=all_keys)
writer.writeheader()
for st... | if k in stat:
val = stat[k]
if isinstance(val, (np.float32, np.float64)):
stat[k] = "%0.3f" % val
else:
stat[k] = "" | conditional_block |
controller_analyze.py | import base64
import csv
import io
import multiprocessing
import numpy as np
import sys
from collections import defaultdict
from io import StringIO
from pathlib import Path
# Import matplotlib ourselves and make it use agg (not any GUI anything)
# before the analyze module pulls it in.
import matplotlib
matplotlib.use... |
def _do_analyze(trackrel):
trackrel = Path(trackrel)
# ensure directories exist for plot creation
trackreldir = trackrel.parent
mkdir(config.PLOTDIR / trackreldir)
# look for debug frames to create links in the trace plot
trackname = trackrel.name.replace('-track.csv', '')
dbgframedir =... | trackrels = request.query.tracks.split('|')
exp_type = request.query.exp_type
stats = []
all_keys = set()
for trackrel in trackrels:
curstats = {}
curstats['Track file'] = trackrel
try:
processor = process.TrackProcessor(str(config.TRACKDIR / trackrel))
... | identifier_body |
sound.tag.js | /*
*
* @author Benoit Vinay
*
* ben@benoitvinay.com
* http://www.benoitvinay.com
*
*/
//////////////////////////////////////////////////////////////////////////////////////////
// Sound Object
//
// use in loader.sound.js
////////////////////////////////////////////////////////////////////////////////////////... | {
var _this = this;
var _tag = tag;
var _valid = (_tag.canPlayType ? true : false); // check if the tag is valid (i.e.: Safari on Windows)
var _playTimeout = undefined;
var _loopInterval = undefined;
var _duration = (_valid ? (_tag.duration * 1000) : -1);
var _playing = false;
this.url = url;
// play
... | identifier_body | |
sound.tag.js | /*
*
* @author Benoit Vinay
*
* ben@benoitvinay.com
* http://www.benoitvinay.com
*
*/
//////////////////////////////////////////////////////////////////////////////////////////
// Sound Object
//
// use in loader.sound.js
////////////////////////////////////////////////////////////////////////////////////////... | (url, tag) {
var _this = this;
var _tag = tag;
var _valid = (_tag.canPlayType ? true : false); // check if the tag is valid (i.e.: Safari on Windows)
var _playTimeout = undefined;
var _loopInterval = undefined;
var _duration = (_valid ? (_tag.duration * 1000) : -1);
var _playing = false;
this.url = url;
... | SoundObject | identifier_name |
sound.tag.js | /*
*
* @author Benoit Vinay
*
* ben@benoitvinay.com
* http://www.benoitvinay.com
*
*/
//////////////////////////////////////////////////////////////////////////////////////////
// Sound Object
//
// use in loader.sound.js
////////////////////////////////////////////////////////////////////////////////////////... |
complete.apply(_this);
}, _duration);
}
}
// loop
this.loop = function(time, complete) {
_play.apply(_this, [time]);
try {
_tag.loop = true;
}
catch(e) {
_error(e);
}
_loopInterval = setInterval(function() {
if(complete) {
complete.apply(_this);
}
}, _duration... | if(complete) {
_playTimeout = setTimeout(function() {
clearTimeout(_playTimeout); | random_line_split |
sound.tag.js | /*
*
* @author Benoit Vinay
*
* ben@benoitvinay.com
* http://www.benoitvinay.com
*
*/
//////////////////////////////////////////////////////////////////////////////////////////
// Sound Object
//
// use in loader.sound.js
////////////////////////////////////////////////////////////////////////////////////////... |
}
| {
if($("#audios-holder").length == 0) {
$("body").prepend("<div id='audios-holder'></div>");
}
$("#audios-holder").append(_tag);
_tag = document.getElementById(url);
} | conditional_block |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | (window: &glfw::Window, (time, event): (f64, glfw::WindowEvent)) {
match event {
glfw::PosEvent(x, y) => window.set_title(format!("Time: {}, Window pos: ({}, {})", time, x, y).as_slice()),
glfw::SizeEvent(w, h) => window.set_title(format!("Time: {}, Window size: ({}, {})... | handle_window_event | identifier_name |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
fn handle_window_event(window: &glfw::Window, (time, event): (f64, glfw::WindowEvent)) {
match event {
glfw::PosEvent(x, y) => window.set_title(format!("Time: {}, Window pos: ({}, {})", time, x, y).as_slice()),
glfw::SizeEvent(w, h) => window.set_title(format!("Time: {... | {
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
glfw.window_hint(glfw::Resizable(true));
let (window, events) = glfw.create_window(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Polling of events can b... | identifier_body |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | glfw.window_hint(glfw::Resizable(true));
let (window, events) = glfw.create_window(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Polling of events can be turned on and off by the specific event type
window.set... |
fn main() {
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
| random_line_split |
nb.py |
import numpy as np
import util
from datetime import datetime
from scipy.stats import norm
import better_exceptions
from scipy.stats import multivariate_normal as mvn
class NaiveBayers(object):
def __init__(self):
# Gaussian deviation
self.gaussians = dict()
# Class priors
self.pri... |
if __name__ == '__main__':
# Get train data
X, Y = util.get_data(40000)
Ntrain = len(Y) // 2
Xtest, Ytest = util.get_test_data(40000)
Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain]
# Xtest, Ytest = X[Ntrain:], Y[Ntrain:]
model = NaiveBayers()
t0 = datetime.now()
model.fit(Xtrain, Ytrain... | N, D = X.shape
# Hyperparameter (10)
K = len(self.gaussians)
# Fill by Zeros
P = np.zeros((N, K))
# for each class and mean/covariance
for c, g in self.gaussians.items():
mean, var = g['mean'], g['var']
log = np.log(self.priors[c])
... | identifier_body |
nb.py | import numpy as np
import util
from datetime import datetime
from scipy.stats import norm
import better_exceptions
from scipy.stats import multivariate_normal as mvn
class NaiveBayers(object):
def __init__(self):
# Gaussian deviation
self.gaussians = dict()
# Class priors | def fit(self, X, Y, smoothing=10e-3):
N, D = X.shape
# 1,2,3,4,5,6,7,8,9,0 - is labels
labels = set(Y)
for c in labels:
# get the current slice [0:number] where X in our class
current_x = X[Y == c]
# Compute mean and variance. Store in the diction... | self.priors = dict()
| random_line_split |
nb.py |
import numpy as np
import util
from datetime import datetime
from scipy.stats import norm
import better_exceptions
from scipy.stats import multivariate_normal as mvn
class NaiveBayers(object):
def __init__(self):
# Gaussian deviation
self.gaussians = dict()
# Class priors
self.pri... | X, Y = util.get_data(40000)
Ntrain = len(Y) // 2
Xtest, Ytest = util.get_test_data(40000)
Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain]
# Xtest, Ytest = X[Ntrain:], Y[Ntrain:]
model = NaiveBayers()
t0 = datetime.now()
model.fit(Xtrain, Ytrain)
print("Training time: ", (datetime.now() - t0))... | conditional_block | |
nb.py |
import numpy as np
import util
from datetime import datetime
from scipy.stats import norm
import better_exceptions
from scipy.stats import multivariate_normal as mvn
class NaiveBayers(object):
def | (self):
# Gaussian deviation
self.gaussians = dict()
# Class priors
self.priors = dict()
def fit(self, X, Y, smoothing=10e-3):
N, D = X.shape
# 1,2,3,4,5,6,7,8,9,0 - is labels
labels = set(Y)
for c in labels:
# get the current slice [0:nu... | __init__ | identifier_name |
amp-pinterest.js | /**
* Copyright 2015 The AMP HTML Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... |
const html = htmlFor(this.element);
return {
color: '#E60019',
content: html`
<svg viewBox="0 0 72 72">
<path
fill="currentColor"
d="M36,26c-5.52,0-9.99,4.47-9.99,9.99c0,4.24,2.63,7.85,6.35,9.31c-0.09-0.79-0.16-2.01,0.03-2.87
c0.18-0.78,1.17-4.... | {
return {};
} | conditional_block |
amp-pinterest.js | /**
* Copyright 2015 The AMP HTML Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... | (element) {
super(element);
/** @private {string} */
this.type_ = '';
}
/**
* @param {boolean=} onLayout
* @override
*/
preconnectCallback(onLayout) {
// preconnect to widget APIpinMedia
Services.preconnectFor(this.win).url(
this.getAmpDoc(),
'https://widgets.pinterest.co... | constructor | identifier_name |
amp-pinterest.js | /**
* Copyright 2015 The AMP HTML Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... |
/** @override */
layoutCallback() {
return this.render().then((node) => {
return this.element.appendChild(node);
});
}
/**
* Renders the component
* @return {*} TODO(#23582): Specify return type
*/
render() {
switch (this.type_) {
case 'embedPin':
return new PinWidg... | {
this.type_ = userAssert(
this.element.getAttribute('data-do'),
'The data-do attribute is required for <amp-pinterest> %s',
this.element
);
} | identifier_body |
amp-pinterest.js | /**
* Copyright 2015 The AMP HTML Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... | </svg>
`,
};
}
}
AMP.extension('amp-pinterest', '0.1', (AMP) => {
AMP.registerElement('amp-pinterest', AmpPinterest, CSS);
}); | random_line_split | |
levels.py | #-------------------------------------------------------------------------------
# Name: levels
# Purpose:
#
# Author: novirael
#
# Created: 17-04-2012
# Copyright: (c) novirael 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------... | (n):
if n == 1:
# The top of the block (y position)
top = 80
for i in range(15):
block = Kafel(blue, kafelek[0], i*(k_width+2), top)
blocks.add(block)
allsprites.add(block)
return allsprites, blocks
# --- Create blocks
"""
# Five rows of blo... | draw_level | identifier_name |
levels.py | #-------------------------------------------------------------------------------
# Name: levels
# Purpose:
#
# Author: novirael
#
# Created: 17-04-2012
# Copyright: (c) novirael 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------... | if n == 1:
# The top of the block (y position)
top = 80
for i in range(15):
block = Kafel(blue, kafelek[0], i*(k_width+2), top)
blocks.add(block)
allsprites.add(block)
return allsprites, blocks
# --- Create blocks
"""
# Five rows of blocks
for ... | identifier_body | |
levels.py | #-------------------------------------------------------------------------------
| # Author: novirael
#
# Created: 17-04-2012
# Copyright: (c) novirael 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
# Import
from sprites import Kafel
# Blocks
kafelek = [ "img/blue.png", "img/green.png",... | # Name: levels
# Purpose:
#
| random_line_split |
levels.py | #-------------------------------------------------------------------------------
# Name: levels
# Purpose:
#
# Author: novirael
#
# Created: 17-04-2012
# Copyright: (c) novirael 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------... |
return allsprites, blocks
# --- Create blocks
"""
# Five rows of blocks
for row in range(2):
for column in range(0,20):
block = Kafel(blue, kafelek[0], column*(k_width+2), top)
blocks.add(block)
allsprites.add(block)
# Move the top of the next row down
... | block = Kafel(blue, kafelek[0], i*(k_width+2), top)
blocks.add(block)
allsprites.add(block) | conditional_block |
app.module.ts | /**
* Copyright (c) 2017 Francois-Xavier Soubirou.
*
* This file is part of tam4.
*
* tam4 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 3 of the License, or
* (at your option) any lat... |
@NgModule({
imports: importedModules,
declarations: [
AppComponent,
NavbarComponent,
LoginComponent,
],
exports: [
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
| {
console.log('Enabling mocked services.');
importedModules.push(MockModule);
} | conditional_block |
app.module.ts | /**
* Copyright (c) 2017 Francois-Xavier Soubirou.
*
* This file is part of tam4.
*
* tam4 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 3 of the License, or
* (at your option) any lat... | { }
| AppModule | identifier_name |
app.module.ts | /**
* Copyright (c) 2017 Francois-Xavier Soubirou.
*
* This file is part of tam4.
*
* tam4 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 3 of the License, or
* (at your option) any lat... | import { PersonalModule } from './personal/personal.module';
import { SharedModule } from './shared/shared.module';
import { environment } from 'app/../environments/environment';
import { LoginComponent } from './login/login.component';
const importedModules: Array<any> = [
BrowserModule,
FormsModule,
Htt... | import { MockModule } from './core/mock.module';
import { HomeModule } from './home/home.module'; | random_line_split |
sales_order.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
import frappe.utils
from frappe.utils import cstr, flt, getdate, comma_and, cint
from frappe import _
from frappe.model.utils ... |
def update_prevdoc_status(self, flag):
for quotation in list(set([d.prevdoc_docname for d in self.get("items")])):
if quotation:
doc = frappe.get_doc("Quotation", quotation)
if doc.docstatus==2:
frappe.throw(_("Quotation {0} is cancelled").format(quotation))
doc.set_status(update=True)
doc... | frappe.db.sql("update `tabOpportunity` set status = %s where name=%s",(flag,enq[0][0])) | conditional_block |
sales_order.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
import frappe.utils
from frappe.utils import cstr, flt, getdate, comma_and, cint
from frappe import _
from frappe.model.utils ... | (source, target, source_parent):
target.project = source_parent.project
doc = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
"doctype": "Material Request",
"validation": {
"docstatus": ["=", 1]
}
},
"Packed Item": {
"doctype": "Material Request Item",
"field_map": {
"pare... | update_item | identifier_name |
sales_order.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
import frappe.utils
from frappe.utils import cstr, flt, getdate, comma_and, cint
from frappe import _
from frappe.model.utils ... |
item = frappe.db.get_value("Item", target.item_code, ["item_group", "selling_cost_center"], as_dict=1)
target.cost_center = frappe.db.get_value("Project", source_parent.project, "cost_center") \
or item.selling_cost_center \
or frappe.db.get_value("Item Group", item.item_group, "default_cost_center")
targe... | random_line_split | |
sales_order.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
import frappe.utils
from frappe.utils import cstr, flt, getdate, comma_and, cint
from frappe import _
from frappe.model.utils ... |
def validate_drop_ship(self):
for d in self.get('items'):
if d.delivered_by_supplier and not d.supplier:
frappe.throw(_("Row #{0}: Set Supplier for item {1}").format(d.idx, d.item_code))
def on_submit(self):
self.check_credit_limit()
self.update_reserved_qty()
frappe.get_doc('Authorization Control'... | for quotation in list(set([d.prevdoc_docname for d in self.get("items")])):
if quotation:
doc = frappe.get_doc("Quotation", quotation)
if doc.docstatus==2:
frappe.throw(_("Quotation {0} is cancelled").format(quotation))
doc.set_status(update=True)
doc.update_opportunity() | identifier_body |
second.rs | // Module containing functions for calculating second order greeks
use std::f64::consts::E;
use common::*;
/// Calculates the Gamma for an option
///
/// Gamma measures the rate of change in the delta with respect to the change in the underlying price.
///
/// # Arguments
/// * `s0` - The underlying price of the opti... | () {
let gamma = gamma(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL);
let abs = (gamma - E_GAMMA).abs();
assert!(abs < 0.001);
}
} | test_gamma | identifier_name |
second.rs | // Module containing functions for calculating second order greeks
use std::f64::consts::E; |
use common::*;
/// Calculates the Gamma for an option
///
/// Gamma measures the rate of change in the delta with respect to the change in the underlying price.
///
/// # Arguments
/// * `s0` - The underlying price of the option
/// * `x` - The strike price of the option
/// * `t` - time to expiration as a percentage... | random_line_split | |
second.rs | // Module containing functions for calculating second order greeks
use std::f64::consts::E;
use common::*;
/// Calculates the Gamma for an option
///
/// Gamma measures the rate of change in the delta with respect to the change in the underlying price.
///
/// # Arguments
/// * `s0` - The underlying price of the opti... |
#[cfg(test)]
mod tests {
use greeks::*;
const UNDERLYING: f64 = 64.68;
const STRIKE: f64 = 65.00;
const VOL: f64 = 0.5051;
const INTEREST_RATE: f64 = 0.0150;
const DIV_YIELD: f64 = 0.0210;
const DAYS_PER_YEAR: f64 = 365.0;
const TIME_TO_EXPIRY: f64 = 23.0 / DAYS_PER_YEAR;
const ... | {
let arg1 = E.powf(-(q * t)) / (s0 * sigma * (t.sqrt()));
let arg2 = one_over_sqrt_pi();
let arg3 = E.powf((-d1).powf(2.0)) / 2.0;
return arg1 * arg2 * arg3;
} | identifier_body |
raster_symbolizer_test.py | #!/usr/bin/env python
from nose.tools import *
from utilities import execution_path, save_data, contains_word
import os, mapnik
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
def test_dataraster_colori... | ():
srs = '+init=epsg:32630'
lyr = mapnik.Layer('dataraster')
lyr.datasource = mapnik.Gdal(
file = '../data/raster/dataraster.tif',
band = 1,
)
lyr.srs = srs
_map = mapnik.Map(256,256, srs)
_map.layers.append(lyr)
# point inside raster extent with valid data
x, y... | test_dataraster_query_point | identifier_name |
raster_symbolizer_test.py | #!/usr/bin/env python
from nose.tools import *
from utilities import execution_path, save_data, contains_word
import os, mapnik
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
def test_dataraster_colori... |
def test_dataraster_query_point():
srs = '+init=epsg:32630'
lyr = mapnik.Layer('dataraster')
lyr.datasource = mapnik.Gdal(
file = '../data/raster/dataraster.tif',
band = 1,
)
lyr.srs = srs
_map = mapnik.Map(256,256, srs)
_map.layers.append(lyr)
# point inside raste... | srs = '+init=epsg:32630'
lyr = mapnik.Layer('dataraster')
lyr.datasource = mapnik.Gdal(
file = '../data/raster/dataraster.tif',
band = 1,
)
lyr.srs = srs
_map = mapnik.Map(256,256, srs)
style = mapnik.Style()
rule = mapnik.Rule()
sym = mapnik.RasterSymbolizer()
# ... | identifier_body |
raster_symbolizer_test.py | #!/usr/bin/env python
from nose.tools import *
from utilities import execution_path, save_data, contains_word
import os, mapnik
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
def test_dataraster_colori... | sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color("transparent"))
for value, color in [
( 0, "#0044cc"),
( 10, "#00cc00"),
( 20, "#ffff00"),
( 30, "#ff7f00"),
( 40, "#ff0000"),
( 50, "#ff007f"),
( 60, "#ff00ff"),
... | style = mapnik.Style()
rule = mapnik.Rule()
sym = mapnik.RasterSymbolizer()
# Assigning a colorizer to the RasterSymbolizer tells the later
# that it should use it to colorize the raw data raster | random_line_split |
raster_symbolizer_test.py | #!/usr/bin/env python
from nose.tools import *
from utilities import execution_path, save_data, contains_word
import os, mapnik
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
def test_dataraster_colori... |
rule.symbols.append(sym)
style.rules.append(rule)
_map.append_style('foo', style)
lyr.styles.append('foo')
_map.layers.append(lyr)
_map.zoom_to_box(lyr.envelope())
im = mapnik.Image(_map.width,_map.height)
mapnik.render(_map, im)
# save a png somewhere so we can see it
save_dat... | sym.colorizer.add_stop(value, mapnik.Color(color)) | conditional_block |
app.routes.ts | import { PrivateComponent } from "./private.component";
import { LoginComponent } from "./login.component";
import { RegisterComponent } from "./register.component";
import { SettingsComponent } from "./settings.component";
import { HomeComponent } from "./home.component";
import { AssetComponent } from "./asset.compon... | { path: '', component: HomeComponent },
{ path: 'asset/:tx', component: AssetComponent },
{ path: 'asset/:tx/view', component: ViewerComponent },
{ path: 'asset/:tx/analytics', component: AnalyticsComponent },
{ path: 'settings', component: SettingsComponent }... | },
{
path: 'me',
component: PrivateComponent,
children: [ | random_line_split |
state.rs | use std::fmt::{Debug, Formatter, Result};
use std::clone::Clone;
pub enum State {
Unknown,
Unsupported,
Unauthorized,
PoweredOff,
PoweredOn,
}
impl State {
fn id(&self) -> usize {
match *self {
State::Unknown => 1,
State::Unsupported => 3,
Stat... |
}
impl Debug for State {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "State::{}", match *self {
State::Unknown => "Unknown",
State::Unsupported => "Unsupported",
State::Unauthorized => "Unauthorized",
State::PoweredOff => "PoweredOff",
... | {
self.id() == other.id()
} | identifier_body |
state.rs | use std::fmt::{Debug, Formatter, Result};
use std::clone::Clone;
pub enum State {
Unknown,
Unsupported,
Unauthorized,
PoweredOff,
PoweredOn,
}
impl State {
fn id(&self) -> usize {
match *self {
State::Unknown => 1,
State::Unsupported => 3,
Stat... | (&self, f: &mut Formatter) -> Result {
write!(f, "State::{}", match *self {
State::Unknown => "Unknown",
State::Unsupported => "Unsupported",
State::Unauthorized => "Unauthorized",
State::PoweredOff => "PoweredOff",
State::PoweredOn => "Powe... | fmt | identifier_name |
state.rs | use std::fmt::{Debug, Formatter, Result};
use std::clone::Clone;
pub enum State {
Unknown,
Unsupported,
Unauthorized,
PoweredOff,
PoweredOn,
}
impl State {
fn id(&self) -> usize {
match *self {
State::Unknown => 1,
State::Unsupported => 3,
Stat... | }
impl PartialEq for State {
fn eq(&self, other: &State) -> bool {
self.id() == other.id()
}
}
impl Debug for State {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "State::{}", match *self {
State::Unknown => "Unknown",
State::Unsupported => "Unsuppor... | } | random_line_split |
Northwind.RegionService.ts | namespace Enterprise.Northwind {
export namespace RegionService {
export const baseUrl = 'Northwind/Region';
export declare function Create(request: Serenity.SaveRequest<RegionRow>, onSuccess?: (response: Serenity.SaveResponse) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
export decla... | 'Update',
'Delete',
'Retrieve',
'List'
].forEach(x => {
(<any>RegionService)[x] = function (r, s, o) {
return Q.serviceRequest(baseUrl + '/' + x, r, s, o);
};
(<any>Methods)[x] = baseUrl + '/' + x;
});... | [
'Create', | random_line_split |
mat.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import OrderedDict
from uuid import uuid4
from warnings import warn
from numpy import object as np_object
from numpy import array, inf, isinf
from six import string_types
from cobra.core import Metabolite, Model, Reaction
from... | """send the model to a MATLAB workspace through pymatbridge
This model can then be manipulated through the COBRA toolbox
Parameters
----------
variable_name : str
The variable name to which the model will be assigned in the
MATLAB workspace
matlab : None or pymatbridge.Matlab inst... | identifier_body | |
mat.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import OrderedDict
from uuid import uuid4
from warnings import warn
from numpy import object as np_object
from numpy import array, inf, isinf
from six import string_types
from cobra.core import Metabolite, Model, Reaction
from... | for possible_name in possible_names:
try:
return from_mat_struct(data[possible_name], model_id=possible_name,
inf=inf)
except ValueError:
pass
# If code here is executed, then no model was found.
raise IOError("no COBRA model found")... | if len(possible_names) == 1:
variable_name = possible_names[0]
if variable_name is not None:
return from_mat_struct(data[variable_name], model_id=variable_name,
inf=inf) | random_line_split |
mat.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import OrderedDict
from uuid import uuid4
from warnings import warn
from numpy import object as np_object
from numpy import array, inf, isinf
from six import string_types
from cobra.core import Metabolite, Model, Reaction
from... |
if variable_name is not None:
return from_mat_struct(data[variable_name], model_id=variable_name,
inf=inf)
for possible_name in possible_names:
try:
return from_mat_struct(data[possible_name], model_id=possible_name,
... | variable_name = possible_names[0] | conditional_block |
mat.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import OrderedDict
from uuid import uuid4
from warnings import warn
from numpy import object as np_object
from numpy import array, inf, isinf
from six import string_types
from cobra.core import Metabolite, Model, Reaction
from... | (result):
"""ensure success of a pymatbridge operation"""
if result["success"] is not True:
raise RuntimeError(result["content"]["stdout"])
def model_to_pymatbridge(model, variable_name="model", matlab=None):
"""send the model to a MATLAB workspace through pymatbridge
This model can then be m... | _check | identifier_name |
thesubdb.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import babelfish
import requests
from . import Provider
from .. import __version__
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
from ..subtitle import Subtitle, is_valid_subtitle, detect
logger = logging.ge... | (Provider):
languages = set([babelfish.Language.fromalpha2(l) for l in ['en', 'es', 'fr', 'it', 'nl', 'pl', 'pt', 'ro', 'sv', 'tr']])
required_hash = 'thesubdb'
def initialize(self):
self.session = requests.Session()
self.session.headers = {'User-Agent': 'SubDB/1.0 (subliminal/%s; https://g... | TheSubDBProvider | identifier_name |
thesubdb.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import babelfish
import requests
from . import Provider
from .. import __version__
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
from ..subtitle import Subtitle, is_valid_subtitle, detect
logger = logging.ge... |
elif r.status_code != 200:
raise ProviderError('Request failed with status code %d' % r.status_code)
return [TheSubDBSubtitle(language, hash) for language in
set([babelfish.Language.fromalpha2(l) for l in r.content.split(',')])]
def list_subtitles(self, video, languages... | logger.debug('No subtitle found')
return [] | conditional_block |
thesubdb.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import babelfish
import requests
from . import Provider
from .. import __version__
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
from ..subtitle import Subtitle, is_valid_subtitle, detect
logger = logging.ge... |
def get(self, params):
"""Make a GET request on the server with the given parameters
:param params: params of the request
:return: the response
:rtype: :class:`requests.Response`
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable`
"""
try:
... | self.session.close() | identifier_body |
thesubdb.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import babelfish
import requests
from . import Provider
from .. import __version__
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
from ..subtitle import Subtitle, is_valid_subtitle, detect
logger = logging.ge... | raise InvalidSubtitle
return subtitle_text | ))
subtitle_text = r.content.decode(
detect(r.content, subtitle.language.alpha2)['encoding'], 'replace')
if not is_valid_subtitle(subtitle_text): | random_line_split |
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) {
if i.path
... |
let mut jni_global_vars = jni_cache_macro_cache.global_vars();
file.items.append(&mut jni_global_vars);
let out_path = Path::new(&out_dir).join(include_path.file_name().expect("No file name"));
let mut cache =
file_cache::FileWriteCache::new(&out_path, &mut file_cache::NoNe... | {
panic!("jni cache macros visiting failed: {}", visitor.errors[0]);
} | conditional_block |
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) {
if i.path
... | .unwrap();
}
exp_code
.update_file_if_necessary()
.unwrap_or_else(|err| panic!("Can not write to {}: {}", exp_code_path.display(), err));
println!("cargo:rerun-if-changed={}", exp_tests_list_path.display());
} | random_line_split | |
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) {
if i.path
... | () {
let out_dir = env::var("OUT_DIR").unwrap();
for include_path in &[
Path::new("src/java_jni/jni-include.rs"),
Path::new("src/cpp/cpp-include.rs"),
] {
let src_cnt_tail = std::fs::read_to_string(include_path)
.unwrap_or_else(|err| panic!("Error during read {}: {}", in... | main | identifier_name |
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) |
}
mod file_cache {
include!("src/file_cache.rs");
}
mod jni_find_cache {
include!("src/java_jni/find_cache.rs");
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
for include_path in &[
Path::new("src/java_jni/jni-include.rs"),
Path::new("src/cpp/cpp-include.rs"),
] {
... | {
if i.path
.clone()
.into_token_stream()
.to_string()
.starts_with("swig_")
{
*i = parse_quote! { #[doc = "swig_ replace"] };
}
} | identifier_body |
backdrop.ts | import { Directive, ElementRef, Input } from '@angular/core';
import { DisableScroll, GestureController, GestureDelegate } from '../../gestures/gesture-controller';
import { isTrueProperty } from '../../util/util';
/**
* @private
*/
@Directive({
selector: 'ion-backdrop',
host: {
'role': 'presentation',
... |
}
getNativeElement(): HTMLElement {
return this._elementRef.nativeElement;
}
}
| {
this._gestureCtrl.enableScroll(this._gestureID);
} | conditional_block |
backdrop.ts | import { Directive, ElementRef, Input } from '@angular/core';
import { DisableScroll, GestureController, GestureDelegate } from '../../gestures/gesture-controller';
import { isTrueProperty } from '../../util/util';
/**
* @private
*/
@Directive({
selector: 'ion-backdrop',
host: {
'role': 'presentation',
... |
ngOnInit() {
if (isTrueProperty(this.disableScroll)) {
this._gestureID = this._gestureCtrl.newID();
this._gestureCtrl.disableScroll(this._gestureID);
}
}
ngOnDestroy() {
if (this._gestureID) {
this._gestureCtrl.enableScroll(this._gestureID);
}
}
getNativeElement(): HTMLEl... | {} | identifier_body |
backdrop.ts | import { Directive, ElementRef, Input } from '@angular/core';
import { DisableScroll, GestureController, GestureDelegate } from '../../gestures/gesture-controller';
import { isTrueProperty } from '../../util/util';
/**
* @private
*/
@Directive({
selector: 'ion-backdrop',
host: {
'role': 'presentation',
... | () {
if (this._gestureID) {
this._gestureCtrl.enableScroll(this._gestureID);
}
}
getNativeElement(): HTMLElement {
return this._elementRef.nativeElement;
}
}
| ngOnDestroy | identifier_name |
backdrop.ts | import { Directive, ElementRef, Input } from '@angular/core';
import { DisableScroll, GestureController, GestureDelegate } from '../../gestures/gesture-controller';
import { isTrueProperty } from '../../util/util';
/**
* @private
*/
@Directive({
selector: 'ion-backdrop',
host: {
'role': 'presentation',
... | this._gestureCtrl.disableScroll(this._gestureID);
}
}
ngOnDestroy() {
if (this._gestureID) {
this._gestureCtrl.enableScroll(this._gestureID);
}
}
getNativeElement(): HTMLElement {
return this._elementRef.nativeElement;
}
} | random_line_split | |
bin_test.js | /**
* Test for fur bin.
* Runs with mocha.
*/
'use strict'
const assert = require('assert')
const fs = require('fs')
const furBin = require.resolve('../bin/fur')
const execcli = require('execcli')
const mkdirp = require('mkdirp')
let tmpDir = __dirname + '/../tmp'
describe('bin', function () {
this.timeout(24... | })
it('Generate banner', async () => {
let filename = tmpDir + '/testing-bin-banner.png'
await execcli(furBin, [ 'banner', filename ])
assert.ok(fs.existsSync(filename))
})
})
/* global describe, before, after, it */ |
it('Generate favicon', async () => {
let filename = tmpDir + '/testing-bin-favicon.png'
await execcli(furBin, [ 'favicon', filename ])
assert.ok(fs.existsSync(filename)) | random_line_split |
postsCtrl.js | angular.module('fishTank')
.controller('PostsCtrl', [
'$scope',
'postsFactory',
'post',
function($scope, postsFactory, post){
$("input.tags").tagsinput('items')
// $("input.form-control").show()
$scope.post = post;
$scope.incrementUpvotes = function(comment) {
postsFactor... | $scope.error = xhr.data.error
});
}
}]); | };
var errors = function() {
$scope.$on('devise:unauthorized', function(event, xhr, deferred) { | random_line_split |
postsCtrl.js | angular.module('fishTank')
.controller('PostsCtrl', [
'$scope',
'postsFactory',
'post',
function($scope, postsFactory, post){
$("input.tags").tagsinput('items')
// $("input.form-control").show()
$scope.post = post;
$scope.incrementUpvotes = function(comment) {
postsFactor... |
postsFactory.addComment(post.id, {
body: $scope.body,
author: 'user'
}).success(function(comment) {
$scope.post.comments.push(comment)
});
$scope.body = '';
};
var errors = function() {
$scope.$on('devise:unauthorized', function(event, ... | {return;} | conditional_block |
gulpfile.js | var gulp = require('gulp');
var paths = {
scripts: ['js/**/*.js']
};
/**
* Run test once and exit
*/
gulp.task('test', function (done) {
new (require('karma').Server)({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('lint', function () {
va... |
gulp.task('patch', function() { return inc('patch'); })
gulp.task('feature', function() { return inc('minor'); })
gulp.task('release', function() { return inc('major'); }) | {
var git = require('gulp-git'),
bump = require('gulp-bump'),
filter = require('gulp-filter'),
tag_version = require('gulp-tag-version');
// get all the files to bump version in
return gulp.src(['./package.json', './bower.json'])
// bump the version number in those files
... | identifier_body |
gulpfile.js | var gulp = require('gulp');
var paths = {
scripts: ['js/**/*.js']
};
/**
* Run test once and exit
*/
gulp.task('test', function (done) {
new (require('karma').Server)({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('lint', function () {
va... | (importance) {
var git = require('gulp-git'),
bump = require('gulp-bump'),
filter = require('gulp-filter'),
tag_version = require('gulp-tag-version');
// get all the files to bump version in
return gulp.src(['./package.json', './bower.json'])
// bump the version number in th... | inc | identifier_name |
gulpfile.js | var gulp = require('gulp');
var paths = {
scripts: ['js/**/*.js']
};
/**
* Run test once and exit
*/
gulp.task('test', function (done) {
new (require('karma').Server)({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('lint', function () {
va... |
gulp.task('build', function (callback) {
require('run-sequence')('lint', 'test', 'scripts', callback);
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['lint', 'test']);
// Versioning tasks
/**
* Increments a version value within the package json and bower json
*/
function i... | }))
.pipe(rename("circuits-min.js"))
.pipe(gulp.dest('./'));
}); | random_line_split |
o-list-item-text.component.ts | import {
AfterViewInit,
Component,
ElementRef,
forwardRef,
Inject,
Injector,
OnInit,
Optional,
Renderer2,
ViewEncapsulation,
} from '@angular/core';
import { OListItemComponent } from '../../list-item/o-list-item.component';
import {
DEFAULT_INPUTS_O_TEXT_RENDERER,
DEFAULT_OUTPUTS_O_TEXT_RENDER... |
}
ngAfterViewInit() {
this.modifyMatListItemElement();
}
get iconPosition(): string {
return this._iconPosition;
}
set iconPosition(val: string) {
this._iconPosition = val;
}
}
| {
this.iconPosition = this.ICON_POSITION_RIGHT;
} | conditional_block |
o-list-item-text.component.ts | import {
AfterViewInit,
Component,
ElementRef,
forwardRef,
Inject,
Injector,
OnInit,
Optional,
Renderer2,
ViewEncapsulation,
} from '@angular/core';
import { OListItemComponent } from '../../list-item/o-list-item.component';
import {
DEFAULT_INPUTS_O_TEXT_RENDERER,
DEFAULT_OUTPUTS_O_TEXT_RENDER... | (): string {
return this._iconPosition;
}
set iconPosition(val: string) {
this._iconPosition = val;
}
}
| iconPosition | identifier_name |
o-list-item-text.component.ts | import {
AfterViewInit,
Component,
ElementRef, | Renderer2,
ViewEncapsulation,
} from '@angular/core';
import { OListItemComponent } from '../../list-item/o-list-item.component';
import {
DEFAULT_INPUTS_O_TEXT_RENDERER,
DEFAULT_OUTPUTS_O_TEXT_RENDERER,
OListItemTextRenderer,
} from '../o-list-item-text-renderer.class';
export const DEFAULT_INPUTS_O_LIST_I... | forwardRef,
Inject,
Injector,
OnInit,
Optional, | random_line_split |
o-list-item-text.component.ts | import {
AfterViewInit,
Component,
ElementRef,
forwardRef,
Inject,
Injector,
OnInit,
Optional,
Renderer2,
ViewEncapsulation,
} from '@angular/core';
import { OListItemComponent } from '../../list-item/o-list-item.component';
import {
DEFAULT_INPUTS_O_TEXT_RENDERER,
DEFAULT_OUTPUTS_O_TEXT_RENDER... |
get iconPosition(): string {
return this._iconPosition;
}
set iconPosition(val: string) {
this._iconPosition = val;
}
}
| {
this.modifyMatListItemElement();
} | identifier_body |
common.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 ... |
pub fn indenter() -> _indenter {
debug!(">>");
_indenter(())
}
pub fn field_expr(f: ast::field) -> @ast::expr { return f.node.expr; }
pub fn field_exprs(fields: ~[ast::field]) -> ~[@ast::expr] {
fields.map(|f| f.node.expr)
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// o... | {
_indenter {
_i: ()
}
} | identifier_body |
common.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 ... | <T>(do_it: bool, what: ~str, thunk: &fn() -> T) -> T {
if !do_it { return thunk(); }
let start = std::time::precise_time_s();
let rv = thunk();
let end = std::time::precise_time_s();
io::println(fmt!("time: %3.3f s\t%s", end - start, what));
rv
}
pub fn indent<R>(op: &fn() -> R) -> R {
// U... | time | identifier_name |
common.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 ... | debug!(">>");
let r = op();
debug!("<< (Result = %?)", r);
r
}
pub struct _indenter {
_i: (),
}
impl Drop for _indenter {
fn finalize(&self) { debug!("<<"); }
}
pub fn _indenter(_i: ()) -> _indenter {
_indenter {
_i: ()
}
}
pub fn indenter() -> _indenter {
debug!(">>");
... |
pub fn indent<R>(op: &fn() -> R) -> R {
// Use in conjunction with the log post-processor like `src/etc/indenter`
// to make debug output more readable. | random_line_split |
vr_event.rs | use {VRDisplayData, VRGamepadData, VRGamepadState};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VREvent {
Display(VRDisplayEvent),
Gamepad(VRGamepadEvent),
}
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialization", derive(Deser... | (self) -> VREvent {
VREvent::Display(self)
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VRGamepadEvent {
/// Indicates that a VRGamepad has been connected.
/// params: name, displa_id, state
Connect(VRGamepadData, VRGamepadSt... | into | identifier_name |
vr_event.rs | use {VRDisplayData, VRGamepadData, VRGamepadState};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VREvent {
Display(VRDisplayEvent),
Gamepad(VRGamepadEvent),
}
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialization", derive(Deser... | Pause(u32),
/// Indicates that VRDisplay presentation loop must be resumed (i.e Android app goes to foreground)
Resume(u32),
/// Indicates that user has exited VRDisplay presentation (i.e. User clicked back key on android)
Exit(u32)
}
impl Into<VREvent> for VRDisplayEvent {
fn into(self) -> V... | PresentChange(VRDisplayData, bool),
/// Indicates that VRDisplay presentation loop must be paused (i.e Android app goes to background) | random_line_split |
0004_auto_20141229_1211.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
| dependencies = [
('feed', '0003_auto_20141227_2343'),
]
operations = [
migrations.AddField(
model_name='newsarticle',
name='created',
field=models.DateTimeField(default=datetime.datetime(2014, 12, 29, 11, 11, 7, 540368, tzinfo=utc), auto_now_add=True),
... | identifier_body | |
0004_auto_20141229_1211.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.utils.timezone import utc
import datetime
class | (migrations.Migration):
dependencies = [
('feed', '0003_auto_20141227_2343'),
]
operations = [
migrations.AddField(
model_name='newsarticle',
name='created',
field=models.DateTimeField(default=datetime.datetime(2014, 12, 29, 11, 11, 7, 540368, tzinfo=utc... | Migration | identifier_name |
0004_auto_20141229_1211.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.utils.timezone import utc |
dependencies = [
('feed', '0003_auto_20141227_2343'),
]
operations = [
migrations.AddField(
model_name='newsarticle',
name='created',
field=models.DateTimeField(default=datetime.datetime(2014, 12, 29, 11, 11, 7, 540368, tzinfo=utc), auto_now_add=True),
... | import datetime
class Migration(migrations.Migration): | random_line_split |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
#[cfg(test)]
mod test {
use super::{try_finally, Finally};
use realstd::task::failing;
#[test]
fn test_success() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
},
|i| {
assert!(!failing());... | {
(self.dtor)(self.mutate);
} | identifier_body |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | "finally" case. For advanced cases, the `try_finally` function can
also be used. See that function for more details.
# Example
```
use std::unstable::finally::Finally;
(|| {
// ...
}).finally(|| {
// this code is always run
})
```
*/
#![experimental]
use ops::Drop;
/// A trait for executing a destructor u... | The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
Using the `finally` method is sometimes convenient, but the type rules
prohibit any shared, mutable state between the "try" case and the | random_line_split |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
fn but_always_run_this_function() { }
let mut f = do_some_fallible_work;
f.finally(but_always_run_this_function);
}
}
| do_some_fallible_work | identifier_name |
VirtualTimeScheduler.ts | import { AsyncAction } from './AsyncAction';
import { Subscription } from '../Subscription';
import { AsyncScheduler } from './AsyncScheduler';
export class VirtualTimeScheduler extends AsyncScheduler {
protected static frameTimeFactor: number = 10;
public frame: number = 0;
public index: number = -1;
const... | <VirtualAction<T>> this.add(
new VirtualAction<T>(this.scheduler, this.work))
).schedule(state, delay);
}
protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): any {
this.delay = scheduler.frame + delay;
const {actions} = scheduler;
actions.push(thi... | // must be immutable so they can be inspected later. | random_line_split |
VirtualTimeScheduler.ts | import { AsyncAction } from './AsyncAction';
import { Subscription } from '../Subscription';
import { AsyncScheduler } from './AsyncScheduler';
export class VirtualTimeScheduler extends AsyncScheduler {
protected static frameTimeFactor: number = 10;
public frame: number = 0;
public index: number = -1;
const... |
}
if (error) {
while (action = actions.shift()) {
action.unsubscribe();
}
throw error;
}
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class VirtualAction<T> extends AsyncAction<T> {
constructor(protected scheduler: V... | {
break;
} | conditional_block |
VirtualTimeScheduler.ts | import { AsyncAction } from './AsyncAction';
import { Subscription } from '../Subscription';
import { AsyncScheduler } from './AsyncScheduler';
export class VirtualTimeScheduler extends AsyncScheduler {
protected static frameTimeFactor: number = 10;
public frame: number = 0;
public index: number = -1;
const... |
protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): any {
this.delay = scheduler.frame + delay;
const {actions} = scheduler;
actions.push(this);
actions.sort(VirtualAction.sortActions);
return true;
}
protected recycleAsyncId(scheduler: VirtualTimeSchedul... | {
return !this.id ?
super.schedule(state, delay) : (
// If an action is rescheduled, we save allocations by mutating its state,
// pushing it to the end of the scheduler queue, and recycling the action.
// But since the VirtualTimeScheduler is used for testing, VirtualActions
// must b... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.