file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The `servo` test application.
//!
//! Creates a `Servo` instance with a simple implementation of
//! the comp... | () {
println!(
"Cannot start /ports/servo/ on Android. \
Use /support/android/apk/ + /ports/libsimpleservo/ instead"
);
}
| main | identifier_name |
main.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The `servo` test application.
//!
//! Creates a `Servo` instance with a simple implementation of
//! the comp... | extern crate log;
#[cfg(not(target_os = "android"))]
include!("non_android_main.rs");
#[cfg(target_os = "android")]
pub fn main() {
println!(
"Cannot start /ports/servo/ on Android. \
Use /support/android/apk/ + /ports/libsimpleservo/ instead"
);
} |
// Have this here rather than in non_android_main.rs to work around
// https://github.com/rust-lang/rust/issues/53205
#[cfg(not(target_os = "android"))]
#[macro_use] | random_line_split |
main.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The `servo` test application.
//!
//! Creates a `Servo` instance with a simple implementation of
//! the comp... | {
println!(
"Cannot start /ports/servo/ on Android. \
Use /support/android/apk/ + /ports/libsimpleservo/ instead"
);
} | identifier_body | |
function-call.rs | // This test does not passed with gdb < 8.0. See #53497.
// min-gdb-version: 10.1
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print fun(45, true)
// gdb-check:$1 = true
// gdb-command:print fun(444, false)... | let _ = r.get_x();
zzz(); // #break
}
fn fun(x: isize, y: bool) -> bool {
y
}
fn zzz() { () } |
fn main() {
let _ = fun(4, true);
let r = RegularStruct{x: 4}; | random_line_split |
function-call.rs | // This test does not passed with gdb < 8.0. See #53497.
// min-gdb-version: 10.1
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print fun(45, true)
// gdb-check:$1 = true
// gdb-command:print fun(444, false)... | () {
let _ = fun(4, true);
let r = RegularStruct{x: 4};
let _ = r.get_x();
zzz(); // #break
}
fn fun(x: isize, y: bool) -> bool {
y
}
fn zzz() { () }
| main | identifier_name |
completionListAfterNumericLiteral.ts | /// <reference path='fourslash.ts' />
// @Filename: f1.ts
////0./*dotOnNumberExpressions1*/
// @Filename: f2.ts
////0.0./*dotOnNumberExpressions2*/
// @Filename: f3.ts
////0.0.0./*dotOnNumberExpressions3*/
// @Filename: f4.ts
////0./** comment *//*dotOnNumberExpressions4*/
// @Filename: f5.ts
////(0... | marker: ["dotOnNumberExpressions2", "dotOnNumberExpressions3", "validDotOnNumberExpressions1", "validDotOnNumberExpressions2", "validDotOnNumberExpressions3"],
includes: "toExponential"
},
); | random_line_split | |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵrenderComponent as renderComponent, ɵRenderFlags, ɵɵadvance, ɵɵcontainer, ɵɵcontainerRefreshEnd, ɵɵcontaine... | (1);
ɵɵstyleProp('background-color', ctx.depth % 2 ? '' : 'grey');
ɵɵadvance(1);
ɵɵtextInterpolate1(' ', ctx.value, ' ');
ɵɵcontainerRefreshStart(3);
{
if (ctx.left != null) {
let rf0 = ɵɵembeddedViewStart(0, 5, 2);
{ TreeTpl(rf0, ctx.left); }
ɵɵembeddedViewEnd();
... | {
ɵɵelementStart(1, 'span');
{ ɵɵtext(2); }
ɵɵelementEnd();
ɵɵcontainer(3);
ɵɵcontainer(4);
}
ɵɵelementEnd();
}
if (rf & ɵRenderFlags.Update) {
ɵɵadvance | conditional_block |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵrenderComponent as renderComponent, ɵRenderFlags, ɵɵadvance, ɵɵcontainer, ɵɵcontainerRefreshEnd, ɵɵcontaine... | template:
function(rf: ɵRenderFlags, ctx: TreeFunction) {
// bit of a hack
TreeTpl(rf, ctx.data);
},
inputs: {data: 'data'}
});
}
const TreeFunctionCmpDef = TreeFunction.ɵcmp as {decls: number, vars: number};
export function TreeTpl(rf: ɵRenderFlags, ctx: TreeNode) {
if ... | vars: 2, | random_line_split |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵrenderComponent as renderComponent, ɵRenderFlags, ɵɵadvance, ɵɵcontainer, ɵɵcontainerRefreshEnd, ɵɵcontaine... | yTree;
/** @nocollapse */
static ɵfac = () => new TreeFunction;
/** @nocollapse */
static ɵcmp = ɵɵdefineComponent({
type: TreeFunction,
selectors: [['tree']],
decls: 5,
vars: 2,
template:
function(rf: ɵRenderFlags, ctx: TreeFunction) {
// bit of a hack
TreeTpl(... | eNode = empt | identifier_name |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵrenderComponent as renderComponent, ɵRenderFlags, ɵɵadvance, ɵɵcontainer, ɵɵcontainerRefreshEnd, ɵɵcontaine... | { TreeTpl(rf0, ctx.left); }
ɵɵembeddedViewEnd();
}
}
ɵɵcontainerRefreshEnd();
ɵɵcontainerRefreshStart(4);
{
if (ctx.right != null) {
let rf0 = ɵɵembeddedViewStart(0, TreeFunctionCmpDef.decls, TreeFunctionCmpDef.vars);
{ TreeTpl(rf0, ctx.right); }
ɵɵemb... | {
ɵɵelementStart(0, 'tree');
{
ɵɵelementStart(1, 'span');
{ ɵɵtext(2); }
ɵɵelementEnd();
ɵɵcontainer(3);
ɵɵcontainer(4);
}
ɵɵelementEnd();
}
if (rf & ɵRenderFlags.Update) {
ɵɵadvance(1);
ɵɵstyleProp('background-color', ctx.depth % 2 ? '' : 'grey');
ɵɵadvanc... | identifier_body |
CustomSeparator.tsx | import * as React from 'react';
import Breadcrumbs from '@material-ui/core/Breadcrumbs';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
import Stack from '@material-ui/core/Stack';
import NavigateNextIcon from '@material-ui/icons/NavigateNext';
function handleClick(ev... | <Breadcrumbs separator="›" aria-label="breadcrumb">
{breadcrumbs}
</Breadcrumbs>
<Breadcrumbs separator="-" aria-label="breadcrumb">
{breadcrumbs}
</Breadcrumbs>
<Breadcrumbs
separator={<NavigateNextIcon fontSize="small" />}
aria-label="breadcrumb"
>
... | {
const breadcrumbs = [
<Link key="1" color="inherit" href="/" onClick={handleClick}>
Material-UI
</Link>,
<Link
key="2"
color="inherit"
href="/getting-started/installation/"
onClick={handleClick}
>
Core
</Link>,
<Typography key="3" color="text.primary">
... | identifier_body |
CustomSeparator.tsx | import * as React from 'react';
import Breadcrumbs from '@material-ui/core/Breadcrumbs';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
import Stack from '@material-ui/core/Stack';
import NavigateNextIcon from '@material-ui/icons/NavigateNext';
function handleClick(ev... | </Stack>
);
} | random_line_split | |
CustomSeparator.tsx | import * as React from 'react';
import Breadcrumbs from '@material-ui/core/Breadcrumbs';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
import Stack from '@material-ui/core/Stack';
import NavigateNextIcon from '@material-ui/icons/NavigateNext';
function | (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) {
event.preventDefault();
console.info('You clicked a breadcrumb.');
}
export default function CustomSeparator() {
const breadcrumbs = [
<Link key="1" color="inherit" href="/" onClick={handleClick}>
Material-UI
</Link>,
<Link
key="2... | handleClick | identifier_name |
package-version-file-types-view.js | /******************************************************************************\
| |
| package-version-file-types-view.js |
| ... |
}
});
});
| {
this.onClickOk();
this.hide();
} | conditional_block |
package-version-file-types-view.js | /******************************************************************************\
| |
| package-version-file-types-view.js |
| ... |
// callbacks
//
success: function(data) {
var collection = new Backbone.Collection();
for (var key in data) {
collection.add(new Backbone.Model({
'extension': key,
'count': data[key]
}));
}
self.fileTypes.show(
new FileTypesListView({
collectio... | var self = this;
this.model.fetchFileTypes({
data: {
'dirname': this.options.packagePath
}, | random_line_split |
Improvement.js | function Improvement(options) {
this.name = options.name;
this.image = options.image;
this.depth = options.depth || 0;
this.parent = options.parent;
this.children = options.children || []; |
this.cost = options.cost;
this.materials = options.materials;
this.buildEvent = 'event:'+options.buildEvent;
}
Improvement.prototype = {
/*
* The build function will build the improvement, adding it to the list of
* improvements built in the GameState and removing the needed materials
* from the ch... | this.siblings = options.siblings || [];
this.toDisplay = options.toDisplay || [];
this.toBuild = options.toBuild || []; | random_line_split |
Improvement.js |
function Improvement(options) {
this.name = options.name;
this.image = options.image;
this.depth = options.depth || 0;
this.parent = options.parent;
this.children = options.children || [];
this.siblings = options.siblings || [];
this.toDisplay = options.toDisplay || [];
this.toBuild = options.toBuild ... |
return true;
},
/*
* Function used to check to see if the improvement can be built regardless
* of whether the character has the materials or not. If this improvement
* has a parent location that hasn't been built then this improvement cannot
* be built. If this improvement has any sibling improv... | {
if (GameState.isImprovementBuilt(this.children[i])) {
return false;
}
} | conditional_block |
Improvement.js |
function Improvement(options) |
Improvement.prototype = {
/*
* The build function will build the improvement, adding it to the list of
* improvements built in the GameState and removing the needed materials
* from the character's inventory.
*/
build: function() {
GameState.buildImprovement(this.code);
var character = Game... | {
this.name = options.name;
this.image = options.image;
this.depth = options.depth || 0;
this.parent = options.parent;
this.children = options.children || [];
this.siblings = options.siblings || [];
this.toDisplay = options.toDisplay || [];
this.toBuild = options.toBuild || [];
this.cost = options.c... | identifier_body |
Improvement.js |
function | (options) {
this.name = options.name;
this.image = options.image;
this.depth = options.depth || 0;
this.parent = options.parent;
this.children = options.children || [];
this.siblings = options.siblings || [];
this.toDisplay = options.toDisplay || [];
this.toBuild = options.toBuild || [];
this.cost =... | Improvement | identifier_name |
pyoptic.py | self, gitem, **defaults)
def propagateRay(self, ray):
"""Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays"""
surface = self.surfaces[0]
p1, ai = surface.intersectRay(ray)
if p1 is not None:
p1 = surface.mapToItem... | hildren(self) | identifier_name | |
pyoptic.py | (object):
# Just a helper for tracking parameters and responding to changes
def __init__(self):
self.__params = {}
def __setitem__(self, item, val):
self.setParam(item, val)
def setParam(self, param, val):
self.setParams(**{param:val})
def setParams(sel... |
def propagateRay(self, ray):
"""Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays"""
"""
NOTE:: We can probably use this to compute refractions faster: (from GLSL 120 docs)
For the incident vector I and surface normal N, and the
... | Optic.__init__(self, gitem, **defaults) | random_line_split |
pyoptic.py | surface = self.surfaces[i]
ior = iors[i]
p1, ai = surface.intersectRay(ray)
#print "surface intersection:", p1, ai*180/3.14159
#trans = self.sceneTransform().inverted()[0] * surface.sceneTransform()
#p1 = trans.map(p1)
if p1 is None:
... | ir[0]
dy = dir[1]
dr = (dx**2 + dy**2) ** 0.5
D = p[0] * (p[1]+dy) - (p[0]+dx) * p[1]
idr2 = 1.0 / dr**2
disc = r**2 * dr**2 - D**2
if disc < 0:
return None, None
disc2 = disc**0.5
if dy < 0:
... | conditional_block | |
pyoptic.py | ray. This function may create and return new rays"""
surface = self.surfaces[0]
p1, ai = surface.intersectRay(ray)
if p1 is not None:
p1 = surface.mapToItem(ray, p1)
rd = ray['dir']
a1 = np.arctan2(rd[1], rd[0])
ar = a1 + np.pi - 2*ai
... | in self.children:
c.clearChildren()
c.setParentItem(None)
self.scene().removeItem(c)
self.children = []
| identifier_body | |
tamilvu_wordlist.py | #!/usr/bin/python
# (C) 2015 Muthiah Annamalai, <ezhillang@gmail.com>
# Ezhil Language Foundation
#
from __future__ import print_function
import sys
import codecs
import tamil
import json
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
class WordList:
@staticmethod
def extract_words(filename):
... |
if __name__ == u"__main__":
# WordList.pull_words_from_json()
for wlen in range(3,20):
WordFilter.filter_and_save( wlen )
| @staticmethod
def filter_and_save(word_size=4):
match_word_length = lambda word: len(tamil.utf8.get_letters(word.strip().replace(' ',''))) == word_size
filename = u'tamilvu_dictionary_words.txt'
matches = []
with codecs.open(filename,'r','utf-8') as fp:
matches = filter( ... | identifier_body |
tamilvu_wordlist.py | #!/usr/bin/python
# (C) 2015 Muthiah Annamalai, <ezhillang@gmail.com>
# Ezhil Language Foundation
#
from __future__ import print_function
import sys
import codecs
import tamil
import json
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
class WordList:
@staticmethod
def | (filename):
ht = json.load( codecs.open(filename,'r','utf-8') )
for word in sorted(ht.keys()):
print(word)
return
@staticmethod
def pull_words_from_json():
for itr in range(1,25):
filename = u"v%02d.json"%itr
WordList.extract_words(filenam... | extract_words | identifier_name |
tamilvu_wordlist.py | #!/usr/bin/python | import sys
import codecs
import tamil
import json
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
class WordList:
@staticmethod
def extract_words(filename):
ht = json.load( codecs.open(filename,'r','utf-8') )
for word in sorted(ht.keys()):
print(word)
return
@st... | # (C) 2015 Muthiah Annamalai, <ezhillang@gmail.com>
# Ezhil Language Foundation
#
from __future__ import print_function | random_line_split |
tamilvu_wordlist.py | #!/usr/bin/python
# (C) 2015 Muthiah Annamalai, <ezhillang@gmail.com>
# Ezhil Language Foundation
#
from __future__ import print_function
import sys
import codecs
import tamil
import json
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
class WordList:
@staticmethod
def extract_words(filename):
... | for wlen in range(3,20):
WordFilter.filter_and_save( wlen ) | conditional_block | |
util.rs | #![allow(clippy::declare_interior_mutable_const)]
use std::{
cell::{RefCell, RefMut},
cmp,
convert::Infallible,
io,
};
use xitca_web::{
dev::bytes::{Bytes, BytesMut},
http::{
header::{HeaderValue, SERVER},
StatusCode,
},
response::{WebResponse, WebResponseBuilder},
};
... | (&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.extend_from_slice(buf);
Ok(buf.len())
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
pub(super) trait QueryParse {
fn parse_query(self) -> u16;
}
impl QueryParse for Option<&str> {
fn parse_query(sel... | write | identifier_name |
util.rs | #![allow(clippy::declare_interior_mutable_const)]
use std::{
cell::{RefCell, RefMut},
cmp,
convert::Infallible,
io,
};
use xitca_web::{
dev::bytes::{Bytes, BytesMut},
http::{
header::{HeaderValue, SERVER},
StatusCode,
},
response::{WebResponse, WebResponseBuilder},
};
... | pub(super) struct AppState<C> {
client: C,
// a re-usable buffer for write response data.
write_buf: RefCell<BytesMut>,
}
impl<C> AppState<C> {
pub(super) fn new(client: C) -> Self {
let write_buf = RefCell::new(BytesMut::new());
Self { client, write_buf }
}
#[inline]
pub(s... | cmp::min(500, cmp::max(1, num))
}
}
| random_line_split |
util.rs | #![allow(clippy::declare_interior_mutable_const)]
use std::{
cell::{RefCell, RefMut},
cmp,
convert::Infallible,
io,
};
use xitca_web::{
dev::bytes::{Bytes, BytesMut},
http::{
header::{HeaderValue, SERVER},
StatusCode,
},
response::{WebResponse, WebResponseBuilder},
};
... |
#[inline]
pub(super) fn writer(&self) -> Writer<'_> {
Writer(self.write_buf.borrow_mut())
}
#[inline]
pub(super) fn client(&self) -> &C {
&self.client
}
}
pub const SERVER_HEADER_VALUE: HeaderValue = HeaderValue::from_static("TFB");
pub const HTML_HEADER_VALUE: HeaderValue =... | {
let write_buf = RefCell::new(BytesMut::new());
Self { client, write_buf }
} | identifier_body |
km.js | /*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
| insertOption: 'ជំនួសក្នុងមាតិកាបច្ចុប្បន្ន',
options: 'ជម្រើសពុម្ពគំរូ',
selectPromptMsg: 'សូមរើសពុម្ពគំរូដើម្បីបើកក្នុងកម្មវិធីសរសេរអត្ថបទ',
title: 'ពុម្ពគំរូមាតិកា'
}); | For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'templates', 'km', {
button: 'ពុម្ពគំរូ',
emptyListMsg: '(មិនមានពុម្ពគំរូត្រូវបានកំណត់)',
| random_line_split |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... |
if (conflictFields.length > 0) {
notify.info('Not adding ' + conflictFields.length + ' duplicate fields: ' + conflictFields.join(', '));
}
};
$scope.create = function () {
const params = {
indexPattern: $scope.indexPattern.id
};
kbnUrl.change(f... | {
notify.info(fieldsAdded + ' script fields created');
} | conditional_block |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... | () {
_.invoke(rowScopes, '$destroy');
rowScopes.length = 0;
const fields = filter($scope.indexPattern.getScriptedFields(), $scope.fieldFilter);
_.find($scope.editSections, {index: 'scriptedFields'}).count = fields.length; // Update the tab count
$scope.rows = fields.map(functio... | refreshRows | identifier_name |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... | }
];
});
}
$scope.addDateScripts = function () {
const conflictFields = [];
let fieldsAdded = 0;
_.each(dateScripts($scope.indexPattern), function (script, field) {
try {
$scope.indexPattern.addScriptedField(field, script, 'number... | {
_.invoke(rowScopes, '$destroy');
rowScopes.length = 0;
const fields = filter($scope.indexPattern.getScriptedFields(), $scope.fieldFilter);
_.find($scope.editSections, {index: 'scriptedFields'}).count = fields.length; // Update the tab count
$scope.rows = fields.map(function (... | identifier_body |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... | }
};
}); | }; | random_line_split |
0003_votetoken.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-28 17:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('voting', '0002_auto_20150813_2010'),
]
operations = [
migrations.CreateModel(
name='VoteToken',
fields=[
('id', models.AutoField(auto_create... | Migration | identifier_name |
0003_votetoken.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-28 17:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
(... | ],
),
] | random_line_split | |
0003_votetoken.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-28 17:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('voting', '0002_auto_20150813_2010'),
]
operations = [
migrations.CreateModel(
name='VoteToken',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, ser... | identifier_body | |
websiteParser.py | from IPython.display import HTML
from bs4 import BeautifulSoup
import urllib
f = open('chars.txt', 'w')
r = urllib.urlopen('http://www.eventhubs.com/tiers/ssb4/').read()
soup = BeautifulSoup(r, "lxml")
characters = soup.find_all("td", class_="tierstdnorm")
count = 1
tierCharList=[]
for element in characters:
if ... |
count+=1
tierCharList.remove(tierCharList[len(tierCharList)-1])
for x in range(0,len(tierCharList)):
f.write(tierCharList[x])
f.write("\n")
| character = element.get_text()
tierChar = tier + "," + character
tierCharList.append(tierChar) | conditional_block |
websiteParser.py | from IPython.display import HTML
from bs4 import BeautifulSoup
import urllib
f = open('chars.txt', 'w')
r = urllib.urlopen('http://www.eventhubs.com/tiers/ssb4/').read()
soup = BeautifulSoup(r, "lxml")
characters = soup.find_all("td", class_="tierstdnorm")
count = 1
tierCharList=[]
for element in characters:
if ... | elif count%12==2:
character = element.get_text()
tierChar = tier + "," + character
tierCharList.append(tierChar)
count+=1
tierCharList.remove(tierCharList[len(tierCharList)-1])
for x in range(0,len(tierCharList)):
f.write(tierCharList[x])
f.write("\n") | character = element.get_text()
tierChar = tier + "," + character
tierCharList.append(tierChar)
elif count%12==1:
tier = element.get_text() | random_line_split |
exhaust.ts |
import { Observable } from '../../Observable';
import { exhaust as higherOrder } from '../../operators/exhaust';
import { ObservableInput } from '../../types';
export function exhaust<T>(this: Observable<ObservableInput<T>>): Observable<T>;
export function exhaust<T, R>(this: Observable<T>): Observable<R>;
/**
* Co... | <T>(this: Observable<ObservableInput<T>>): Observable<T> {
return higherOrder<T>()(this);
}
| exhaust | identifier_name |
exhaust.ts |
import { Observable } from '../../Observable';
import { exhaust as higherOrder } from '../../operators/exhaust';
import { ObservableInput } from '../../types';
export function exhaust<T>(this: Observable<ObservableInput<T>>): Observable<T>;
export function exhaust<T, R>(this: Observable<T>): Observable<R>;
/**
* Co... | {
return higherOrder<T>()(this);
} | identifier_body | |
exhaust.ts | import { Observable } from '../../Observable';
import { exhaust as higherOrder } from '../../operators/exhaust';
import { ObservableInput } from '../../types';
export function exhaust<T>(this: Observable<ObservableInput<T>>): Observable<T>;
export function exhaust<T, R>(this: Observable<T>): Observable<R>;
/**
* Con... | * next inner Observable and repeat this process.
*
* @example <caption>Run a finite timer for each click, only if there is no currently active timer</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(5));
* var result = hig... | * `exhaust` ignores every new inner Observable if the previous Observable has
* not yet completed. Once that one completes, it will accept and flatten the | random_line_split |
component.ts | namespace Mist {
/**
* @class Component
*/
export class Component {
static responses: any = {};
/**
* @param {} component
* @param {} o
* @returns {}
* @summary for all components
*/
static create<T>(component: any, ...o: any[]): T {
... |
// lasting response
return this.responses[m][n];
}
}
/**
* @access private
* @static
*/
var sessions = 0;
/**
* @access private
* @static
*/
function ser(conv: any[]) {
return JSON.stringify(
conv.map(
... | {
this.responses[m][n] = new (
component.bind.apply(
component, [component].concat([].slice.apply(o))));
} | conditional_block |
component.ts | namespace Mist { |
/**
* @class Component
*/
export class Component {
static responses: any = {};
/**
* @param {} component
* @param {} o
* @returns {}
* @summary for all components
*/
static create<T>(component: any, ...o: any[]): T {
var m =... | random_line_split | |
component.ts | namespace Mist {
/**
* @class Component
*/
export class | {
static responses: any = {};
/**
* @param {} component
* @param {} o
* @returns {}
* @summary for all components
*/
static create<T>(component: any, ...o: any[]): T {
var m = ser([component]);
var n = ser(o);
// in... | Component | identifier_name |
component.ts | namespace Mist {
/**
* @class Component
*/
export class Component {
static responses: any = {};
/**
* @param {} component
* @param {} o
* @returns {}
* @summary for all components
*/
static create<T>(component: any, ...o: any[]): T {
... |
}
| {
return JSON.stringify(
conv.map(
function(v) {
return v instanceof Object ?
v.sessid || (v.sessid = sessions++) :
v;
}));
} | identifier_body |
test_column.py | import unittest
import pandas as pd
from pandas_schema import Column
from pandas_schema.validation import CanConvertValidation, LeadingWhitespaceValidation, TrailingWhitespaceValidation
class SingleValidationColumn(unittest.TestCase):
"""
Test a column with one single validation
"""
NAME = 'col1'
... | (self):
results = self.col.validate(self.ser)
self.assertEqual(len(results), len(self.ser), 'A Column produces the wrong number of errors')
for i in range(2):
self.assertTrue(any([r.row == i for r in results]), 'A Column does not report errors for every row')
class DoubleValidatio... | test_outputs | identifier_name |
test_column.py | import unittest
import pandas as pd
from pandas_schema import Column
from pandas_schema.validation import CanConvertValidation, LeadingWhitespaceValidation, TrailingWhitespaceValidation
class SingleValidationColumn(unittest.TestCase):
"""
Test a column with one single validation
"""
NAME = 'col1'
... | self.assertEqual(len(results), 0, 'allow_empty is not allowing empty columns') | random_line_split | |
test_column.py | import unittest
import pandas as pd
from pandas_schema import Column
from pandas_schema.validation import CanConvertValidation, LeadingWhitespaceValidation, TrailingWhitespaceValidation
class SingleValidationColumn(unittest.TestCase):
"""
Test a column with one single validation
"""
NAME = 'col1'
... |
class AllowEmptyColumn(unittest.TestCase):
"""
Test a column with one single validation that allows empty columns
"""
NAME = 'col1'
col = Column(NAME, [CanConvertValidation(int)], allow_empty=True)
ser = pd.Series([
'',
])
def test_outputs(self):
results = self.col.v... | in_row = [r for r in results if r.row == i]
self.assertEqual(len(in_row), 2, 'A Column does not report both errors for every row') | conditional_block |
test_column.py | import unittest
import pandas as pd
from pandas_schema import Column
from pandas_schema.validation import CanConvertValidation, LeadingWhitespaceValidation, TrailingWhitespaceValidation
class SingleValidationColumn(unittest.TestCase):
"""
Test a column with one single validation
"""
NAME = 'col1'
... |
def test_outputs(self):
results = self.col.validate(self.ser)
self.assertEqual(len(results), len(self.ser), 'A Column produces the wrong number of errors')
for i in range(2):
self.assertTrue(any([r.row == i for r in results]), 'A Column does not report errors for every row')
... | self.assertEqual(self.col.name, self.NAME, 'A Column does not store its name correctly') | identifier_body |
webpack-dev-server.js | require('babel-polyfill');
var Express = require('express');
var webpack = require('webpack');
var config = require('config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = config.host || 'localhost';
var port = (Number(config.port) + 1) || 3001;
var serverOptions = {
... | stats: { colors: true }
};
var app = new Express();
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err);
} else {
console.info('==> 🚧 Webpack developmen... | publicPath: webpackConfig.output.publicPath,
headers: { 'Access-Control-Allow-Origin': '*' }, | random_line_split |
webpack-dev-server.js | require('babel-polyfill');
var Express = require('express');
var webpack = require('webpack');
var config = require('config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = config.host || 'localhost';
var port = (Number(config.port) + 1) || 3001;
var serverOptions = {
... | else {
console.info('==> 🚧 Webpack development server listening on port %s', port);
}
});
| {
console.error(err);
} | conditional_block |
map.rs | #[cfg(feature = "vec_map")]
pub use vec_map::{Values, VecMap};
#[cfg(not(feature = "vec_map"))]
pub use self::vec_map::{Values, VecMap};
#[cfg(not(feature = "vec_map"))]
mod vec_map {
use std::collections::btree_map;
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
#[derive(Clo... |
pub fn contains_key(&self, key: usize) -> bool {
self.inner.contains_key(&key)
}
pub fn entry(&mut self, key: usize) -> Entry<V> {
self.inner.entry(key)
}
pub fn get(&self, key: usize) -> Option<&V> {
self.inner.get(&key)
}
}
... | {
Iter {
inner: self.inner.iter(),
}
} | identifier_body |
map.rs | #[cfg(feature = "vec_map")]
pub use vec_map::{Values, VecMap};
#[cfg(not(feature = "vec_map"))]
pub use self::vec_map::{Values, VecMap};
#[cfg(not(feature = "vec_map"))]
mod vec_map {
use std::collections::btree_map;
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
#[derive(Clo... | (&self) -> Values<V> {
self.inner.values()
}
pub fn iter(&self) -> Iter<V> {
Iter {
inner: self.inner.iter(),
}
}
pub fn contains_key(&self, key: usize) -> bool {
self.inner.contains_key(&key)
}
pub fn ent... | values | identifier_name |
map.rs | #[cfg(feature = "vec_map")]
pub use vec_map::{Values, VecMap};
#[cfg(not(feature = "vec_map"))]
pub use self::vec_map::{Values, VecMap};
#[cfg(not(feature = "vec_map"))]
mod vec_map {
use std::collections::btree_map;
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
#[derive(Clo... | self.inner.is_empty()
}
pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
self.inner.insert(key, value)
}
pub fn values(&self) -> Values<V> {
self.inner.values()
}
pub fn iter(&self) -> Iter<V> {
Iter {
... | self.inner.len()
}
pub fn is_empty(&self) -> bool { | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2011, Monash e-Research Centre
# (Monash University, Australia)
# Copyright (c) 2010-2011, VeRSI Consortium
# (Victorian eResearch Strategic Initiative, Australia)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modificatio... | try:
dot = path.rindex('.')
except ValueError:
raise ImproperlyConfigured('%s isn\'t a filter module' % path)
filter_module, filter_classname = path[:dot], path[dot + 1:]
try:
mod = import_module(filter_module)
except ImportError, e:
raise ... | identifier_body | |
__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2011, Monash e-Research Centre
# (Monash University, Australia)
# Copyright (c) 2010-2011, VeRSI Consortium
# (Victorian eResearch Strategic Initiative, Australia)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modificatio... | (object):
def __init__(self):
from tardis.tardis_portal.models import Dataset_File
for f in settings.POST_SAVE_FILTERS:
cls = f[0]
args = []
kw = {}
if len(f) == 2:
args = f[1]
if len(f) == 3:
kw = f[2]
... | FilterInitMiddleware | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2011, Monash e-Research Centre
# (Monash University, Australia)
# Copyright (c) 2010-2011, VeRSI Consortium
# (Victorian eResearch Strategic Initiative, Australia)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modificatio... | # * Neither the name of the VeRSI, the VeRSI Consortium members, nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRES... | # notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution. | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2011, Monash e-Research Centre
# (Monash University, Australia)
# Copyright (c) 2010-2011, VeRSI Consortium
# (Victorian eResearch Strategic Initiative, Australia)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modificatio... |
# disable middleware
raise MiddlewareNotUsed()
def _safe_import(self, path, args, kw):
try:
dot = path.rindex('.')
except ValueError:
raise ImproperlyConfigured('%s isn\'t a filter module' % path)
filter_module, filter_classname = path[:dot], path[d... | cls = f[0]
args = []
kw = {}
if len(f) == 2:
args = f[1]
if len(f) == 3:
kw = f[2]
hook = self._safe_import(cls, args, kw)
# XXX seems to requre a strong ref else it won't fire,
# could be because some... | conditional_block |
test.js | 'use strict';
var Command = require('../models/command');
var SilentError = require('silent-error');
var path = require('path');
var defaultPort = 7357;
module.exports = Command.extend({
name: 'test',
description: 'Runs your app\'s test suite.',
aliases: ['t'],
availableOptions: [
{ name: 'en... | }); | random_line_split | |
test.js | 'use strict';
var Command = require('../models/command');
var SilentError = require('silent-error');
var path = require('path');
var defaultPort = 7357;
module.exports = Command.extend({
name: 'test',
description: 'Runs your app\'s test suite.',
aliases: ['t'],
availableOptions: [
{ name: 'en... |
var testPage = options['test-page'];
var queryString = this.buildTestPageQueryString(options);
if (testPage) {
var containsQueryString = testPage.indexOf('?') > -1;
var testPageJoinChar = containsQueryString ? '&' : '?';
config.testPage = testPage + testPageJoinChar + queryString;
... | { return config; } | conditional_block |
index.js | // Carregar base de dados
const escolas = require('./db/escolas.json')
// Busca Fuzzy
const Fuse = require('fuse.js')
const fuse_options = {
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"escola"
]
}
const fuse... | buttons: [{
type: "postback",
title: "Info Nutricional",
payload: "INFO_NUTRICIONAL"
}]
},
{
title: "Feijão",
image_url: "http://g.glbimg.com/og/gs/gsat5/f/thumbs/tag/2015/07/14/feijao-620_1.jpg",
subtitle: "Feijão, cozido",
but... | random_line_split | |
index.js | ('./db/escolas.json')
// Busca Fuzzy
const Fuse = require('fuse.js')
const fuse_options = {
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"escola"
]
}
const fuse = new Fuse(escolas, fuse_options)
// Botly - Ge... | .use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: false
}));
app.use("/ | conditional_block | |
AchievementsMenu.js | /**
* Menu showing the player's unlocked achievements.
*
* @class AchievementsMenu
* @extends Menu
* @constructor
*/
function AchievementsMenu() {
// call the parent constructor
Menu.call(this);
// add custom buttons
var mainMenu = new Button("mainMenu", "Return to menu", (layout.getWidth()/2)-(this.but... |
}
/**
* Checks for button presses and responds appropriately.
*
* @override
* @method mouseClicked
* @param {Number} mouseX The mouse's X co-ordinate
* @param {Number} mouseY The mouse's Y co-ordinate
*/
AchievementsMenu.prototype.mouseClicked = function(mouseX,mouseY) {
for(var i = 0; i < this.buttons.l... | {
// draw box
context.fillStyle = "black";
context.fillRect(
(layout.getWidth()/100)*35-(this.button_width),
layout.getSandLevel()+15,
(layout.getWidth() /100) *80,
25
);
// write message
context.fillStyle = "#FFFFFF";
context.font = "12px Verdana";
context.textAlign = 'ce... | conditional_block |
AchievementsMenu.js | /**
* Menu showing the player's unlocked achievements.
*
* @class AchievementsMenu
* @extends Menu
* @constructor
*/
function AchievementsMenu() {
// call the parent constructor
Menu.call(this);
// add custom buttons
var mainMenu = new Button("mainMenu", "Return to menu", (layout.getWidth()/2)-(this.but... | (this.buttons[i].getX()+this.buttons[i].getWidth())-iconSize,
(this.buttons[i].getY()+this.buttons[i].getHeight())-iconSize,
iconSize,
iconSize
);
} else {
context.drawImage(
img_cross,
(this.buttons[i].getX()+this.buttons[i].getWidth())-iconSize,
(this.buttons[... | img_tick,
| random_line_split |
AchievementsMenu.js | /**
* Menu showing the player's unlocked achievements.
*
* @class AchievementsMenu
* @extends Menu
* @constructor
*/
function AchievementsMenu() | this.buttons.push(mainMenu);
this.buttons.push(level3);
this.buttons.push(level5);
this.buttons.push(level10);
this.buttons.push(earlyDeath);
this.buttons.push(bigEarner);
this.buttons.push(fishKiller);
this.buttons.push(allGrowth);
this.buttons.push(allPoison);
this.buttons.push(allUpgrades);
this... | {
// call the parent constructor
Menu.call(this);
// add custom buttons
var mainMenu = new Button("mainMenu", "Return to menu", (layout.getWidth()/2)-(this.button_width/2), layout.getSystemLevel() + 50, this.button_width, this.button_height);
var level3 = new Button("level3", "Reached Level 3", (layout.ge... | identifier_body |
AchievementsMenu.js | /**
* Menu showing the player's unlocked achievements.
*
* @class AchievementsMenu
* @extends Menu
* @constructor
*/
function | () {
// call the parent constructor
Menu.call(this);
// add custom buttons
var mainMenu = new Button("mainMenu", "Return to menu", (layout.getWidth()/2)-(this.button_width/2), layout.getSystemLevel() + 50, this.button_width, this.button_height);
var level3 = new Button("level3", "Reached Level 3", (layout... | AchievementsMenu | identifier_name |
test_user.py | #import pytest
#import sys
import test.api as api
#import bauble.db as db
from bauble.model.user import User
def xtest_user_json(session):
username = 'test_user_json'
password = username
users = session.query(User).filter_by(username=username)
for user in users:
session.delete(user)
ses... |
def xtest_get_schema():
schema = api.get_resource("/user/schema")
def xtest_resource(session):
"""
Test the server properly /family resources
"""
return
db.set_session_schema(session, session.merge(organization).pg_schema)
families = session.query(Family)
# create a family family
... | session.add(user)
session.commit()
| random_line_split |
test_user.py | #import pytest
#import sys
import test.api as api
#import bauble.db as db
from bauble.model.user import User
def xtest_user_json(session):
username = 'test_user_json'
password = username
users = session.query(User).filter_by(username=username)
for user in users:
|
session.commit()
user = User(username=username, password=password)
session.add(user)
session.commit()
def xtest_get_schema():
schema = api.get_resource("/user/schema")
def xtest_resource(session):
"""
Test the server properly /family resources
"""
return
db.set_session_sc... | session.delete(user) | conditional_block |
test_user.py | #import pytest
#import sys
import test.api as api
#import bauble.db as db
from bauble.model.user import User
def xtest_user_json(session):
username = 'test_user_json'
password = username
users = session.query(User).filter_by(username=username)
for user in users:
session.delete(user)
ses... | (session):
"""
Test the server properly /family resources
"""
return
db.set_session_schema(session, session.merge(organization).pg_schema)
families = session.query(Family)
# create a family family
first_family = api.create_resource('/family', {'family': api.get_random_name()})
# ... | xtest_resource | identifier_name |
test_user.py | #import pytest
#import sys
import test.api as api
#import bauble.db as db
from bauble.model.user import User
def xtest_user_json(session):
username = 'test_user_json'
password = username
users = session.query(User).filter_by(username=username)
for user in users:
session.delete(user)
ses... | api.delete_resource(first_family['ref'])
api.delete_resource(second_family['ref'])
def test_password(session):
username = api.get_random_name()
email = username + '@bauble.io'
password = api.get_random_name()
user = User(email=email, username=username, password=password)
session.add(user... | """
Test the server properly /family resources
"""
return
db.set_session_schema(session, session.merge(organization).pg_schema)
families = session.query(Family)
# create a family family
first_family = api.create_resource('/family', {'family': api.get_random_name()})
# get the family
... | identifier_body |
views.py | from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import UrlShrinked
from .forms import UrlShrinkedForm
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib.sites.shortcuts import get_current_site
from django.http import JsonResponse,HttpR... | (request):
if request.method == "POST":
form=UrlShrinkedForm(request.POST)
if form.is_valid():
url=form.save(commit=False)
url.save()
url.publish()
tmp="/"+url.shrinked_code+"/"
full_url = ''.join(['http://', get_current_site(request).domai... | create_shorturl | identifier_name |
views.py | from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import UrlShrinked
from .forms import UrlShrinkedForm
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib.sites.shortcuts import get_current_site
from django.http import JsonResponse,HttpR... | else:
form=UrlShrinkedForm()
return render(request, 'redirector/create.html',{'form':form})
#View redirect me to the right url
def url_redirection(request, code):
url_retrieved=get_url(code)
if(url_retrieved!=None):
return redirect(url_retrieved.url)
else:
return render(requ... | random_line_split | |
views.py | from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import UrlShrinked
from .forms import UrlShrinkedForm
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib.sites.shortcuts import get_current_site
from django.http import JsonResponse,HttpR... |
object_response={'url':result.url,'shrink':result.shrinked_code}
return HttpResponse(JsonResponse(object_response), content_type="application/json")
#Search url using shrinked code, private function, TO MOVE
def get_url(code):
try:
return UrlShrinked.objects.get(shrinked_code=code)
except UrlS... | url_verification=URLValidator()
post_url=request.POST.get('url');
result=UrlShrinked(url="")
if post_url:
try:
url_verification(post_url)
result.url=post_url
result.save()
result.publish()
except Exception as... | conditional_block |
views.py | from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import UrlShrinked
from .forms import UrlShrinkedForm
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib.sites.shortcuts import get_current_site
from django.http import JsonResponse,HttpR... |
#Get url from shrinked code (Json)
#Csrf is disabled for get post request from external site without cookie or sessions
@csrf_exempt
def api_url_response(request,code):
result=get_url(code)
if(result!= None):
object_response={'url':result.url,'shrink':result.shrinked_code}
response=HttpRespons... | url_retrieved=get_url(code)
if(url_retrieved!=None):
return redirect(url_retrieved.url)
else:
return render(request,'redirector/error.html') | identifier_body |
test_model_versioned_delete.py | # -*- encoding: utf-8 -*-
import pytest
from django.utils import timezone
from base.model_utils import BaseError
from example_base.models import FruitCake
from login.tests.factories import UserFactory
from .factories import FruitCakeFactory
@pytest.mark.django_db
def test_factory():
FruitCakeFactory()
@pytest... |
@pytest.mark.django_db
def test_undelete():
obj = FruitCakeFactory()
user = UserFactory()
FruitCake.objects.set_deleted(obj, user)
assert obj.deleted_version > 0
obj.refresh_from_db()
obj.undelete()
obj.refresh_from_db()
assert obj.deleted is False
assert obj.user_deleted is None
... | """Standard way to delete rows from non-versioned delete models"""
obj = FruitCakeFactory()
with pytest.raises(BaseError) as e:
obj.set_deleted(UserFactory())
assert 'model with deleted version tracking' in str(e.value) | identifier_body |
test_model_versioned_delete.py | # -*- encoding: utf-8 -*-
import pytest
from django.utils import timezone
from base.model_utils import BaseError
from example_base.models import FruitCake
from login.tests.factories import UserFactory
from .factories import FruitCakeFactory
@pytest.mark.django_db
def test_factory():
FruitCakeFactory()
@pytest... | assert 3 == result.count()
assert [
(19, True, 1),
(19, True, 2),
(19, False, 0),
] == [(o.number, o.deleted, o.deleted_version) for o in result]
@pytest.mark.django_db
def test_set_deleted_model():
"""Standard way to delete rows from non-versioned delete models"""
obj = Fr... | FruitCakeFactory(number=19, description='c3')
result = FruitCake.objects.filter(number=19).order_by('description') | random_line_split |
test_model_versioned_delete.py | # -*- encoding: utf-8 -*-
import pytest
from django.utils import timezone
from base.model_utils import BaseError
from example_base.models import FruitCake
from login.tests.factories import UserFactory
from .factories import FruitCakeFactory
@pytest.mark.django_db
def test_factory():
FruitCakeFactory()
@pytest... | ():
"""Standard way to delete rows from non-versioned delete models"""
obj = FruitCakeFactory()
with pytest.raises(BaseError) as e:
obj.set_deleted(UserFactory())
assert 'model with deleted version tracking' in str(e.value)
@pytest.mark.django_db
def test_undelete():
obj = FruitCakeFactory... | test_set_deleted_model | identifier_name |
tag_to_tag.py | import os
import sys
from github import Github
from github.GithubException import GithubException
def tag_to_tag():
SRC_TAG=os.environ.get('SRC_TAG')
ORG_NAME=os.environ.get('ORG_NAME')
REPO_NAME=os.environ.get('REPO_NAME')
USERNAME=os.environ.get('USERNAME')
PASSWORD=os.environ.get('PASSWORD')
... | try:
tag_to_tag()
except:
import traceback
exc_type, exc_value, exc_traceback = sys.exc_info()
print '-'*60
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)
print '-'*60
sys.exit(1) | conditional_block | |
tag_to_tag.py | import os
import sys
from github import Github
from github.GithubException import GithubException
def tag_to_tag():
SRC_TAG=os.environ.get('SRC_TAG')
ORG_NAME=os.environ.get('ORG_NAME')
REPO_NAME=os.environ.get('REPO_NAME')
USERNAME=os.environ.get('USERNAME')
PASSWORD=os.environ.get('PASSWORD')
... | exc_type, exc_value, exc_traceback = sys.exc_info()
print '-'*60
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)
print '-'*60
sys.exit(1) | random_line_split | |
tag_to_tag.py | import os
import sys
from github import Github
from github.GithubException import GithubException
def tag_to_tag():
| break
if not src_tag:
print 'No tag named %s found' % SRC_TAG
exit(1)
tag = repo.create_git_tag(TAG, 'Created from tag %s' % SRC_TAG, src_tag.commit.sha, 'commit')
print 'Tag Created:'
print tag._rawData
# Could not figure out how to look up the existing but dec... | SRC_TAG=os.environ.get('SRC_TAG')
ORG_NAME=os.environ.get('ORG_NAME')
REPO_NAME=os.environ.get('REPO_NAME')
USERNAME=os.environ.get('USERNAME')
PASSWORD=os.environ.get('PASSWORD')
TAG=os.environ.get('TAG')
print 'Attempting to create tag %s from tag %s' % (TAG, SRC_TAG)
g = Github(... | identifier_body |
tag_to_tag.py | import os
import sys
from github import Github
from github.GithubException import GithubException
def | ():
SRC_TAG=os.environ.get('SRC_TAG')
ORG_NAME=os.environ.get('ORG_NAME')
REPO_NAME=os.environ.get('REPO_NAME')
USERNAME=os.environ.get('USERNAME')
PASSWORD=os.environ.get('PASSWORD')
TAG=os.environ.get('TAG')
print 'Attempting to create tag %s from tag %s' % (TAG, SRC_TAG)
g =... | tag_to_tag | identifier_name |
show_rack_rack.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2013 Contributor
#
# 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 t... |
class CommandShowRackRack(BrokerCommand):
required_parameters = ["rack"]
def render(self, session, rack, **arguments):
return Rack.get_unique(session, rack, compel=True) | """Contains the logic for `aq show rack --rack`."""
from aquilon.aqdb.model import Rack
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
| random_line_split |
show_rack_rack.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2013 Contributor
#
# 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 t... | (self, session, rack, **arguments):
return Rack.get_unique(session, rack, compel=True)
| render | identifier_name |
show_rack_rack.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2013 Contributor
#
# 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 t... | required_parameters = ["rack"]
def render(self, session, rack, **arguments):
return Rack.get_unique(session, rack, compel=True) | identifier_body | |
header-components.tsx | import React from 'react';
import { Translate } from 'react-jhipster';
import { NavItem, NavLink, NavbarBrand } from 'reactstrap';
import { NavLink as Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import appConfig from 'app/config/constants';
export const BrandIcon... | </NavbarBrand>
);
export const AboutUs = props => (
<NavItem>
<NavLink tag={Link} to="/about-us" className="d-flex align-items-center">
<FontAwesomeIcon icon="hand-spock" />
<span>
About Us
</span>
</NavLink>
</NavItem>
);
export const Home = props => (
<NavItem>
<NavLink ... | </span>
<span className="navbar-version">{appConfig.VERSION}</span> | random_line_split |
angular-sortable.js | /*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('ui.sortable', [])
.value('uiSortableConfig',{})
.directive('uiSortable', [ 'uiSortableConfig',
function(uiSortableConfig) {
return {
... |
}
element.sortable('option', key, value);
});
}, true);
angular.forEach(callbacks, function(value, key ){
opts[key] = combineCallbacks(value, opts[key]);
});
// call a... | {
// call apply after stop
value = combineCallbacks( value, apply );
} | conditional_block |
angular-sortable.js | /*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('ui.sortable', [])
.value('uiSortableConfig',{})
.directive('uiSortable', [ 'uiSortableConfig',
function(uiSortableConfig) {
return {
... |
var opts = {};
var callbacks = {
receive: null,
remove:null,
start:null,
stop:null,
update:null
};
var apply = function(e, ui) {
if (u... | {
if( second && (typeof second === "function") ){
return function(e,ui){
first(e,ui);
second(e,ui);
};
}
return first;
} | identifier_body |
angular-sortable.js | /*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('ui.sortable', [])
.value('uiSortableConfig',{})
.directive('uiSortable', [ 'uiSortableConfig',
function(uiSortableConfig) {
return {
... | (first,second){
if( second && (typeof second === "function") ){
return function(e,ui){
first(e,ui);
second(e,ui);
};
}
return first;
}
var o... | combineCallbacks | identifier_name |
angular-sortable.js | /*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('ui.sortable', [])
.value('uiSortableConfig',{})
.directive('uiSortable', [ 'uiSortableConfig',
function(uiSortableConfig) {
return {
... | angular.forEach(callbacks, function(value, key ){
opts[key] = combineCallbacks(value, opts[key]);
});
// call apply after stop
opts.stop = combineCallbacks( opts.stop, apply );
// Create sortable
... | random_line_split | |
rtconfig.py | import os
# toolchains options
ARCH='arm'
CPU='cortex-m0'
CROSS_TOOL='keil'
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR
if CROSS_TOOL == 'gcc':
print '================ERROR==... |
elif CROSS_TOOL == 'iar':
PLATFORM = 'iar'
IAR_PATH = r'C:/Program Files (x86)/IAR Systems/Embedded Workbench 8.0'
if os.getenv('RTT_EXEC_PATH'):
EXEC_PATH = os.getenv('RTT_EXEC_PATH')
#BUILD = 'debug'
BUILD = 'release'
if PLATFORM == 'gcc':
# toolchains
PREFIX = 'arm-none-eabi-'
CC = PREFI... | PLATFORM = 'armcc'
EXEC_PATH = 'C:/keil_v5' | conditional_block |
rtconfig.py | import os
# toolchains options
ARCH='arm'
CPU='cortex-m0'
CROSS_TOOL='keil'
if os.getenv('RTT_CC'): | if CROSS_TOOL == 'gcc':
print '================ERROR============================'
print 'Not support gcc yet!'
print '================================================='
elif CROSS_TOOL == 'keil':
PLATFORM = 'armcc'
EXEC_PATH = 'C:/keil_v5'
elif CROSS_TOOL == 'iar':
PLATFORM = 'iar'
IAR_P... | CROSS_TOOL = os.getenv('RTT_CC')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR | random_line_split |
functions_8h.js | fe5801ad4bc179be28ad7a41", null ],
[ "bloch2rho", "functions_8h.html#a7e5c413d74d838e78264444307e81576", null ],
[ "comm", "functions_8h.html#aa4c1b998a518e655645a0285f90550e3", null ],
[ "complement", "functions_8h.html#a87ad5b3e58dedde05467ac1961e44892", null ],
[ "conjugate", "functions_8h.html#ad430... | [ "grams", "functions_8h.html#aa37bbf414317d23b7fa7287f8100f96c", null ],
[ "grams", "functions_8h.html#aa4917f28299b0430203972045b8cf377", null ],
[ "heig", "functions_8h.html#acbb48ecd842d8f6a3938e3e5b9a36506", null ],
[ "hevals", "functions_8h.html#a322665174fcacffbdf82dd04139d667e", null ],
[ "h... | [ "evects", "functions_8h.html#acc9597bacc39c501eb8e2e5e8530fcd8", null ],
[ "expm", "functions_8h.html#a6855dd77c49ae0b96baf10c12b4bc722", null ],
[ "funm", "functions_8h.html#a659b50e01fa0b26089d3944c2c56601a", null ],
[ "grams", "functions_8h.html#ac38ccf0665bd72f6d350c13c6d926b15", null ], | random_line_split |
test_blacklist_model.py | """
Module for testing the Blacklist model
"""
import unittest
from app.models.shopping import BlacklistToken, ShoppingList
try:
from .common_functions import BaseModelTestClass
except (ImportError, SystemError):
from common_functions import BaseModelTestClass
class BlacklistModelTest(BaseModelTestClass):
... |
# blacklist token
try:
blacklisted_token = BlacklistToken(token=token)
# putting save() commits to session and closes the session
return blacklisted_token
except Exception as e:
raise e
def test_... | token = self.user.generate_token(self.user.id) | conditional_block |
test_blacklist_model.py | """
Module for testing the Blacklist model
"""
import unittest
from app.models.shopping import BlacklistToken, ShoppingList
try:
from .common_functions import BaseModelTestClass
except (ImportError, SystemError):
from common_functions import BaseModelTestClass
class | (BaseModelTestClass):
"""
Handles the testing for the Blacklist model class
"""
def blacklist_token(self, token=None):
"""
Helper method to blacklist a token
"""
with self.app.app_context():
if not token:
# create token from default user
... | BlacklistModelTest | identifier_name |
test_blacklist_model.py | """
Module for testing the Blacklist model
"""
import unittest
from app.models.shopping import BlacklistToken, ShoppingList
try:
from .common_functions import BaseModelTestClass
except (ImportError, SystemError):
from common_functions import BaseModelTestClass
class BlacklistModelTest(BaseModelTestClass):
... | def test_token_can_be_blacklisted(self):
"""
A token can be blacklisted
"""
with self.app.app_context():
blacklisted_token = self.blacklist_token()
blacklisted_token.save() # save in the same session
from_database = BlacklistToken.query.get(blackli... | """
Handles the testing for the Blacklist model class
"""
def blacklist_token(self, token=None):
"""
Helper method to blacklist a token
"""
with self.app.app_context():
if not token:
# create token from default user
token = sel... | identifier_body |
test_blacklist_model.py | """
Module for testing the Blacklist model
"""
import unittest
from app.models.shopping import BlacklistToken, ShoppingList
try:
from .common_functions import BaseModelTestClass
except (ImportError, SystemError):
from common_functions import BaseModelTestClass
class BlacklistModelTest(BaseModelTestClass):
... | def test_token_can_be_blacklisted(self):
"""
A token can be blacklisted
"""
with self.app.app_context():
blacklisted_token = self.blacklist_token()
blacklisted_token.save() # save in the same session
from_database = BlacklistToken.query.get(blackli... | random_line_split | |
engine.py | # -*- coding: utf-8 -*-
# This file is part of the Horus Project
__author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>'
__copyright__ = 'Copyright (C) 2014-2016 Mundo Reader S.L.'
__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
from horus.engine.driver.driver import Driver
from ... | image_capture = ImageCapture()
image_detection = ImageDetection()
laser_segmentation = LaserSegmentation()
point_cloud_generation = PointCloudGeneration()
point_cloud_roi = PointCloudROI() | scanner_autocheck = Autocheck()
laser_triangulation = LaserTriangulation()
platform_extrinsics = PlatformExtrinsics()
combo_calibration = ComboCalibration() | random_line_split |
pairs.rs | pub(crate) fn infix(infix: &'a str) -> PairParts<'a> {
PairParts {
prefix: "",
infix,
suffix: "",
}
}
}
// Flattens a tree of pairs into a list and tries to rewrite them all at once.
// FIXME would be nice to reuse the lists API for this, but because each separa... | (
expr: &ast::Expr,
shape: Shape,
context: &RewriteContext<'_>,
) -> Option<String> {
expr.flatten(context, shape).and_then(|list| {
// First we try formatting on one line.
rewrite_pairs_one_line(&list, shape, context)
.or_else(|| rewrite_pairs_multiline(&list, shape, context... | rewrite_all_pairs | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.