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 |
|---|---|---|---|---|
speed.py | # -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... | return {}
def load_settings(self, settings):
self.speedSlider.setValue(settings.get('speed', 1) * 100)
def speedChanged(self, value):
self.speedLabel.setText(str(value / 100.0)) | def get_settings(self):
if not (self.groupBox.isCheckable() and not self.groupBox.isChecked()):
return {'speed': self.speedSlider.value() / 100}
| random_line_split |
speed.py | # -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... | self.speedLabel.setText(str(value / 100.0)) | identifier_body | |
server.rs | //! A low-level interface to send and receive server-client protocol messages
use std;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, TryRecvError};
use std::sync::atomic::{Ordering, AtomicUsize};
use bincode;
use common::protocol;
use common::socket::{SendSocket, ReceiveSocket};
#[allow(miss... |
impl SSender {
#[allow(missing_docs)]
pub fn new(sender: Sender<Box<[u8]>>) -> SSender {
SSender {
sender: sender,
bytes_sent: Arc::new(AtomicUsize::new(0)),
}
}
#[allow(missing_docs)]
pub fn tell(&self, msg: &protocol::ClientToServer) {
let msg = bincode::serialize(msg, bincode::Inf... | // A boxed slice is used to reduce the sent size
pub sender: Sender<Box<[u8]>>,
// Please replace with AtomicU64 when it becomes stable
pub bytes_sent: Arc<AtomicUsize>,
} | random_line_split |
server.rs | //! A low-level interface to send and receive server-client protocol messages
use std;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, TryRecvError};
use std::sync::atomic::{Ordering, AtomicUsize};
use bincode;
use common::protocol;
use common::socket::{SendSocket, ReceiveSocket};
#[allow(miss... | {
pub talk : SSender,
pub listen : SReceiver,
}
#[allow(missing_docs)]
pub fn new(
server_url: &str,
listen_url: &str,
) -> T {
let (send_send, send_recv) = std::sync::mpsc::channel();
let (recv_send, recv_recv) = std::sync::mpsc::channel();
let _recv_thread ={
let listen_url = listen_url.to_owne... | T | identifier_name |
server.rs | //! A low-level interface to send and receive server-client protocol messages
use std;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, TryRecvError};
use std::sync::atomic::{Ordering, AtomicUsize};
use bincode;
use common::protocol;
use common::socket::{SendSocket, ReceiveSocket};
#[allow(miss... |
#[allow(missing_docs)]
pub fn wait(&self) -> protocol::ServerToClient {
let msg = self.0.lock().unwrap().recv().unwrap();
bincode::deserialize(msg.as_ref()).unwrap()
}
}
#[allow(missing_docs)]
#[derive(Clone)]
pub struct T {
pub talk : SSender,
pub listen : SReceiver,
}
#[allow(missing_docs)]
pu... | {
match self.0.lock().unwrap().try_recv() {
Ok(msg) => Some(bincode::deserialize(&Vec::from(msg)).unwrap()),
Err(TryRecvError::Empty) => None,
e => {
e.unwrap();
unreachable!();
},
}
} | identifier_body |
ObjectExpression.js | var _ = require('lodash');
var valueFactory = require('../factory/value.js');
var Base = require('./Base');
/**
* Object expression token (e.g. `{ a: "foo"}`)
* @class
* @param {Object} node AST ObjectExpression token
*/
var ObjectExpression = module.exports = Base.extend({
constructor: function (node) {
th... |
return valueFactory.wrap(node.value);
},
/**
* Replace node with new value
* @param {String} value
* @return {Object} New value object
*/
value: function (value) {
var val = valueFactory.create(value);
// As we don't keep reference to the parent, just update properties so the object s... | {
node = {
type: 'Property',
key: { type: 'Identifier', name: name },
value: { type: 'ObjectExpression', properties: [] },
kind: 'init',
TEMP: true
};
Object.defineProperty(node.value, 'TEMP', {
get: function () {
return true;
},
... | conditional_block |
ObjectExpression.js | var _ = require('lodash');
var valueFactory = require('../factory/value.js');
var Base = require('./Base');
/**
* Object expression token (e.g. `{ a: "foo"}`)
* @class
* @param {Object} node AST ObjectExpression token
*/
var ObjectExpression = module.exports = Base.extend({
constructor: function (node) {
th... | return valueFactory.wrap(this.node);
}
}); | _.extend(this.node, val);
| random_line_split |
SiteColumnAnswerComponent.ts | import PropTypes from "prop-types"
import React from "react"
const R = React.createElement
import EntityDisplayComponent from "../EntityDisplayComponent"
export interface SiteColumnAnswerComponentProps {
value?: any
onValueChange: any
siteType: string
}
// Displays a site answer in a cell. No direct code enter... | extends React.Component<SiteColumnAnswerComponentProps> {
static contextTypes = {
selectEntity: PropTypes.func,
getEntityById: PropTypes.func.isRequired,
getEntityByCode: PropTypes.func.isRequired,
renderEntityListItemView: PropTypes.func.isRequired,
T: PropTypes.func.isRequired // Localizer to u... | SiteColumnAnswerComponent | identifier_name |
SiteColumnAnswerComponent.ts | import PropTypes from "prop-types"
import React from "react"
const R = React.createElement
import EntityDisplayComponent from "../EntityDisplayComponent"
export interface SiteColumnAnswerComponentProps {
value?: any
onValueChange: any
siteType: string
}
// Displays a site answer in a cell. No direct code enter... |
}
| {
if (this.props.value?.code) {
return R(
"div",
null,
R(
"button",
{ className: "btn btn-link btn-sm float-end", onClick: this.handleClearClick },
R("span", { className: "fas fa-times" })
),
R(EntityDisplayComponent, {
entityTyp... | identifier_body |
SiteColumnAnswerComponent.ts | import PropTypes from "prop-types"
import React from "react"
const R = React.createElement
import EntityDisplayComponent from "../EntityDisplayComponent"
export interface SiteColumnAnswerComponentProps {
value?: any
onValueChange: any
siteType: string
}
// Displays a site answer in a cell. No direct code enter... | "button",
{ className: "btn btn-link btn-sm float-end", onClick: this.handleClearClick },
R("span", { className: "fas fa-times" })
),
R(EntityDisplayComponent, {
entityType: this.props.siteType,
entityCode: this.props.value?.code,
getEntityByC... | random_line_split | |
SiteColumnAnswerComponent.ts | import PropTypes from "prop-types"
import React from "react"
const R = React.createElement
import EntityDisplayComponent from "../EntityDisplayComponent"
export interface SiteColumnAnswerComponentProps {
value?: any
onValueChange: any
siteType: string
}
// Displays a site answer in a cell. No direct code enter... |
}
}
| {
return R("button", { className: "btn btn-link", onClick: this.handleSelectClick }, this.context.T("Select..."))
} | conditional_block |
pelican_import.py | #!/usr/bin/env python
import argparse
import os
import subprocess
import sys
import time
from codecs import open
from pelican.utils import slugify
def wp2fields(xml):
"""Opens a wordpress XML file, and yield pelican fields"""
try:
from BeautifulSoup import BeautifulStoneSoup
except ImportError:... | """Opens a Dotclear export file, and yield pelican fields"""
try:
from BeautifulSoup import BeautifulStoneSoup
except ImportError:
error = ('Missing dependency '
'"BeautifulSoup" required to import Dotclear files.')
sys.exit(error)
in_cat = False
in_post = ... |
yield (title, content, filename, date, author, categories, tags, "html")
def dc2fields(file): | random_line_split |
pelican_import.py | #!/usr/bin/env python
import argparse
import os
import subprocess
import sys
import time
from codecs import open
from pelican.utils import slugify
def wp2fields(xml):
"""Opens a wordpress XML file, and yield pelican fields"""
try:
from BeautifulSoup import BeautifulStoneSoup
except ImportError:... |
else:
error = "You must provide either --wpfile, --dotclear or --feed options"
exit(error)
if not os.path.exists(args.output):
try:
os.mkdir(args.output)
except OSError:
error = "Unable to create the output folder: " + args.output
exit(error)... | input_type = 'feed' | conditional_block |
pelican_import.py | #!/usr/bin/env python
import argparse
import os
import subprocess
import sys
import time
from codecs import open
from pelican.utils import slugify
def wp2fields(xml):
"""Opens a wordpress XML file, and yield pelican fields"""
try:
from BeautifulSoup import BeautifulStoneSoup
except ImportError:... |
def build_markdown_header(title, date, author, categories, tags):
"""Build a header from a list of fields"""
header = 'Title: %s\n' % title
if date:
header += 'Date: %s\n' % date
if categories:
header += 'Category: %s\n' % ', '.join(categories)
if tags:
header += 'Tags: %s\... | """Build a header from a list of fields"""
header = '%s\n%s\n' % (title, '#' * len(title))
if date:
header += ':date: %s\n' % date
if categories:
header += ':category: %s\n' % ', '.join(categories)
if tags:
header += ':tags: %s\n' % ', '.join(tags)
header += '\n'
return h... | identifier_body |
pelican_import.py | #!/usr/bin/env python
import argparse
import os
import subprocess
import sys
import time
from codecs import open
from pelican.utils import slugify
def | (xml):
"""Opens a wordpress XML file, and yield pelican fields"""
try:
from BeautifulSoup import BeautifulStoneSoup
except ImportError:
error = ('Missing dependency '
'"BeautifulSoup" required to import Wordpress XML files.')
sys.exit(error)
xmlfile = open(xml, ... | wp2fields | identifier_name |
utils.js | /* Python new-style string formatting.
* > "Hello, {0}.".format('Mike');
* Hello, Mike.
* > "How is the weather in {citi}?".format({city: 'Mountain View'}) | var str = this;
// Support either an object, or a series.
return str.replace(/\{[\w\d\._-]+\}/g, function(part) {
// Strip off {}.
part = part.slice(1, -1);
var index = parseInt(part, 10);
if (isNaN(index)) {
return dottedGet(obj, part);
} else {
return args[index];
}
});
};
... | * How is the weather in Mountain View?
*/
String.prototype.format = function(obj) {
var args = arguments; | random_line_split |
utils.js | /* Python new-style string formatting.
* > "Hello, {0}.".format('Mike');
* Hello, Mike.
* > "How is the weather in {citi}?".format({city: 'Mountain View'})
* How is the weather in Mountain View?
*/
String.prototype.format = function(obj) {
var args = arguments;
var str = this;
// Support either an object, or... |
});
};
dottedGet = function(obj, selector) {
selector = selector.split('.');
while (selector.length) {
obj = obj[selector.splice(0, 1)[0]];
}
return obj;
};
| {
return args[index];
} | conditional_block |
script.js | $(document).ready(function() {
/**
* We are loading the stored guideline.json file, which
* is a list of test names.
*/
$.getJSON('data/guideline.json', function(guideline) {
$('body').append('<div id="enable-accessibility"><a href="#">Turn on accessibility tests</a></div>');
$('#enable-accessibility a')... |
}
});
});
});
});
| {
$(':submit').removeClass('disabled')
.removeAttr('disabled');
} | conditional_block |
script.js | $(document).ready(function() {
/**
* We are loading the stored guideline.json file, which
* is a list of test names.
*/
$.getJSON('data/guideline.json', function(guideline) {
$('body').append('<div id="enable-accessibility"><a href="#">Turn on accessibility tests</a></div>');
$('#enable-accessibility a')... | });
$('#edit').keyup(function() {
var $text = $('<div>' + $(this).val() + '</div>');
$text.quail({ guideline : guideline,
jsonPath : '../../src/resources',
reset : true,
testFailed : function(event) {
if(event.severity == 'severe') {
$(':submit').addClas... | }
}); | random_line_split |
resolve.js | 'use strict';
var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];
var _getIterator = require('babel-runtime/core-js/get-iterator')['default'];
var fs = require('fs'),
path = require('path'),
resolve = require('resolve');
var CASE_INSENSITIVE = fs.existsSync(path.join(__dirname, '... |
function opts(basedir, settings) {
// pulls all items from 'import/resolve'
return _Object$assign({}, settings['import/resolve'], { basedir: basedir });
}
/**
* wrapper around resolve
* @param {string} p - module path
* @param {object} context - ESLint context
* @return {string} - the full module filesyste... | {
if (CASE_INSENSITIVE) {
return fileExistsWithCaseSync(filepath);
} else {
return fs.existsSync(filepath);
}
} | identifier_body |
resolve.js | 'use strict';
var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];
var _getIterator = require('babel-runtime/core-js/get-iterator')['default'];
var fs = require('fs'),
path = require('path'),
resolve = require('resolve');
var CASE_INSENSITIVE = fs.existsSync(path.join(__dirname, '... | (_x) {
var _again = true;
_function: while (_again) {
var filepath = _x;
dir = filenames = undefined;
_again = false;
// shortcut exit
if (!fs.existsSync(filepath)) return false;
var dir = path.dirname(filepath);
if (dir === '/' || dir === '.' || /^[A-Z]:\\$/.test(dir)) return true;
... | fileExistsWithCaseSync | identifier_name |
resolve.js | 'use strict';
var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];
var _getIterator = require('babel-runtime/core-js/get-iterator')['default'];
var fs = require('fs'),
path = require('path'),
resolve = require('resolve');
var CASE_INSENSITIVE = fs.existsSync(path.join(__dirname, '... | throw err; // else
}
}; | return file;
} catch (err) {
if (err.message.indexOf('Cannot find module') === 0) return null;
| random_line_split |
term_pygame.py | import os
import pygame
import sys
import threading, time
from pygame.locals import *
import logging
log = logging.getLogger('pytality.term.pygame')
log.debug("pygame version: %r", pygame.version.ver)
"""
A mapping of special keycodes into representative strings.
Based off the keymap in WConio, but with 'alt... |
#----------------------------------------------------------------------------
#Actual functions
def flip():
#keep the event queue happy
for event in pygame.event.get([
#this should be all the event types we aren't blocking
#and aren't about keyboard input
QUIT,
ACTIVEEVENT,
... | global replaced_character
if not replaced_character:
return
x, y, fg, bg, ch = replaced_character
blit_at(x, y, fg, bg, ch)
pygame.display.flip()
replaced_character = None | identifier_body |
term_pygame.py | import os
import pygame
import sys
import threading, time
from pygame.locals import *
import logging
log = logging.getLogger('pytality.term.pygame')
log.debug("pygame version: %r", pygame.version.ver)
"""
A mapping of special keycodes into representative strings.
Based off the keymap in WConio, but with 'alt... | x += 1
w += 1
y += 1
source.dirty = False
return
def get_at(x, y):
if x < 0 or x >= max_x or y < 0 or y >= max_y:
raise ValueError("get_at: Invalid coordinate (%r, %r)" % (x,y))
global cell_data
return cell_data[y][x]
def prepare_raw_getkey():
"""
... | #remember the info for the cache
local_cell_data[y][x] = new_data
| random_line_split |
term_pygame.py | import os
import pygame
import sys
import threading, time
from pygame.locals import *
import logging
log = logging.getLogger('pytality.term.pygame')
log.debug("pygame version: %r", pygame.version.ver)
"""
A mapping of special keycodes into representative strings.
Based off the keymap in WConio, but with 'alt... | (fg, bg, ch):
bg_sprite = sprites['bg']
fg_sprite = sprites[fg]
index = ord(ch)
#coordinates on the bg sprite map
bg_x = bg * W
#coordinates on the fg sprite map
fg_x = (index % 16) * W
fg_y = int(index / 16) * H
cell_sprite = pygame.Surface((W, H))
#voodoo: this helps a littl... | cache_sprite | identifier_name |
term_pygame.py | import os
import pygame
import sys
import threading, time
from pygame.locals import *
import logging
log = logging.getLogger('pytality.term.pygame')
log.debug("pygame version: %r", pygame.version.ver)
"""
A mapping of special keycodes into representative strings.
Based off the keymap in WConio, but with 'alt... |
else:
restore_character()
def replace_character():
global replaced_character
if not cursor_type:
return
fg, bg, ch = get_at(cursor_x, cursor_y)
replaced_character = (cursor_x, cursor_y, fg, bg, ch)
new_fg = 15
if bg == 15:
new_fg = 7
blit_at(cursor_x, cursor_y,... | replace_character() | conditional_block |
catalog_page.js | var win = Titanium.UI.currentWindow;
win.showNavBar();
var data = [
{title:'HI-FI Sound Systems', hasChild:true, header:'Audio'}, | {title:'Digital Radio', hasChild:true },
{title:'Docking Stations', hasChild:true },
{title:'Home Theatre', hasChild:true },
{title:'MP3 Players', hasChild:true },
{title:'Camcorders', hasChild:true, header:'Cameras & Camcorders'},
{title:'Camera Accessories', hasChild:true },
{title:'Computer Acce... | {title:'Audio Accessories', hasChild:true },
{title:'CD/Radio/Cassette', hasChild:true }, | random_line_split |
catalog_page.js | var win = Titanium.UI.currentWindow;
win.showNavBar();
var data = [
{title:'HI-FI Sound Systems', hasChild:true, header:'Audio'},
{title:'Audio Accessories', hasChild:true },
{title:'CD/Radio/Cassette', hasChild:true },
{title:'Digital Radio', hasChild:true },
{title:'Docking Stations', hasChild:true },
{... |
});
// add table view to the window
win.add(tableview); | {
win = Titanium.UI.createWindow({
url: 'display_catalog.js'
});
win.selectedCatalog = rowdata.title;
Titanium.UI.currentTab.open(win,{animated:true});
} | conditional_block |
frequencyAnalysis.py | """ You've recently read "The Gold-Bug" by Edgar Allan Poe, and was so impressed by the cryptogram in it that
decided to try and decipher an encrypted text yourself. You asked your friend to encode a piece of text using
a substitution cipher, and now have an encryptedText that you'd like to decipher.
The encryption ... |
def frequencyAnalysis(encryptedText):
return max(Counter(encryptedText), key=Counter(encryptedText).get) # CodeFights asks to change this line only | from collections import Counter # "Counter" is what CodeFights asks for | random_line_split |
ArrayUtil.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program 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 later version.
*
* This progr... | <T>(array: T[] | Float32Array, size: number) {
const chunks = [];
for (let index = 0, length = array.length; index < length; index += size) {
chunks.push(array.slice(index, index + size));
}
return chunks;
}
/**
* Gets all the values that are in array2 which are not in array1.
*
* @param array1 the base... | chunk | identifier_name |
ArrayUtil.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program 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 later version.
*
* This progr... |
/**
* Gets all the values that are in array2 which are not in array1.
*
* @param array1 the base array
* @param array2 the array to compare with
* @param matcher a custom matching function in case referencial equality is not enough
* @returns the array containing values in array2 that are not in array1
*/
expo... | {
const chunks = [];
for (let index = 0, length = array.length; index < length; index += size) {
chunks.push(array.slice(index, index + size));
}
return chunks;
} | identifier_body |
ArrayUtil.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program 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 later version.
*
* This progr... |
return (currentIndex + 1) % array.length;
}
return undefined;
};
export const iterateItem = <T>(array: T[], currentItem: T, reverse = false): T | undefined => {
if (Array.isArray(array) && array.length) {
const currentIndex = array.indexOf(currentItem);
// If item could not be found
const isNe... | {
const isZeroIndex = currentIndex === 0;
return isZeroIndex ? array.length - 1 : (currentIndex - 1) % array.length;
} | conditional_block |
ArrayUtil.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program 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 later version.
*
* This progr... | if (Array.isArray(array) && array.length && Number.isFinite(currentIndex)) {
if (reverse) {
const isZeroIndex = currentIndex === 0;
return isZeroIndex ? array.length - 1 : (currentIndex - 1) % array.length;
}
return (currentIndex + 1) % array.length;
}
return undefined;
};
export const i... | export const isLastItem = <T>(array: T[], item: T) => array.indexOf(item) === array.length - 1;
export const iterateIndex = <T>(array: T, currentIndex: number, reverse = false): number | undefined => { | random_line_split |
index.js | var readFile = require('graceful-fs').readFile
var resolve = require('path').resolve
var spawn = require('win-spawn')
module.exports = function () {
return {
getStatement: function getStatement (callback) {
readFile(
resolve(__dirname, './problem.txt'),
{encoding: 'utf-8'},
callback... |
})
server.stderr.on('data', function (data) {
console.log(data.toString('utf8').trim())
err += data.toString('utf8')
})
server.on('close', function () {
t.notOk(
out.match(/parse error/) || err.match(/parse error/) || err.match(/EADDRINUSE/),
'reque... | {
var client = spawn('node', [resolve(process.cwd(), filename)])
var cout = ''
var cerr = ''
client.stdout.on('data', function (data) { cout += data.toString('utf8') })
client.stderr.on('data', function (data) { cerr += data.toString('utf8') })
client.on('cl... | conditional_block |
index.js | var readFile = require('graceful-fs').readFile
var resolve = require('path').resolve
var spawn = require('win-spawn')
module.exports = function () {
return {
getStatement: function getStatement (callback) {
readFile(
resolve(__dirname, './problem.txt'),
{encoding: 'utf-8'},
callback... | } | })
}
} | random_line_split |
Command.py | from pygame import K_UP, K_DOWN, K_LEFT, K_RIGHT
from Caracter import Caracter
class CommandHandler(object):
#0 1 2 3 4 5 6 7 8 9 10 11 12 13
_automata_transitions= [[11,11,0, 4, 0, 0, 11,11,0, 11,0, 11,13,0],#up
[9, 2, 0, 0, 0, 0, 9, 9, 0, 0, 0, 1... | self.final_state = 0
input_code = -1
if in_key == K_UP: input_code = 0
elif in_key == K_DOWN: input_code = 1
elif in_key == K_LEFT: input_code = 2
elif in_key == K_RIGHT: input_code = 3
self.actual_state = self._automata_transitions[input_code][self.actual_state]
... | identifier_body | |
Command.py | from pygame import K_UP, K_DOWN, K_LEFT, K_RIGHT
from Caracter import Caracter
class CommandHandler(object): | _automata_transitions= [[11,11,0, 4, 0, 0, 11,11,0, 11,0, 11,13,0],#up
[9, 2, 0, 0, 0, 0, 9, 9, 0, 0, 0, 12,0, 0],#down
[0, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],#left
[1, 0, 0, 0, 5, 0, 7, 0, 0, 0, 0, 1, 0, 0]]#right
# The fin... |
#0 1 2 3 4 5 6 7 8 9 10 11 12 13 | random_line_split |
Command.py | from pygame import K_UP, K_DOWN, K_LEFT, K_RIGHT
from Caracter import Caracter
class CommandHandler(object):
#0 1 2 3 4 5 6 7 8 9 10 11 12 13
_automata_transitions= [[11,11,0, 4, 0, 0, 11,11,0, 11,0, 11,13,0],#up
[9, 2, 0, 0, 0, 0, 9, 9, 0, 0, 0, 1... |
elif self.actual_state == 7: self.caracter.doSprint()
elif self.actual_state == 9:
if self.caracter.onGround == False:
self.caracter.pendingGetDown = True
else:
self.caracter.doGetDown()
elif self.actual_state == 11: self.caracter... | self.caracter.pendingRoll = True | conditional_block |
Command.py | from pygame import K_UP, K_DOWN, K_LEFT, K_RIGHT
from Caracter import Caracter
class CommandHandler(object):
#0 1 2 3 4 5 6 7 8 9 10 11 12 13
_automata_transitions= [[11,11,0, 4, 0, 0, 11,11,0, 11,0, 11,13,0],#up
[9, 2, 0, 0, 0, 0, 9, 9, 0, 0, 0, 1... | (self, caracter):
self.caracter = caracter
self.actual_state = 0
def refresh_state(self, in_key):
self.final_state = 0
input_code = -1
if in_key == K_UP: input_code = 0
elif in_key == K_DOWN: input_code = 1
elif in_key == K_LEFT: input_code = 2
elif i... | __init__ | identifier_name |
user.service.ts | import {Injectable} from "@angular/core";
import {Http, Headers, Response} from "@angular/http";
import {User} from "./user";
import {Config} from "../config";
import {Observable} from "rxjs/Rx";
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
@Injectable()
export class UserService {
constructor(priva... | })
.catch(this.handleErrors);
}
resetPassword(email) {
let headers = new Headers();
headers.append("Content-Type", "application/json");
return this._http.post(
Config.apiUrl + "Users/resetpassword",
JSON.stringify({
Email: email
}),
{ headers: headers }
)
... | { headers: headers }
)
.map(response => response.json())
.do(data => {
Config.token = data.Result.access_token; | random_line_split |
user.service.ts | import {Injectable} from "@angular/core";
import {Http, Headers, Response} from "@angular/http";
import {User} from "./user";
import {Config} from "../config";
import {Observable} from "rxjs/Rx";
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
@Injectable()
export class UserService {
constructor(priva... |
handleErrors(error: Response) {
console.log(JSON.stringify(error.json()));
return Observable.throw(error);
}
}
| {
let headers = new Headers();
headers.append("Content-Type", "application/json");
return this._http.post(
Config.apiUrl + "Users/resetpassword",
JSON.stringify({
Email: email
}),
{ headers: headers }
)
.catch(this.handleErrors);
} | identifier_body |
user.service.ts | import {Injectable} from "@angular/core";
import {Http, Headers, Response} from "@angular/http";
import {User} from "./user";
import {Config} from "../config";
import {Observable} from "rxjs/Rx";
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
@Injectable()
export class UserService {
| (private _http: Http) {}
register(user: User) {
let headers = new Headers();
headers.append("Content-Type", "application/json");
return this._http.post(
Config.apiUrl + "Users",
JSON.stringify({
Username: user.email,
Email: user.email,
Password: user.password
})... | constructor | identifier_name |
error_handler_spec.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 {ERROR_DEBUG_CONTEXT, ERROR_LOGGER, ERROR_TYPE, wrappedError} from '@angular/core/src/util/errors';
import {... | (error: any) {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
errorHandler.handleError(error);
return logger.res.map(line => line.join('#')).join('\n');
}
describe('ErrorHandler', () => {
it('should output exception', () => {
c... | errorToString | identifier_name |
error_handler_spec.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 {ERROR_DEBUG_CONTEXT, ERROR_LOGGER, ERROR_TYPE, wrappedError} from '@angular/core/src/util/errors';
import {... | source: 'context!',
toString() {
return 'Context';
}
} as any;
const original = debugError(cause, context);
const e = errorToString(wrappedError('message', original));
expect(e).toEqual(`ERROR#Error: message caused by: Error in context! caused by: message!
ORIGI... | random_line_split | |
error_handler_spec.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 {ERROR_DEBUG_CONTEXT, ERROR_LOGGER, ERROR_TYPE, wrappedError} from '@angular/core/src/util/errors';
import {... | {
const error = wrappedError(`Error in ${context.source}`, originalError);
(error as any)[ERROR_DEBUG_CONTEXT] = context;
(error as any)[ERROR_TYPE] = debugError;
return error;
} | identifier_body | |
amp-form.js | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
/**
* Returns form data as an object.
* @return {!Object}
* @private
*/
getFormAsObject_() {
const data = {};
const inputs = this.form_.elements;
const submittableTagsRegex = /^(?:input|select|textarea)$/i;
const unsubmittableTypesRegex = /^(?:button|image|file|reset)$/i;
const che... | {
if (this.state_ == FormState_.SUBMITTING) {
e.stopImmediatePropagation();
return;
}
// Validity checking should always occur, novalidate only circumvent
// reporting and blocking submission on non-valid forms.
const isValid = checkUserValidityOnSubmission(this.form_);
if (this.sho... | identifier_body |
amp-form.js | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
return UserValidityState.NONE;
}
/**
* Updates class names on the element to reflect the active invalid types on it.
*
* TODO(#5005): Maybe propagate the invalid type classes to parents of the input as well.
*
* @param {!Element} element
*/
function updateInvalidTypesClasses(element) {
if (!element.validi... | {
return UserValidityState.USER_INVALID;
} | conditional_block |
amp-form.js | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | return this.templates_.findAndRenderTemplate(container, data)
.then(rendered => {
rendered.id = messageId;
rendered.setAttribute('i-amp-rendered', '');
container.appendChild(rendered);
});
}
}
/**
* @private
*/
cleanupRenderedTemplate_() {
... | container.setAttribute('role', 'alert');
container.setAttribute('aria-labeledby', messageId);
container.setAttribute('aria-live', 'assertive'); | random_line_split |
amp-form.js | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | (win) {
return getService(win, 'amp-form', () => {
if (isExperimentOn(win, TAG)) {
installStyles(win.document, CSS, () => {
installSubmissionHandlers(win);
});
}
return {};
});
}
installAmpForm(AMP.win);
| installAmpForm | identifier_name |
test_avhrr_l0_hrpt.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2021 Satpy developers
#
# This file is part of satpy.
#
# satpy 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 Licens... | (TestHRPTWithFile):
"""Test case for reading hrpt data."""
def test_reading(self):
"""Test that data is read."""
fh = HRPTFile(self.filename, {}, {})
assert fh._data is not None
class TestHRPTGetUncalibratedData(TestHRPTWithFile):
"""Test case for reading uncalibrated hrpt data.""... | TestHRPTReading | identifier_name |
test_avhrr_l0_hrpt.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2021 Satpy developers
#
# This file is part of satpy.
#
# satpy 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 Licens... |
class TestHRPTGetCalibratedBT(TestHRPTWithPatchedCalibratorAndFile):
"""Test case for reading calibrated brightness temperature from hrpt data."""
def _get_channel_4_bt(self):
"""Get the channel 4 bt."""
dataset_id = make_dataid(name='4', calibration='brightness_temperature')
return ... | """Test case for reading calibrated reflectances from hrpt data."""
def _get_channel_1_reflectance(self):
"""Get the channel 1 reflectance."""
dataset_id = make_dataid(name='1', calibration='reflectance')
return self._get_dataset(dataset_id)
def test_calibrated_reflectances_values(self... | identifier_body |
test_avhrr_l0_hrpt.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2021 Satpy developers
#
# This file is part of satpy.
#
# satpy 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 Licens... | """Get the channel 4 bt."""
dataset_id = make_dataid(name='3b', calibration='brightness_temperature')
return self._get_dataset(dataset_id)
def _get_channel_3a_reflectance(self):
"""Get the channel 4 bt."""
dataset_id = make_dataid(name='3a', calibration='reflectance')
... | def _get_channel_3b_bt(self): | random_line_split |
main.js | /*
Generates a deck of cards. You can swap cards between the "main" deck and other decks (which can represent players, dealers etc)
Sebastian Lenton 2013
*/
"use strict";
//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];... | (array) {
var counter = array.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter--) | 0;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index... | shuffle | identifier_name |
main.js | /*
Generates a deck of cards. You can swap cards between the "main" deck and other decks (which can represent players, dealers etc)
Sebastian Lenton 2013
*/
"use strict";
//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];... |
var deck = new Deck( 'DefaultDeck' );
var startDeck = new Deck( 'StartDeck' );
var eggDeck = new Deck( 'EggDeck' );
deck.generate();
deck.passCards( eggDeck, 20 );
//deck.passCards( startDeck ); //need to stop too large amounts throwing errors
deck.renderAll();
startDeck.renderAll();
eggDeck.renderAll();
$( '.c... | {
this.cards = [];
this.name = name;
this.generate = function() {
var counter = 0;
for( var j = 0; j < suits.length; j++ ) {
for( var i = 0; i < cardValues.length; i++ ) {
this.cards.push( new Card( suits[ j ], cardValues[ i ], counter ) );
//console.log( this.cards[ this.howMany( true ) ].identify() ... | identifier_body |
main.js | /*
Generates a deck of cards. You can swap cards between the "main" deck and other decks (which can represent players, dealers etc)
Sebastian Lenton 2013
*/
"use strict";
//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];... |
};
this.shuffle = function() {
this.cards = shuffle( this.cards );
};
this.howMany = function( countFromZero ) {
var length = this.cards.length;
if( countFromZero ) {
return length - 1;
} else {
return length;
}
};
this.passCards = function( deck, amount ) { //this could be more efficient
... | {
for( var i = 0; i < cardValues.length; i++ ) {
this.cards.push( new Card( suits[ j ], cardValues[ i ], counter ) );
//console.log( this.cards[ this.howMany( true ) ].identify() );
}
} | conditional_block |
main.js | /*
Generates a deck of cards. You can swap cards between the "main" deck and other decks (which can represent players, dealers etc)
Sebastian Lenton 2013
*/
"use strict";
//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];... | }
}
};
this.shuffle = function() {
this.cards = shuffle( this.cards );
};
this.howMany = function( countFromZero ) {
var length = this.cards.length;
if( countFromZero ) {
return length - 1;
} else {
return length;
}
};
this.passCards = function( deck, amount ) { //this could be more eff... | for( var j = 0; j < suits.length; j++ ) {
for( var i = 0; i < cardValues.length; i++ ) {
this.cards.push( new Card( suits[ j ], cardValues[ i ], counter ) );
//console.log( this.cards[ this.howMany( true ) ].identify() ); | random_line_split |
ui-bootstrap-custom-tpls-0.6.0.js | angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.modal"]);
angular.module("ui.bootstrap.tpls", ["template/modal/backdrop.html","template/modal/window.html"]);
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* ele... |
//destroy scope
modalWindow.modalScope.$destroy();
}
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
$rootScope.$apply(function () {
... | {
backdropDomEl.remove();
backdropDomEl = undefined;
} | conditional_block |
ui-bootstrap-custom-tpls-0.6.0.js | angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.modal"]);
angular.module("ui.bootstrap.tpls", ["template/modal/backdrop.html","template/modal/window.html"]);
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* ele... |
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key);
});
}
}
... | {
var modalWindow = openedWindows.get(modalInstance).value;
//clean up the stack
openedWindows.remove(modalInstance);
//remove window DOM element
modalWindow.modalDomEl.remove();
//remove backdrop if no longer needed
if (backdropIndex() == -1) {
back... | identifier_body |
ui-bootstrap-custom-tpls-0.6.0.js | angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.modal"]);
angular.module("ui.bootstrap.tpls", ["template/modal/backdrop.html","template/modal/window.html"]);
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* ele... | (options) {
return options.template ? $q.when(options.template) :
$http.get(options.templateUrl, {cache: $templateCache}).then(function (result) {
return result.data;
});
}
function getResolvePromises(resolves) {
var promisesArr = ... | getTemplatePromise | identifier_name |
ui-bootstrap-custom-tpls-0.6.0.js | angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.modal"]);
angular.module("ui.bootstrap.tpls", ["template/modal/backdrop.html","template/modal/window.html"]);
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* ele... | $modalStack.dismiss(modal.key);
});
}
}
});
$modalStack.open = function (modalInstance, modal) {
openedWindows.add(modalInstance, {
deferred: modal.deferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keybo... | if (modal && modal.value.keyboard) {
$rootScope.$apply(function () { | random_line_split |
demo2.py | # Import time (for delay) library (for SmartHome api) and GPIO (for raspberry pi gpio)
from library import SmartHomeApi
import RPi.GPIO as GPIO
import time
from datetime import datetime
# 7 -> LED
# Create the client with pre-existing credentials | api = SmartHomeApi("http://localhost:5000/api/0.1", id=10, api_key="api_eMxSb7n6G10Svojn3PlU5P6srMaDrFxmKAnWvnW6UyzmBG")
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
last_status = "UNKNOWN"
while True:
preferences = api.GetUserPrefences(2)['results']
print(preferences)
preference = (item f... | random_line_split | |
demo2.py | # Import time (for delay) library (for SmartHome api) and GPIO (for raspberry pi gpio)
from library import SmartHomeApi
import RPi.GPIO as GPIO
import time
from datetime import datetime
# 7 -> LED
# Create the client with pre-existing credentials
api = SmartHomeApi("http://localhost:5000/api/0.1", id=10, api_key="ap... |
time.sleep(1)
| print(bedtime)
time_str = datetime.now().strftime('%H:%M')
print("time: {}".format(time_str))
bedtime_dt = datetime.strptime(bedtime, "%H:%M")
time_hm = datetime.strptime(time_str, "%H:%M")
if time_hm >= bedtime_dt:
pr... | conditional_block |
scrape.py | # -*- coding: utf-8 -*-
import time
import requests
from datetime import datetime
from logging import getLogger
from typing import Optional
from typing import Dict
from typing import Iterable
from funcy import compose
from funcy import partial
from pandas import DataFrame
from pandas import to_datetime
from pandas imp... |
def insert(cursor, row):
return cursor.execute("""
INSERT INTO scraped_chart (time, currency_pair, high, low, price_usd, quote_volume, volume, weighted_average)
VALUES (%(time)s, %(currency_pair)s, %(high)s, %(low)s, %(price_usd)s, %(quote_volume)s, %(volume)s, %(weighted_average)s);""",
... | if row['volume'] == 0 and row['weighted_average'] == 0:
# we will just ignore these
pass
else:
yield row | conditional_block |
scrape.py | # -*- coding: utf-8 -*-
import time
import requests
from datetime import datetime
from logging import getLogger
from typing import Optional
from typing import Dict
from typing import Iterable
from funcy import compose
from funcy import partial
from pandas import DataFrame
from pandas import to_datetime
from pandas imp... | ex_trades = polo.return_chart_data(
currency_pair=pair,
period=period,
start=start,
end=end,
)
# Data marshalling
ts_df = DataFrame(ex_trades, dtype=float)
ts_df['time'] = [datetime.fromtimestamp(t) for t in ts_df['date']]
ts_df.index = ts_df['time']
ts_df['pr... | now = time.time()
start = start or now - YEAR_IN_SECS
end = end or now | random_line_split |
scrape.py | # -*- coding: utf-8 -*-
import time
import requests
from datetime import datetime
from logging import getLogger
from typing import Optional
from typing import Dict
from typing import Iterable
from funcy import compose
from funcy import partial
from pandas import DataFrame
from pandas import to_datetime
from pandas imp... | (cursor, row):
return cursor.execute("""
INSERT INTO scraped_chart (time, currency_pair, high, low, price_usd, quote_volume, volume, weighted_average)
VALUES (%(time)s, %(currency_pair)s, %(high)s, %(low)s, %(price_usd)s, %(quote_volume)s, %(volume)s, %(weighted_average)s);""",
row... | insert | identifier_name |
scrape.py | # -*- coding: utf-8 -*-
import time
import requests
from datetime import datetime
from logging import getLogger
from typing import Optional
from typing import Dict
from typing import Iterable
from funcy import compose
from funcy import partial
from pandas import DataFrame
from pandas import to_datetime
from pandas imp... |
def scrape_since_last_reading():
# postgres client
client = Postgres.get_client()
cursor = client.cursor()
inserter = partial(insert, cursor)
# get the last time we fetched some data,
# looking at the most recent result in the db
query = ' '.join([
'select time from scraped_chart'... | return cursor.execute("""
INSERT INTO scraped_chart (time, currency_pair, high, low, price_usd, quote_volume, volume, weighted_average)
VALUES (%(time)s, %(currency_pair)s, %(high)s, %(low)s, %(price_usd)s, %(quote_volume)s, %(volume)s, %(weighted_average)s);""",
row.to_dict()) | identifier_body |
Errors.js | import React from 'react'
import PropTypes from 'prop-types'
import { EditorialOverlay } from '../editorials/EditorialParts'
import { css, media } from '../../styles/jss'
import * as s from '../../styles/jso'
import * as ENV from '../../../env'
const spinGif = '/static/images/support/ello-spin.gif' | { maxWidth: 780 },
s.px10,
s.mb30,
s.fontSize14,
media(s.minBreak2, s.px0),
)
export const ErrorStateImage = () =>
<img className={imageStyle} src={spinGif} alt="Ello" width="130" height="130" />
export const ErrorState = ({ children = 'Something went wrong.' }) =>
(<div className={errorStyle}>
{chi... |
const imageStyle = css(s.block, { margin: '0 auto 75px' })
const errorStyle = css( | random_line_split |
initial_data.py | # -*- coding: utf-8 -*-
"""
Contains data that initially get added to the database to bootstrap it.
"""
from __future__ import unicode_literals
# pylint: disable=invalid-name
prophet_muhammad = {
'title': u'Prophet',
'display_name': u'النبي محمد (صلى الله عليه وآله وسلم)'.strip(),
'full_name': u'محمد بن... | first_shia_hadith_text = u'''
نضر الله عبدا سمع مقالتي فوعاها وحفظها وبلغها من لم يسمعها، فرب حامل فقه غير فقيه ورب حامل فقه إلى من هو أفقه منه، ثلاث لا يغل عليهن قلب امرئ مسلم: إخلاص العمل لله، والنصحية لائمة المسلمين، واللزوم لجماعتهم، فإن دعوتهم محيطة من ورائهم، المسلمون إخوة تتكافى دماؤهم ويسعى بذمتهم أدناهم.
'... |
# pylint: disable=line-too-long | random_line_split |
forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2019 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 __future__ import unicode_literals
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from w... | title = StringField(_('Title'), [DataRequired()])
description = IndicoMarkdownField(_('Description'), editor=True) | identifier_body | |
forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2019 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 __future__ import unicode_literals
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from w... | (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 - 2019 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 __future__ import unicode_literals
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from w... | from indico.modules.events.tracks.models.groups import TrackGroup
from indico.util.i18n import _
from indico.web.forms.base import IndicoForm, generated_data
from indico.web.forms.fields import IndicoMarkdownField
class TrackForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()])
code = StringFiel... | random_line_split | |
navigation-bar.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... | @Input() previous?: any; // Previous item. If not defined, the previous arrow won't be shown.
@Input() next?: any; // Next item. If not defined, the next arrow won't be shown.
@Input() info?: string; // Info to show when clicking the info button. If not defined, the info button won't be shown.
@Input() ... | templateUrl: 'core-navigation-bar.html',
})
export class CoreNavigationBarComponent { | random_line_split |
navigation-bar.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... | (): void {
this.textUtils.expandText(this.title, this.info, this.component, this.componentId);
}
}
| showInfo | identifier_name |
navigation-bar.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... |
showInfo(): void {
this.textUtils.expandText(this.title, this.info, this.component, this.componentId);
}
}
| {
this.action = new EventEmitter<any>();
} | identifier_body |
BUE.Button.js | (function($, BUE) {
'use strict';
/**
* @file
* Defines bueditor button object.
*/
/**
* Button constructor
*/
BUE.Button = function(def) {
this.construct(def);
};
/**
* Extend the prototype with state manager.
*/
var Button = BUE.extendProto(BUE.Button.prototype, 'state');
/**
* Constructs the button.
... |
if (shortcut) {
attr.title += ' (' + shortcut + ')';
}
return {tag: 'button', attributes: attr, html: text};
};
/**
* Retrieves the button object from a button element.
*/
BUE.buttonOf = function(el) {
var E = BUE.editorOf(el);
return E ? E.buttons[el.bueBid] : false;
};
})(jQuery, BUE); | {
attr['class'] += ' has-text';
} | conditional_block |
BUE.Button.js | (function($, BUE) {
'use strict';
/**
* @file
* Defines bueditor button object.
*/
/**
* Button constructor
*/
BUE.Button = function(def) {
this.construct(def);
};
/**
* Extend the prototype with state manager.
*/
var Button = BUE.extendProto(BUE.Button.prototype, 'state');
/**
* Constructs the button.
... | };
/**
* Creates the button element.
*/
Button.createEl = function() {
var el = this.el;
if (!el) {
el = this.el = BUE.createEl(BUE.buttonHtml(this));
el.onclick = BUE.eButtonClick;
el.onmousedown = BUE.eButtonMousedown;
el.bueBid = this.id;
}
return el;
};
/**
* Toggles disabed state.
*/
... | */
Button.destroy = function() {
this.remove();
$(this.el).remove();
delete this.el; | random_line_split |
aboutDialog.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import sys
from constants import *
#For using unicode utf-8
reload(sys).setdefaultencoding("utf-8")
from PyQt4 import QtCore
from PyQt4 import QtGui
from uiQt_aboutdialog import Ui_aboutDialog
class aboutDialog(QtGui.QDialog, Ui_aboutDialog):
def __init__(se... | <b>Core Developer:</b><p>
%s<p>
%s"""% (CORE_DEVELOPER, CORE_EMAIL)
self.developersText.setText(developers.decode("utf-8"))
self.translatorsText.setText(TRANSLATORS.decode("utf-8"))
licenseFile = QtCore.QFile("COPYING")
if not licenseFile.open(QtCore.QIODevice.ReadOnly... |
developers = """\ | random_line_split |
aboutDialog.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import sys
from constants import *
#For using unicode utf-8
reload(sys).setdefaultencoding("utf-8")
from PyQt4 import QtCore
from PyQt4 import QtGui
from uiQt_aboutdialog import Ui_aboutDialog
class aboutDialog(QtGui.QDialog, Ui_aboutDialog):
def __init__(se... |
else:
textstream = QtCore.QTextStream(licenseFile)
textstream.setCodec("UTF-8")
license = textstream.readAll()
self.licenseText.setText(license)
iconsLicense = "CC by-nc-sa\nhttp://creativecommons.org/licenses/by-nc-sa/3.0/"
self.ico... | license = LICENSE_NAME | conditional_block |
aboutDialog.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import sys
from constants import *
#For using unicode utf-8
reload(sys).setdefaultencoding("utf-8")
from PyQt4 import QtCore
from PyQt4 import QtGui
from uiQt_aboutdialog import Ui_aboutDialog
class aboutDialog(QtGui.QDialog, Ui_aboutDialog):
| def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.fillAll()
def fillAll(self):
name = """\
<b>%s %s</b><p>
%s<p>
%s"""% (NAME, VERSION, SUMMARY, DESCRIPTION)
self.nameAndVersion.setText(name.decode("utf-8"))
developer... | identifier_body | |
aboutDialog.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import sys
from constants import *
#For using unicode utf-8
reload(sys).setdefaultencoding("utf-8")
from PyQt4 import QtCore
from PyQt4 import QtGui
from uiQt_aboutdialog import Ui_aboutDialog
class | (QtGui.QDialog, Ui_aboutDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.fillAll()
def fillAll(self):
name = """\
<b>%s %s</b><p>
%s<p>
%s"""% (NAME, VERSION, SUMMARY, DESCRIPTION)
self.nameAndVersion.setText(name.decode... | aboutDialog | identifier_name |
questionGenerator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright 2011 Yaşar Arabacı
This file is part of packagequiz.
packagequiz 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 y... | # return getRandomPackage([question.correctAnswer]).name
if __name__ == "__main__":
(getRandomQuestion()) | random_line_split | |
questionGenerator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright 2011 Yaşar Arabacı
This file is part of packagequiz.
packagequiz 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 y... | wrong_answers = []
while len(wrong_answers) < numWrongAnswers:
answer = function(question, numWrongAnswers)
if answer not in wrong_answers and answer is not None:
wrong_answers.append(answer)
return (question.text, correct_answer, wrong_answers,question.... | rrect_answer = question.correctAnswer
| conditional_block |
questionGenerator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright 2011 Yaşar Arabacı
This file is part of packagequiz.
packagequiz 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 y... |
def _requiredBy(question, numWrongAnswers=3):
global localdb
if len(question.correctAnswer) > 0:
correct_answer_name = choice(question.correctAnswer)
correct_answer_package = localdb.get_pkg(correct_answer_name)
correct_answer = correct_answer_name + "(" + correct_answer_package.desc + ... | g = getRandomPackage([question.correctAnswer])
return pkg.name + "(" + pkg.desc + ")"
| identifier_body |
questionGenerator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright 2011 Yaşar Arabacı
This file is part of packagequiz.
packagequiz 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 y... | xception=[]):
"""
Return a random package
@ param exception: list of packages as an exception
@ return: a package
"""
global localdb
package = choice(localdb.pkgcache)
if len(exception) == 0:
return package
else:
while package.name in exception:
package =... | tRandomPackage(e | identifier_name |
models.py | # -*- coding: utf-8 -*-
from datetime import date
from django.db import models
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
import reversion
from users.models import Employee
from services.models import Service
class ProjectStatus(models.Model):
id = model... |
return turnover
def get_turnover_per_year(self):
year_min = self.date_start.year
year_max = self.date_end.year
turnover = dict()
for year in range(year_min,year_max+1):
year_turnover = 0
for deliverable in self.deliverable_set.all():
... | turnover += deliverable.get_turnover() | conditional_block |
models.py | # -*- coding: utf-8 -*-
from datetime import date
from django.db import models
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
import reversion
from users.models import Employee
from services.models import Service
class ProjectStatus(models.Model):
id = model... |
class Deliverable (models.Model):
SERVICE_OWNER_APPROVAL_CHOICES = (
('P','Pending'),
('A','Approved'),
('R','Rejected')
)
project = models.ForeignKey(Project, on_delete=models.PROTECT, verbose_name="project name")
service = models.ForeignKey(Service, on_delete=m... | if value < 0:
raise ValidationError(u'%s is not a positive value !' % value) | identifier_body |
models.py | # -*- coding: utf-8 -*-
from datetime import date
from django.db import models
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
import reversion
from users.models import Employee
from services.models import Service
class ProjectStatus(models.Model):
id = model... | elf):
return self.quantity * self.unit_price
# Register this object in reversion, so that we can track its history
#reversion.register(DeliverableVolume) | t_total_price(s | identifier_name |
models.py | # -*- coding: utf-8 -*-
from datetime import date
from django.db import models
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
import reversion
from users.models import Employee
from services.models import Service
class ProjectStatus(models.Model):
id = model... | deliverable = models.ForeignKey(Deliverable)
date_start = models.DateField(help_text='YYYY-MM-DD')
date_end = models.DateField(help_text='YYYY-MM-DD')
quantity = models.IntegerField(null=True, blank=True)
unit_price = models.DecimalField(max_digits=10, decimal_places=2, default=0, null=True, blank=T... |
class DeliverableVolume(models.Model):
| random_line_split |
step3_controller_test.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... |
var controller;
describe('App.AddHawqStandbyWizardStep3Controller', function () {
beforeEach(function () {
controller = getController();
});
describe('#isSubmitDisabled', function () {
var cases = [
{
isLoaded: false,
isSubmitDisabled: true,
title: 'wizard step c... | {
return App.AddHawqStandbyWizardStep3Controller.create({
content: Em.Object.create({})
});
} | identifier_body |
step3_controller_test.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | () {
return App.AddHawqStandbyWizardStep3Controller.create({
content: Em.Object.create({})
});
}
var controller;
describe('App.AddHawqStandbyWizardStep3Controller', function () {
beforeEach(function () {
controller = getController();
});
describe('#isSubmitDisabled', function () {
var cases = ... | getController | identifier_name |
step3_controller_test.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | })
});
controller.setDynamicConfigValues(configs, data);
});
it('hawq_standby_address_host value', function () {
expect(configs.configs.findProperty('name', 'hawq_standby_address_host').get('value')).to.equal('h1');
});
it('hawq_standby_address_host recommendedValue', function... | hawqMaster: 'h0',
newHawqStandby: 'h1'
} | random_line_split |
definition.rs | use iron::mime::Mime;
use iron::prelude::*;
use iron::status;
use serde_json::to_string;
use super::EngineProvider;
use crate::engine::{Buffer, Context, CursorPosition, Definition};
/// Given a location, return where the identifier is defined
///
/// Possible responses include
///
/// - `200 OK` the request was succ... | struct FindDefinitionResponse {
pub file_path: String,
pub column: usize,
pub line: usize,
pub text: String,
pub context: String,
pub kind: String,
pub docs: String,
} | }
#[derive(Debug, Deserialize, Serialize)] | random_line_split |
definition.rs | use iron::mime::Mime;
use iron::prelude::*;
use iron::status;
use serde_json::to_string;
use super::EngineProvider;
use crate::engine::{Buffer, Context, CursorPosition, Definition};
/// Given a location, return where the identifier is defined
///
/// Possible responses include
///
/// - `200 OK` the request was succ... | () {
let s = stringify!({
"file_path": "src.rs",
"buffers": [{
"file_path": "src.rs",
"contents": "fn foo() {}\nfn bar() {}\nfn main() {\nfoo();\n}"
}],
"line": 4,
"column": 3
});
let req: FindDefinitionRequest = serde_json::from_str(s).unwrap... | find_definition_request_from_json | identifier_name |
definition.rs | use iron::mime::Mime;
use iron::prelude::*;
use iron::status;
use serde_json::to_string;
use super::EngineProvider;
use crate::engine::{Buffer, Context, CursorPosition, Definition};
/// Given a location, return where the identifier is defined
///
/// Possible responses include
///
/// - `200 OK` the request was succ... |
impl From<Definition> for FindDefinitionResponse {
fn from(def: Definition) -> FindDefinitionResponse {
FindDefinitionResponse {
file_path: def.file_path,
column: def.position.col,
line: def.position.line,
text: def.text,
context: def.text_contex... | {
// Parse the request. If the request doesn't parse properly, the request is invalid, and a 400
// BadRequest is returned.
let fdr = match req.get::<::bodyparser::Struct<FindDefinitionRequest>>() {
Ok(Some(s)) => {
trace!("definition::find parsed FindDefinitionRequest");
s
... | identifier_body |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
@property
def install_targets(self):
return [
'INSTALLDIR={0}'.format(self.prefix.bin),
'LIB_PATH_GENERAL={0}'.format(
join_path(self.stage.source_path, 'libStatGen')),
'install'
]
| return ['LIB_PATH_GENERAL={0}'.format(
join_path(self.stage.source_path, 'libStatGen'))] | identifier_body |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | def build_targets(self):
return ['LIB_PATH_GENERAL={0}'.format(
join_path(self.stage.source_path, 'libStatGen'))]
@property
def install_targets(self):
return [
'INSTALLDIR={0}'.format(self.prefix.bin),
'LIB_PATH_GENERAL={0}'.format(
jo... | git='https://github.com/statgen/libStatGen.git',
commit='9db9c23e176a6ce6f421a3c21ccadedca892ac0c'
)
@property | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (self):
return [
'INSTALLDIR={0}'.format(self.prefix.bin),
'LIB_PATH_GENERAL={0}'.format(
join_path(self.stage.source_path, 'libStatGen')),
'install'
]
| install_targets | identifier_name |
util.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | () -> Result<PackageIdent> {
Ok(PackageIdent::from_str(BUSYBOX_IDENT)?)
}
/// Returns the path to a package prefix for the provided Package Identifier in a root file system.
///
/// # Errors
///
/// * If a package cannot be loaded from in the root file system
pub fn pkg_path_for<P: AsRef<Path>>(ident: &PackageIden... | busybox_ident | identifier_name |
util.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... |
/// Returns the path to a package prefix for the provided Package Identifier in a root file system.
///
/// # Errors
///
/// * If a package cannot be loaded from in the root file system
pub fn pkg_path_for<P: AsRef<Path>>(ident: &PackageIdent, rootfs: P) -> Result<PathBuf> {
let pkg_install = PackageInstall::load... | {
Ok(PackageIdent::from_str(BUSYBOX_IDENT)?)
} | identifier_body |
util.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | Path::new("/").join(
pkg_install
.installed_path()
.strip_prefix(rootfs.as_ref())
.expect("installed path contains rootfs path"),
),
)
}
/// Writes a truncated/new file at the provided path with the provided content.
///
/// # Errors
///
/... | let pkg_install = PackageInstall::load(ident, Some(rootfs.as_ref()))?;
Ok( | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.