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 |
|---|---|---|---|---|
imageCover.tsx | import {Event, ipcRenderer} from 'electron'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import * as globalProperties from '../../globalProperties'
import * as HelperUI from '../../HelperUI'
import { ISettings } from '../../settings'
import { TrelloTypes } from '../../TrelloInterfaces'
export d... | extends React.Component<IimageCoverProps, {}> {
public render () {
let extension: string = this.props.attData.url.match(/.+([.].+)/)[1]
if (this.props.settings !== undefined && !this.props.settings.animateGIFs && extension === '.gif') {
extension = '.png'
}
const filename = `${this.props.attData.id}${exten... | ImageCover | identifier_name |
imageCover.tsx | import {Event, ipcRenderer} from 'electron'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import * as globalProperties from '../../globalProperties'
import * as HelperUI from '../../HelperUI'
import { ISettings } from '../../settings'
import { TrelloTypes } from '../../TrelloInterfaces'
export d... |
}
interface IimageCoverProps {
attData: TrelloTypes.Attachment
// TODO - remove this and use Redux
settings: ISettings
}
| {
let extension: string = this.props.attData.url.match(/.+([.].+)/)[1]
if (this.props.settings !== undefined && !this.props.settings.animateGIFs && extension === '.gif') {
extension = '.png'
}
const filename = `${this.props.attData.id}${extension}`
const pathToImage = `${globalProperties.getPath()}attachme... | identifier_body |
imageCover.tsx | import {Event, ipcRenderer} from 'electron'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import * as globalProperties from '../../globalProperties'
import * as HelperUI from '../../HelperUI'
import { ISettings } from '../../settings'
import { TrelloTypes } from '../../TrelloInterfaces'
export d... |
const filename = `${this.props.attData.id}${extension}`
const pathToImage = `${globalProperties.getPath()}attachments/${filename}`
return (
<div style={{backgroundColor: this.props.attData.edgeColor}}>
<img className='imgCover' src={pathToImage}/>
</div>
)
}
}
interface IimageCoverProps {
attData:... | {
extension = '.png'
} | conditional_block |
imageCover.tsx | import {Event, ipcRenderer} from 'electron'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import * as globalProperties from '../../globalProperties'
import * as HelperUI from '../../HelperUI'
import { ISettings } from '../../settings' | if (this.props.settings !== undefined && !this.props.settings.animateGIFs && extension === '.gif') {
extension = '.png'
}
const filename = `${this.props.attData.id}${extension}`
const pathToImage = `${globalProperties.getPath()}attachments/${filename}`
return (
<div style={{backgroundColor: this.props.a... | import { TrelloTypes } from '../../TrelloInterfaces'
export default class ImageCover extends React.Component<IimageCoverProps, {}> {
public render () {
let extension: string = this.props.attData.url.match(/.+([.].+)/)[1] | random_line_split |
index.js | ');
var clientVersion = require('socket.io-client/package').version;
var Client = require('./client');
var Namespace = require('./namespace');
var Adapter = require('socket.io-adapter');
var debug = require('debug')('socket.io:server');
var url = require('url');
/**
* Module exports.
*/
module.exports = Server;
/*... | (srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Ada... | Server | identifier_name |
index.js | var clientVersion = require('socket.io-client/package').version;
var Client = require('./client');
var Namespace = require('./namespace');
var Adapter = require('socket.io-adapter');
var debug = require('debug')('socket.io:server');
var url = require('url');
/**
* Module exports.
*/
module.exports = Server;
/**
*... |
/**
* Server request verification function, that checks for allowed origins
*
* @param {http.IncomingMessage} request
* @param {Function} callback to be called with the result: `fn(err, success)`
*/
Server.prototype.checkRequest = function(req, fn) {
var origin = req.headers.origin || req.headers.referer;
... | {
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
th... | identifier_body |
index.js | ');
var clientVersion = require('socket.io-client/package').version;
var Client = require('./client');
var Namespace = require('./namespace');
var Adapter = require('socket.io-adapter');
var debug = require('debug')('socket.io:server');
var url = require('url');
/**
* Module exports.
*/
module.exports = Server;
/*... | else {
for (var i = 0; i < evs.length; i++) {
evs[i].call(srv, req, res);
}
}
});
};
/**
* Handles a request serving `/socket.io.js`
*
* @param {http.Request} req
* @param {http.Response} res
* @api private
*/
Server.prototype.serve = function(req, res){
var etag = req.headers['if-n... | {
self.serve(req, res);
} | conditional_block |
index.js | ');
var clientVersion = require('socket.io-client/package').version;
var Client = require('./client');
var Namespace = require('./namespace');
var Adapter = require('socket.io-adapter');
var debug = require('debug')('socket.io:server');
var url = require('url');
/**
* Module exports.
*/
module.exports = Server;
/*... | * @api public
*/
Server.prototype.listen =
Server.prototype.attach = function(srv, opts){
if ('function' == typeof srv) {
var msg = 'You are trying to attach socket.io to an express' +
'request handler function. Please pass a http.Server instance.';
throw new Error(msg);
}
// handle a port as a st... | * @param {http.Server|Number} server or port
* @param {Object} options passed to engine.io
* @return {Server} self | random_line_split |
plugin.py | # @file plugin.py
#
# Connect Zen Coding to Pluma.
#
# Adapted to pluma by Joao Manoel (joaomanoel7@gmail.com)
#
# Original Author Franck Marcia (franck.marcia@gmail.com)
#
import pluma, gobject, gtk, os
from zen_editor import ZenEditor
zencoding_ui_str = """
<ui>
<menubar name="MenuBar">
<menu name="EditMenu"... | (self, action, window):
self.editor.expand_abbreviation(window)
def expand_with_abbreviation(self, action, window):
self.editor.expand_with_abbreviation(window)
def wrap_with_abbreviation(self, action, window):
self.editor.wrap_with_abbreviation(window)
def match_pair_inwa... | expand_abbreviation | identifier_name |
plugin.py | # @file plugin.py
#
# Connect Zen Coding to Pluma.
#
# Adapted to pluma by Joao Manoel (joaomanoel7@gmail.com)
#
# Original Author Franck Marcia (franck.marcia@gmail.com)
#
import pluma, gobject, gtk, os
from zen_editor import ZenEditor
zencoding_ui_str = """
<ui>
<menubar name="MenuBar">
<menu name="EditMenu"... |
def update_ui(self, window):
view = window.get_active_view()
windowdata = window.get_data("ZenCodingPluginDataKey")
windowdata["action_group"].set_sensitive(bool(view and view.get_editable()))
def expand_abbreviation(self, action, window):
self.editor.expand_abbreviation(windo... | windowdata = window.get_data("ZenCodingPluginDataKey")
manager = window.get_ui_manager()
manager.remove_ui(windowdata["ui_id"])
manager.remove_action_group(windowdata["action_group"]) | identifier_body |
plugin.py | # @file plugin.py
#
# Connect Zen Coding to Pluma.
#
# Adapted to pluma by Joao Manoel (joaomanoel7@gmail.com)
#
# Original Author Franck Marcia (franck.marcia@gmail.com)
#
import pluma, gobject, gtk, os
from zen_editor import ZenEditor
zencoding_ui_str = """
<ui>
<menubar name="MenuBar">
<menu name="EditMenu"... | windowdata["action_group"] = gtk.ActionGroup("PlumaZenCodingPluginActions")
windowdata["action_group"].add_actions(actions, window)
manager = window.get_ui_manager()
manager.insert_action_group(windowdata["action_group"], -1)
windowdata["ui_id"] = manager.add_ui_from_string(zenco... | ]
windowdata = dict()
window.set_data("ZenCodingPluginDataKey", windowdata) | random_line_split |
plugin.py | # @file plugin.py
#
# Connect Zen Coding to Pluma.
#
# Adapted to pluma by Joao Manoel (joaomanoel7@gmail.com)
#
# Original Author Franck Marcia (franck.marcia@gmail.com)
#
import pluma, gobject, gtk, os
from zen_editor import ZenEditor
zencoding_ui_str = """
<ui>
<menubar name="MenuBar">
<menu name="EditMenu"... |
def deactivate(self, window):
windowdata = window.get_data("ZenCodingPluginDataKey")
manager = window.get_ui_manager()
manager.remove_ui(windowdata["ui_id"])
manager.remove_action_group(windowdata["action_group"])
def update_ui(self, window):
view = window.get_active_... | md = gtk.MessageDialog(window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
gtk.BUTTONS_CLOSE, "There is an error in user settings:")
message = "{0} on line {1} at character {2}\n\nUser settings will not be available."
md.set_title("Zen Coding error")
md.format_secondary_text... | conditional_block |
index.js | var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHTML(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function escapeCodeBlocks() {
var sections = document.querySelect... | () {
var menuList = document.querySelector('.menu-list'),
menuItems = document.querySelectorAll('a[name]'),
menuToggle = document.querySelector('.menu-toggle');
menuToggle.addEventListener('click', function () {
var menu = document.querySelector('.menu');
if (menu.classList.contains('menu-open'... | createMenu | identifier_name |
index.js | var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHTML(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function escapeCodeBlocks() {
var sections = document.querySelect... |
});
[].forEach.call(menuItems, function (menuItem) {
var menuText = menuItem.name.charAt(0).toUpperCase() + menuItem.name.slice(1);
var anchor = document.createElement('a');
anchor.href = '#' + menuText.toLowerCase();
var listItemEl = document.createElement('li');
listItemEl.classList.add('men... | {
menu.classList.add('menu-open');
this.classList.add('menu-toggle-open');
} | conditional_block |
index.js | var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHTML(string) |
function escapeCodeBlocks() {
var sections = document.querySelectorAll('.page-section');
[].forEach.call(sections, function (section) {
var sectionCodeBlocks = section.querySelectorAll('.section-code');
if (sectionCodeBlocks.length) {
[].forEach.call(sectionCodeBlocks, function (codeBlock) {
... | {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
} | identifier_body |
index.js | var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHTML(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function escapeCodeBlocks() {
var sections = document.querySelect... |
function toggleMenu() {
}
function createMenu() {
var menuList = document.querySelector('.menu-list'),
menuItems = document.querySelectorAll('a[name]'),
menuToggle = document.querySelector('.menu-toggle');
menuToggle.addEventListener('click', function () {
var menu = document.querySelector('.men... | random_line_split | |
setup.py | # -*- coding: utf-8 -*-
""" Flexx setup script.
"""
import os
from os import path as op
try:
# use setuptools namespace, allows for "develop"
import setuptools # noqa, analysis:ignore
except ImportError:
pass # it's not essential for installation
from distutils.core import setup
name = 'flexx'
descrip... |
def package_tree(pkgroot):
path = os.path.dirname(__file__)
subdirs = [os.path.relpath(i[0], path).replace(os.path.sep, '.')
for i in os.walk(os.path.join(path, pkgroot))
if '__init__.py' in i[2]]
return subdirs
setup(
name=name,
version=__version__,
author='Fl... | __doc__ += line | conditional_block |
setup.py | # -*- coding: utf-8 -*-
""" Flexx setup script.
"""
import os
from os import path as op
try:
# use setuptools namespace, allows for "develop"
import setuptools # noqa, analysis:ignore
except ImportError:
pass # it's not essential for installation
from distutils.core import setup
name = 'flexx'
descrip... | (pkgroot):
path = os.path.dirname(__file__)
subdirs = [os.path.relpath(i[0], path).replace(os.path.sep, '.')
for i in os.walk(os.path.join(path, pkgroot))
if '__init__.py' in i[2]]
return subdirs
setup(
name=name,
version=__version__,
author='Flexx contributors',
... | package_tree | identifier_name |
setup.py | # -*- coding: utf-8 -*-
""" Flexx setup script.
"""
import os
from os import path as op
try:
# use setuptools namespace, allows for "develop"
import setuptools # noqa, analysis:ignore
except ImportError:
pass # it's not essential for installation
from distutils.core import setup
name = 'flexx'
descrip... | download_url='https://pypi.python.org/pypi/flexx',
keywords="ui design, web runtime, pyscript, reactive programming, FRP",
description=description,
long_description=__doc__,
platforms='any',
provides=[name],
install_requires=[],
packages=package_tree(name),
package_dir={name: name},
... | version=__version__,
author='Flexx contributors',
author_email='almar.klein@gmail.com',
license='(new) BSD',
url='http://flexx.readthedocs.org', | random_line_split |
setup.py | # -*- coding: utf-8 -*-
""" Flexx setup script.
"""
import os
from os import path as op
try:
# use setuptools namespace, allows for "develop"
import setuptools # noqa, analysis:ignore
except ImportError:
pass # it's not essential for installation
from distutils.core import setup
name = 'flexx'
descrip... |
setup(
name=name,
version=__version__,
author='Flexx contributors',
author_email='almar.klein@gmail.com',
license='(new) BSD',
url='http://flexx.readthedocs.org',
download_url='https://pypi.python.org/pypi/flexx',
keywords="ui design, web runtime, pyscript, reactive programming, FRP",... | path = os.path.dirname(__file__)
subdirs = [os.path.relpath(i[0], path).replace(os.path.sep, '.')
for i in os.walk(os.path.join(path, pkgroot))
if '__init__.py' in i[2]]
return subdirs | identifier_body |
print.rs | fn main() {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{} days", 31);
// Without a suffix, 31 becomes an i32. You can change what type 31 is,
// with a suffix.
// There are various optional patterns this works with. Positi... | // Special formatting can be specified after a `:`.
println!("{} of {:b} people know binary, the other half don't", 1, 2);
// You can right-align text with a specified width. This will output
// " 1". 5 white spaces and a "1".
println!("{number:>width$}", number=1, width=6);
// You can pad... | subject="the quick brown fox",
verb="jumps over");
| random_line_split |
print.rs | fn main() {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{} days", 31);
// Without a suffix, 31 becomes an i32. You can change what type 31 is,
// with a suffix.
// There are various optional patterns this works with. Positi... | (i32);
// However, custom types such as this structure require more complicated
// handling. This will not work.
println!("This struct `{}` won't print...", Structure(3));
// FIXME ^ Comment out this line.
}
| Structure | identifier_name |
print.rs | fn main() |
// You can right-align text with a specified width. This will output
// " 1". 5 white spaces and a "1".
println!("{number:>width$}", number=1, width=6);
// You can pad numbers with extra zeroes. This will output "000001".
println!("{number:>0width$}", number=1, width=6);
// It will even c... | {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{} days", 31);
// Without a suffix, 31 becomes an i32. You can change what type 31 is,
// with a suffix.
// There are various optional patterns this works with. Positional
/... | identifier_body |
lightbox.js | id:'numberDisplay'})
]),
Builder.node('div',{id:'bottomNav'},
Builder.node('a',{id:'bottomNavClose', href: '#' },
Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage })
)
... | random_line_split | ||
here-now.py | ## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/
import sys
from pubnub import PubnubTornado as Pubnub
publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
subscri... |
## -----------------------------------------------------------------------
## Initiate Pubnub State
## -----------------------------------------------------------------------
pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key,
secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_o... | secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
cipher_key = len(sys.argv) > 4 and sys.argv[4] or ''
ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False | random_line_split |
here-now.py | ## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/
import sys
from pubnub import PubnubTornado as Pubnub
publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
subscri... | (message):
print(message)
pubnub.here_now(channel, callback=callback, error=callback)
pubnub.start()
| callback | identifier_name |
here-now.py | ## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/
import sys
from pubnub import PubnubTornado as Pubnub
publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
subscri... |
pubnub.here_now(channel, callback=callback, error=callback)
pubnub.start()
| print(message) | identifier_body |
test_networks.py | # -*- coding: utf-8 -*-
# a hack for pytest to allow imports
if __package__ is None:
import sys
import os.path
sys.path[0:0] = [
os.path.dirname( # project_root
os.path.dirname( # tests
os.path.abspath(__file__) # this file
)... |
@pytest.mark.parametrize("input_", (
" ",
"#commentary",
"""
# commentary
# another commentary
"""
))
def test_empty(self, input_):
with httmock.HTTMock(self.fake_response(input_)):
assert list(fetch_networks("http://fake.url")) == []
#... | with httmock.HTTMock(self.fake_response(self.FAKE_CONTENT)):
networks = [str(ntw) for ntw in fetch_networks("http://fake.url")]
assert set(networks) == set(self.FAKE_NETWORKS) | identifier_body |
test_networks.py | # -*- coding: utf-8 -*-
# a hack for pytest to allow imports
if __package__ is None:
import sys
import os.path
sys.path[0:0] = [
os.path.dirname( # project_root
os.path.dirname( # tests
os.path.abspath(__file__) # this file
)... | (self, input_):
network = convert_to_ipnetworks(input_)
assert network and len(network) > 0
@pytest.mark.parametrize("input_", (
"HELLO:223.123.123.123-123.123.123.255",
"EVIL HACKER:150.250.250.250-",
":150.250.250.250-15",
"::15.12"
))
def test_nok(self, in... | test_ok | identifier_name |
test_networks.py | # -*- coding: utf-8 -*-
# a hack for pytest to allow imports
if __package__ is None:
|
import httmock
import pytest
from six import moves
from iblocklist2ipset.networks import extract_networks, fetch_networks, \
convert_to_ipnetworks, ParseError
from tests import CommonTest
# noinspection PyUnresolvedReferences
class TestConvertToIPNetwork(object):
@pytest.mark.parametrize("input_", (
... | import sys
import os.path
sys.path[0:0] = [
os.path.dirname( # project_root
os.path.dirname( # tests
os.path.abspath(__file__) # this file
)
)
] | conditional_block |
test_networks.py | # -*- coding: utf-8 -*-
# a hack for pytest to allow imports
if __package__ is None:
import sys
import os.path
sys.path[0:0] = [
os.path.dirname( # project_root
os.path.dirname( # tests
os.path.abspath(__file__) # this file
)... | " ",
"#commentary",
"""
# commentary
# another commentary
"""
))
def test_empty(self, input_):
with httmock.HTTMock(self.fake_response(input_)):
assert list(fetch_networks("http://fake.url")) == []
# noinspection PyMethodMayBeStatic
class Tes... | @pytest.mark.parametrize("input_", ( | random_line_split |
build.rs | extern crate gcc;
use std::fs;
use std::io;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::OsString;
trait CommandExt {
fn execute(&mut self) -> io::Result<()>;
}
impl CommandExt for Command {
/// Execute the command and return an error if it exited with a failure stat... | if !build_dir.join("liblua.a").exists() {
let tooling = config.get_compiler();
try!(fs::create_dir_all(&build_dir));
try!(build_lua(&tooling, &lua_dir, &build_dir));
}
println!("cargo:rustc-link-search=native={}", build_dir.display());
}
// Ensure the... | {
let lua_dir = match env::var_os("LUA_LOCAL_SOURCE") {
// If LUA_LOCAL_SOURCE is set, use it
Some(dir) => PathBuf::from(dir),
// Otherwise, pull from lua-source/src in the crate root
None => {
let mut dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
... | identifier_body |
build.rs | extern crate gcc;
use std::fs;
use std::io;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::OsString;
trait CommandExt {
fn execute(&mut self) -> io::Result<()>;
}
impl CommandExt for Command {
/// Execute the command and return an error if it exited with a failure stat... | Err(io::Error::new(io::ErrorKind::Other, format!("The command\n\
\t{:?}\n\
did not run successfully.", self)))
}
}
}
/// The command to build lua, with switches for different OSes.
fn build_lua(tooling: &gcc::Tool, source: &Path, build: &Path) -> io::Result<()> {
// ... | } else { | random_line_split |
build.rs | extern crate gcc;
use std::fs;
use std::io;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::OsString;
trait CommandExt {
fn execute(&mut self) -> io::Result<()>;
}
impl CommandExt for Command {
/// Execute the command and return an error if it exited with a failure stat... | (tooling: &gcc::Tool, source: &Path, build: &Path) -> io::Result<()> {
// calculate the Lua platform name
let platform = match env::var("TARGET").unwrap().split('-').nth(2).unwrap() {
"windows" => "mingw",
"macos" => "macosx",
"linux" => "linux",
"freebsd" => "freebsd",
"... | build_lua | identifier_name |
meetings.component.ts | import { Component, OnInit } from '@angular/core';
import { MeetingService } from '../../_services/meeting.service';
import { Meeting } from '../../../Meeting';
import { AuthHttp } from 'angular2-jwt'
import { Router } from '@angular/router'
@Component({
moduleId: module.id,
selector: 'meetings',
templateUrl: '/... | () {
this.loadAllMeetings();
}
private loadAllMeetings() {
this.meetingService.getAll().subscribe(meetings => { this.meetings = meetings; });
}
onSelect(meeting: Meeting): void {
this.currentMeeting = meeting;
}
gotoMeetingPage(): void {
const id = "_id";
th... | ngOnInit | identifier_name |
meetings.component.ts | import { Component, OnInit } from '@angular/core';
import { MeetingService } from '../../_services/meeting.service';
import { Meeting } from '../../../Meeting';
import { AuthHttp } from 'angular2-jwt'
import { Router } from '@angular/router'
@Component({
moduleId: module.id,
selector: 'meetings',
templateUrl: '/... |
gotoMeetingPage(): void {
const id = "_id";
this.router.navigate(['/template/meeting-page', this.currentMeeting[id]]);
}
} |
onSelect(meeting: Meeting): void {
this.currentMeeting = meeting;
} | random_line_split |
xz.rs | /*
* Copyright (c) 2017 Jean Guyomarc'h
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, pub... | * extension) of in_file */
let mut output = out_dir.to_path_buf();
match in_file.file_name() {
Some(os_str) => {
output.push(os_str);
},
None => { return Err(unpacker::PathError); }
}
output.set_extension("");
let mut cmd = subprocess::new("xz... | std::fs::create_dir_all(out_dir)?;
}
/* We will write a single file in out_dir with the basename (without | random_line_split |
xz.rs | /*
* Copyright (c) 2017 Jean Guyomarc'h
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, pub... | () -> &'static str {
"xz"
}
| name_get | identifier_name |
xz.rs | /*
* Copyright (c) 2017 Jean Guyomarc'h
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, pub... |
};
/* Create the output directory if it does not exist */
if ! out_dir.exists() {
std::fs::create_dir_all(out_dir)?;
}
/* We will write a single file in out_dir with the basename (without
* extension) of in_file */
let mut output = out_dir.to_path_buf();
matc... | { return Err(unpacker::PathError); } | conditional_block |
canvas_util.rs | /// Get the size of an atlas image.
fn image_dim(&self, img: Image) -> V2<u32>;
/// Draw a stored image on the canvas.
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D);
/// Draw a filled rectangle.
fn fill_rect<... | self.push_vertex(p1 + v2 + v1, layer, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn image_dim(&self, img: Image) -> V2<u32> {
self.image_data(img).pos.1.map(|x| x as u32)
}
... | {
if p1 == p2 { return; }
let tex = self.solid_tex_coord();
// The front vector. Extend by width.
let v1 = p2 - p1;
let scalar = v1.dot(v1);
let scalar = (scalar + width * width) / scalar;
let v1 = v1 * scalar;
// The sideways vector, turn into unit vec... | identifier_body |
canvas_util.rs | fn image_dim(&self, img: Image) -> V2<u32>;
/// Draw a stored image on the canvas.
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D);
/// Draw a filled rectangle.
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Re... | let timestamp = time::precise_time_s() as u64;
// Create screenshot filenames by concatenating the current timestamp in
// seconds with a running number from 00 to 99. 100 shots per second
// should be good enough.
| random_line_split | |
canvas_util.rs | border: Option<D>);
fn char_width(&self, c: char) -> f32;
/// Write a timestamped screenshot PNG to disk.
fn save_screenshot(&mut self, basename: &str);
}
impl<'a> CanvasUtil for Canvas<'a> {
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C) {
... | {
// Thread-safe claiming: create_dir will fail if the dir
// already exists (it'll exist if another thread is gunning
// for the same filename and managed to get past us here).
// At least assuming that create_dir is atomic...
let squat_di... | conditional_block | |
canvas_util.rs | /// Get the size of an atlas image.
fn image_dim(&self, img: Image) -> V2<u32>;
/// Draw a stored image on the canvas.
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D);
/// Draw a filled rectangle.
fn fill_rect<... | <C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C) {
if p1 == p2 { return; }
let tex = self.solid_tex_coord();
// The front vector. Extend by width.
let v1 = p2 - p1;
let scalar = v1.dot(v1);
let scalar = (scalar + width * width)... | draw_line | identifier_name |
cron.py | import os
import datetime
from jinja2 import Environment,PackageLoader,TemplateNotFound
from hotzenplotz.openstack.common import cfg
from hotzenplotz.openstack.common import log as logging
from hotzenplotz.openstack.common import utils
from hotzenplotz.common import exception
from hotzenplotz.api import validator
L... | (self, lb_name,
base_cfg_path='/etc/haproxy/haproxy.cfg'):
with open(base_cfg_path) as cfg:
lines = cfg.readlines()
try:
in_use_lb_name = [line.split()[1] for line in lines
if line.startswith('listen')]
except IndexErro... | _is_lb_in_use | identifier_name |
cron.py | import os
import datetime
from jinja2 import Environment,PackageLoader,TemplateNotFound
from hotzenplotz.openstack.common import cfg
from hotzenplotz.openstack.common import log as logging
from hotzenplotz.openstack.common import utils
from hotzenplotz.common import exception
from hotzenplotz.api import validator
L... |
LOG.debug("Updated the new load balancer successfully")
def _validate_request(self, request):
validate.check_tcp_request(request)
def _get_lb_name(self, msg):
# TODO(wenjianhn): utf-8 support, base64
##return "%s_%s" % (msg['project_id'],
return "%s" % msg['uuid']
... | LOG.debug("Updating the haproxy load "
"balancer for NAME:%s USER: %s PROJECT:%s" %
(msg['uuid'], msg['user_id'], msg['project_id']))
try:
lb_deleted_cfg_path = self._create_lb_deleted_haproxy_cfg(msg)
except exception.HaproxyLBNotExists as e:
... | identifier_body |
cron.py | import os
import datetime
from jinja2 import Environment,PackageLoader,TemplateNotFound
from hotzenplotz.openstack.common import cfg
from hotzenplotz.openstack.common import log as logging
from hotzenplotz.openstack.common import utils
from hotzenplotz.common import exception
from hotzenplotz.api import validator
L... | try:
if not self.dir_path:
self.dir_path = '/etc/puppet/modules/cron/'
cron_name = msg['title']
file_path = self.dir_path + cron_name
if not path.exists(file_path):
with open(file_path,'a') as f:
f.write(output... | random_line_split | |
cron.py | import os
import datetime
from jinja2 import Environment,PackageLoader,TemplateNotFound
from hotzenplotz.openstack.common import cfg
from hotzenplotz.openstack.common import log as logging
from hotzenplotz.openstack.common import utils
from hotzenplotz.common import exception
from hotzenplotz.api import validator
L... |
LOG.debug("Created the new cron successfully")
def _delete_cron(self, msg):
LOG.debug("Deleting cron for NAME:%s USER: %s PROJECT:%s" %
(msg['id'], msg['user_id'], msg['project_id']))
try:
new_cfg_path = self._create_lb_deleted_haproxy_cfg(msg)
excep... | try:
self._test_syntax(file_path)
except exception.ProcessExecutionError as e:
raise exception.CronCreateError(explanation=str(e)) | conditional_block |
service.rs | : ::protobuf::SingularField::none(),
unknown_fields: ::protobuf::UnknownFields::new(),
cached_size: ::std::cell::Cell::new(0),
}
})
}
}
// optional string name = 1;
pub fn clear_name(&mut self) {
self.name.clear();
}
... | (&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields<'s>(&'s self) -> &'s ::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields<'s>(&'s mut self) -> &'s mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn type_id(&self) -> ::std:... | get_cached_size | identifier_name |
service.rs | : ::protobuf::SingularField::none(),
unknown_fields: ::protobuf::UnknownFields::new(),
cached_size: ::std::cell::Cell::new(0),
}
})
}
}
// optional string name = 1;
pub fn clear_name(&mut self) {
self.name.clear();
}
... |
pub fn get_name<'a>(&'a self) -> &'a str {
match self.name.as_ref() {
Some(v) => &v,
None => "",
}
}
}
impl ::protobuf::Message for Service {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -... | random_line_split | |
service.rs | : ::protobuf::SingularField::none(),
unknown_fields: ::protobuf::UnknownFields::new(),
cached_size: ::std::cell::Cell::new(0),
}
})
}
}
// optional string name = 1;
pub fn clear_name(&mut self) {
self.name.clear();
}
... |
fn descriptor_static(_: ::std::option::Option<Service>) -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protob... | {
Service::new()
} | identifier_body |
plot_pe_spatial.py | cmdprov
repo_dir = '/'.join(script_dir.split('/')[:-2])
module_dir = repo_dir + '/modules'
sys.path.append(module_dir)
try:
import general_io as gio
import timeseries
except ImportError:
raise ImportError('Script and modules in wrong directories')
def regrid(cube):
"""Define the sample points for in... | width = 25
height = 10
fig = plt.figure(figsize=[width, height])
outproj = ccrs.PlateCarree(central_longitude=180.0)
nrows = 2
ncols = 2
ax1 = plt.subplot(nrows, ncols, 1, projection=outproj)
plot_data(ax1,
clim_ensemble_mean,
clim_ensemble_agreement,
... | aa_ensemble_mean, aa_ensemble_agreement = ensemble_stats(aa_cube_list)
hist_cube_list, hist_history = get_cube_list(args.hist_files, 'anom', time_bounds=args.time_bounds)
hist_ensemble_mean, hist_ensemble_agreement = ensemble_stats(hist_cube_list)
| random_line_split |
plot_pe_spatial.py | cmdprov
repo_dir = '/'.join(script_dir.split('/')[:-2])
module_dir = repo_dir + '/modules'
sys.path.append(module_dir)
try:
import general_io as gio
import timeseries
except ImportError:
raise ImportError('Script and modules in wrong directories')
def regrid(cube):
"""Define the sample points for in... |
cube = cube.interpolate(sample_points, iris.analysis.Linear())
cube.coord('latitude').guess_bounds()
cube.coord('longitude').guess_bounds()
cube.coord('latitude').standard_name = 'latitude'
cube.coord('latitude').long_name = 'latitude'
cube.coord('latitude').var_name = 'lat'
cube.coor... | if 'lat' in coord:
sample_points.append((coord, lats))
elif 'lon' in coord:
sample_points.append((coord, lons)) | conditional_block |
plot_pe_spatial.py | cmdprov
repo_dir = '/'.join(script_dir.split('/')[:-2])
module_dir = repo_dir + '/modules'
sys.path.append(module_dir)
try:
import general_io as gio
import timeseries
except ImportError:
raise ImportError('Script and modules in wrong directories')
def regrid(cube):
"""Define the sample points for in... | nrows = 2
ncols = 2
ax1 = plt.subplot(nrows, ncols, 1, projection=outproj)
plot_data(ax1,
clim_ensemble_mean,
clim_ensemble_agreement,
'clim',
'(a) piControl',
agreement_bounds=[0.33, 0.66])
ax2 = plt.subplot(nrows, ncols, 2, pro... | """Run the program."""
clim_cube_list, clim_history = get_cube_list(args.clim_files, 'clim', quick=args.quick)
clim_ensemble_mean, clim_ensemble_agreement = ensemble_stats(clim_cube_list)
clim_ensemble_mean.data = clim_ensemble_mean.data * 86400
ghg_cube_list, ghg_history = get_cube_list(args.ghg_file... | identifier_body |
plot_pe_spatial.py | cmdprov
repo_dir = '/'.join(script_dir.split('/')[:-2])
module_dir = repo_dir + '/modules'
sys.path.append(module_dir)
try:
import general_io as gio
import timeseries
except ImportError:
raise ImportError('Script and modules in wrong directories')
def regrid(cube):
"""Define the sample points for in... | (cube_list):
"""Get the ensemble mean and sign agreement"""
equalise_attributes(cube_list)
ensemble_cube = cube_list.merge_cube()
ensemble_mean = ensemble_cube.collapsed('ensemble_member', iris.analysis.MEAN, mdtol=0)
ensemble_mean.remove_coord('ensemble_member')
ensemble_agreemen... | ensemble_stats | identifier_name |
htmlbrelement.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 http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElemen... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLBRElement> {
let element = HTMLBRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
}... | {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
} | identifier_body |
htmlbrelement.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 http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElemen... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBRElement {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString... | new_inherited | identifier_name |
htmlbrelement.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 http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElemen... | Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
}
} | pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLBRElement> {
let element = HTMLBRElement::new_inherited(localName, prefix, document); | random_line_split |
slug.py | # -*- coding: utf-8 -*-
from django.utils import baseconv
from django.template.defaultfilters import slugify
import time
def slugify_uniquely(value, model, slugfield="slug"):
|
def ref_uniquely(project, model, field='ref'):
"""
Returns a unique reference code based on base64 and time.
"""
# this prevents concurrent and inconsistent references.
time.sleep(0.001)
new_timestamp = lambda: int("".join(str(time.time()).split(".")))
while True:
potential = ba... | """
Returns a slug on a name which is unique within a model's table
"""
suffix = 0
potential = base = slugify(value)
if len(potential) == 0:
potential = 'null'
while True:
if suffix:
potential = "-".join([base, str(suffix)])
if not model.objects.filter(**{slu... | identifier_body |
slug.py | # -*- coding: utf-8 -*-
from django.utils import baseconv
from django.template.defaultfilters import slugify
import time
def slugify_uniquely(value, model, slugfield="slug"):
"""
Returns a slug on a name which is unique within a model's table
"""
suffix = 0
potential = base = slugify(value)
... | """
# this prevents concurrent and inconsistent references.
time.sleep(0.001)
new_timestamp = lambda: int("".join(str(time.time()).split(".")))
while True:
potential = baseconv.base62.encode(new_timestamp())
params = {field: potential, 'project': project}
if not model.objec... | Returns a unique reference code based on base64 and time. | random_line_split |
slug.py | # -*- coding: utf-8 -*-
from django.utils import baseconv
from django.template.defaultfilters import slugify
import time
def slugify_uniquely(value, model, slugfield="slug"):
"""
Returns a slug on a name which is unique within a model's table
"""
suffix = 0
potential = base = slugify(value)
... | potential = baseconv.base62.encode(new_timestamp())
params = {field: potential, 'project': project}
if not model.objects.filter(**params).exists():
return potential
time.sleep(0.0002) | conditional_block | |
slug.py | # -*- coding: utf-8 -*-
from django.utils import baseconv
from django.template.defaultfilters import slugify
import time
def | (value, model, slugfield="slug"):
"""
Returns a slug on a name which is unique within a model's table
"""
suffix = 0
potential = base = slugify(value)
if len(potential) == 0:
potential = 'null'
while True:
if suffix:
potential = "-".join([base, str(suffix)])
... | slugify_uniquely | identifier_name |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl cat {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not... | {
println!("Meow");
self.meows += 1_usize;
if self.meows % 5_usize == 0_usize {
self.how_hungry += 1;
}
} | identifier_body |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
impl cat {
fn meow(&mut self) {
println!("Meow");
self.meows += 1_usize;
if self.meows % 5_usize == 0_usize {
self.how_hungry += 1;
}
}
}
impl cat {
pub fn speak(&mut self) { self.meow(); }
pu... | }
impl fmt::String for cat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name) | random_line_split |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
else {
println!("Not hungry!");
return false;
}
}
}
pub fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
}
| {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} | conditional_block |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not hungry!");
return false;
}
}
}
pub fn cat(in_x... | eat | identifier_name |
output.py | from __future__ import unicode_literals
import sys
from pre_commit import color
from pre_commit import five
def get_hook_message(
start,
postfix='',
end_msg=None,
end_len=0,
end_color=None,
use_color=None,
cols=80,
):
"""Prints a message for running a hook... | if s is not None:
stream.write(five.to_bytes(s))
stream.write(b'\n')
stream.flush() | identifier_body | |
output.py | from __future__ import unicode_literals
import sys
from pre_commit import color
from pre_commit import five
def get_hook_message(
start,
postfix='',
end_msg=None,
end_len=0,
end_color=None,
use_color=None,
cols=80,
):
"""Prints a message for running a hook... | # is specified and a newline afterwards
>>> print_hook_message(
'start',
end_msg='end',
end_color=color.RED,
use_color=True,
)
start...................................................................end
# Print `start` followed by dots, followed by the `postfix` mess... | start...............................................................
# Print `start` followed by dots with the end message colored if coloring | random_line_split |
output.py | from __future__ import unicode_literals
import sys
from pre_commit import color
from pre_commit import five
def get_hook_message(
start,
postfix='',
end_msg=None,
end_len=0,
end_color=None,
use_color=None,
cols=80,
):
"""Prints a message for running a hook... |
if end_msg is not None and (end_color is None or use_color is None):
raise ValueError(
'`end_color` and `use_color` are required with `end_msg`'
)
if end_len:
return start + '.' * (cols - len(start) - end_len - 1)
else:
return '{}{}{}{}\n'.format(
st... | raise ValueError('Expected one of (`end_msg`, `end_len`)') | conditional_block |
output.py | from __future__ import unicode_literals
import sys
from pre_commit import color
from pre_commit import five
def | (
start,
postfix='',
end_msg=None,
end_len=0,
end_color=None,
use_color=None,
cols=80,
):
"""Prints a message for running a hook.
This currently supports three approaches:
# Print `start` followed by dots, leaving 6 characters at the end
>>> prin... | get_hook_message | identifier_name |
table.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 {TableCell} from '../util'; |
// We load "IncrementalDOM" as a AMD global because the "incremental-dom" NPM package does not
// come with a named UMD module, and it's easier to just import the AMD file and use it globally.
declare const IncrementalDOM: any;
const {patch, elementOpen, elementClose, elementOpenStart, elementOpenEnd, attr, text} =
... | random_line_split | |
table.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 {TableCell} from '../util';
// We load "IncrementalDOM" as a AMD global because the "incremental-dom" NPM pa... | (private _rootEl: any) {}
set data(data: TableCell[][]) { patch(this._rootEl, () => this._render(data)); }
private _render(data: TableCell[][]) {
elementOpen('table');
elementOpen('tbody');
for (let r = 0; r < data.length; r++) {
elementOpen('tr');
const row = data[r];
for (let c = 0... | constructor | identifier_name |
table.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 {TableCell} from '../util';
// We load "IncrementalDOM" as a AMD global because the "incremental-dom" NPM pa... |
elementClose('tbody');
elementClose('table');
}
}
| {
elementOpen('tr');
const row = data[r];
for (let c = 0; c < row.length; c++) {
elementOpenStart('td');
if (r % 2 === 0) {
attr('style', 'background-color: grey');
}
elementOpenEnd('td');
text(row[c].value);
elementClose('td');
}
e... | conditional_block |
settings.py | import os
import sys
HOSTNAME = os.environ.get('QLF_HOSTNAME', 'localhost')
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))
)
SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32))
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', HOSTNAME).split(',')
SITE_PAGES_DIRECTORY = os.path.join... | MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INSTALLED_APPS += (
'debug_toolbar',
) | conditional_block | |
settings.py | import os
import sys
HOSTNAME = os.environ.get('QLF_HOSTNAME', 'localhost')
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))
)
SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32))
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', HOSTNAME).split(',')
SITE_PAGES_DIRECTORY = os.path.join... | 'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'dashboard',
'channels',
'ui_channel',
'corsheaders',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf... | 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages', | random_line_split |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn main() {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compi... | fe::check_with_diag(&functions, &config).unwrap();
let end = PreciseTime::now();
if arguments.is_present("timings") {
println!("Frontend time: {}", start.to(end));
}
// TODO error hanlding
} | // run frontend
let start = PreciseTime::now();
let functions = fe::parse_with_diag(&inputs, &config).unwrap(); | random_line_split |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn main() | } else {
None
};
// list of input files
let inputs: Vec<_> = arguments.values_of("input").unwrap().map(Path::new).collect();
// run frontend
let start = PreciseTime::now();
let functions = fe::parse_with_diag(&inputs, &config).unwrap();
fe::check_with_diag(&functions, &config).... | {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compiler, it takes .gib files as input.")
.version("0.1")
.author("Alex Hirsch <W4RH4WK@bluephoenix.at>")
.arg(Arg::with_name("diagnostics")
.short("d")
.hel... | identifier_body |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn | () {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compiler, it takes .gib files as input.")
.version("0.1")
.author("Alex Hirsch <W4RH4WK@bluephoenix.at>")
.arg(Arg::with_name("diagnostics")
.short("d")
.... | main | identifier_name |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn main() {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compi... | ;
// list of input files
let inputs: Vec<_> = arguments.values_of("input").unwrap().map(Path::new).collect();
// run frontend
let start = PreciseTime::now();
let functions = fe::parse_with_diag(&inputs, &config).unwrap();
fe::check_with_diag(&functions, &config).unwrap();
let end = Precise... | {
None
} | conditional_block |
report.py | #!/usr/bin/env python
# Copyright (C) 2015 Swift Navigation Inc.
# Contact: Ian Horn <ian@swiftnav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WAR... | Returns
-------
printable
"""
pass | An object used to parametrize the SITL runs
| random_line_split |
report.py | #!/usr/bin/env python
# Copyright (C) 2015 Swift Navigation Inc.
# Contact: Ian Horn <ian@swiftnav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WAR... | (self, key, parents, dist_type=ms.DistType.IGNORE):
self.key = key
self.parents = parents
self.dist_type = dist_type
def report(self, data, analyses, folds, parameters):
"""
Generate a report from the data and analyses the Report depends on.
Parameters
----------
data : iterable
... | __init__ | identifier_name |
report.py | #!/usr/bin/env python
# Copyright (C) 2015 Swift Navigation Inc.
# Contact: Ian Horn <ian@swiftnav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WAR... | Generate a report from the data and analyses the Report depends on.
Parameters
----------
data : iterable
The data passed through the analyses
analyses : dict(str -> whatever)
A map from Analysis keys to the results of map and summary analyses.
folds : dict(str -> whatever)
A ... | """
A report to be generated from SITL data.
Parameters
----------
key : str
A key unique to each report used to identify it. (CANNOT BE EASILY CHECKED FOR UNIQUENESS)
parents : set(Analysis)
A set of Analysis objects on which the Report depends.
dist_type : DistType
The type of distribution to... | identifier_body |
poison.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Send + Reflect> fmt::Display for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl<T: Send + Reflect> Error for TryLockError<T> {
fn description(&self) -> &str {
match *self {
... | TryLockError::WouldBlock => "WouldBlock".fmt(f)
}
} | random_line_split |
poison.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Send + Reflect> fmt::Display for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl<T: Send + Reflect> Error for TryLockError<T> {
fn description(&self) -> &str {
match *self {... | {
match *self {
TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
TryLockError::WouldBlock => "WouldBlock".fmt(f)
}
} | identifier_body |
poison.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> &T { &self.guard }
/// Reaches into this error indicating that a lock is poisoned, returning a
/// mutable reference to the underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}
impl<T> From<PoisonError<T>> f... | get_ref | identifier_name |
distinctUntilChanged.js | import { Subscriber } from '../Subscriber';
import { tryCatch } from '../util/tryCatch';
import { errorObject } from '../util/errorObject';
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
*
*... | this.key = key;
this.destination.next(value);
}
}
}
//# sourceMappingURL=distinctUntilChanged.js.map | {
const keySelector = this.keySelector;
let key = value;
if (keySelector) {
key = tryCatch(this.keySelector)(value);
if (key === errorObject) {
return this.destination.error(errorObject.e);
}
}
let result = false;
if (th... | identifier_body |
distinctUntilChanged.js | import { Subscriber } from '../Subscriber';
import { tryCatch } from '../util/tryCatch';
import { errorObject } from '../util/errorObject';
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
*
*... | this.compare = compare;
this.keySelector = keySelector;
}
call(subscriber, source) {
return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*... | export function distinctUntilChanged(compare, keySelector) {
return (source) => source.lift(new DistinctUntilChangedOperator(compare, keySelector));
}
class DistinctUntilChangedOperator {
constructor(compare, keySelector) { | random_line_split |
distinctUntilChanged.js | import { Subscriber } from '../Subscriber';
import { tryCatch } from '../util/tryCatch';
import { errorObject } from '../util/errorObject';
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
*
*... |
}
let result = false;
if (this.hasKey) {
result = tryCatch(this.compare)(this.key, key);
if (result === errorObject) {
return this.destination.error(errorObject.e);
}
}
else {
this.hasKey = true;
}
i... | {
return this.destination.error(errorObject.e);
} | conditional_block |
distinctUntilChanged.js | import { Subscriber } from '../Subscriber';
import { tryCatch } from '../util/tryCatch';
import { errorObject } from '../util/errorObject';
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
*
*... | (destination, compare, keySelector) {
super(destination);
this.keySelector = keySelector;
this.hasKey = false;
if (typeof compare === 'function') {
this.compare = compare;
}
}
compare(x, y) {
return x === y;
}
_next(value) {
const keySe... | constructor | identifier_name |
lod.rs | //! Structs for keeping track of terrain level of detail.
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::ops::Add;
use block_position::BlockPosition;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// A strongly-typed index into various LOD-indexe... | (u32);
impl Add<u32> for OwnerId {
type Output = OwnerId;
fn add(self, rhs: u32) -> OwnerId {
let OwnerId(id) = self;
OwnerId(id + rhs)
}
}
struct BlockLoadState {
/// The LOD indexes requested by each owner of this block.
// TODO: Change this back to a HashMap once initial capacity is zero for tho... | OwnerId | identifier_name |
lod.rs | //! Structs for keeping track of terrain level of detail.
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::ops::Add;
use block_position::BlockPosition;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// A strongly-typed index into various LOD-indexe... | r()
};
if remove {
entry.remove();
}
r
},
}
}
}
/// A before and after LOD struct.
pub struct LODChange {
/// The target LOD.
pub desired: Option<LOD>,
/// Currently-loaded LOD
pub loaded: Option<LOD>,
}
/// These are used to identify the owner... | desired: Some(new_lod),
}),
)
}; | random_line_split |
MongoStorage.ts | import * as moment from 'moment';
import {MongoClient} from 'mongodb';
import {EventStorage} from './EventStorage';
import CalendarEvent from './CalendarEvent';
export default class MongoStorage implements EventStorage {
db: any;
collection: any;
async init(url: string = process.env.MONGO_URL) {
this.db = ... |
if (!end) {
delete query.start.$lte;
}
if (!start && !end) {
delete query.start;
}
const items = await this.collection.find(query, {
sort: [['start', 'asc']]
}).toArray();
return items.map(i => new CalendarEvent(i));
}
} | {
delete query.start.$gte;
} | conditional_block |
MongoStorage.ts | import * as moment from 'moment';
import {MongoClient} from 'mongodb';
import {EventStorage} from './EventStorage';
import CalendarEvent from './CalendarEvent';
export default class MongoStorage implements EventStorage {
db: any;
collection: any;
async | (url: string = process.env.MONGO_URL) {
this.db = await MongoClient.connect(url);
this.collection = this.db.collection('events');
}
create(event: CalendarEvent) {
return this.collection.insertOne(event.data);
}
update(eventId: string, event: CalendarEvent) {
return this.collection.updateOne(
... | init | identifier_name |
MongoStorage.ts | import * as moment from 'moment';
import {MongoClient} from 'mongodb';
import {EventStorage} from './EventStorage';
import CalendarEvent from './CalendarEvent';
export default class MongoStorage implements EventStorage {
db: any;
collection: any;
async init(url: string = process.env.MONGO_URL) {
this.db = ... | delete query.start;
}
const items = await this.collection.find(query, {
sort: [['start', 'asc']]
}).toArray();
return items.map(i => new CalendarEvent(i));
}
} | if (!end) {
delete query.start.$lte;
}
if (!start && !end) { | random_line_split |
MongoStorage.ts | import * as moment from 'moment';
import {MongoClient} from 'mongodb';
import {EventStorage} from './EventStorage';
import CalendarEvent from './CalendarEvent';
export default class MongoStorage implements EventStorage {
db: any;
collection: any;
async init(url: string = process.env.MONGO_URL) {
this.db = ... |
async findOne(eventId) {
const event = await this.collection.findOne({googleId: eventId});
if (event) {
return new CalendarEvent(event);
}
return null;
}
async find(calendarId, start, end) {
const query = {
calendarGoogleId: calendarId,
cancelled: false,
start: {$gte... | {
return this.collection.updateOne(
{googleId: eventId},
event.data
);
} | identifier_body |
params.rs | Pricer, GasPriceCalibratorOptions};
use user_defaults::UserDefaults;
#[derive(Debug, PartialEq)]
pub enum SpecType {
Mainnet,
Testnet,
Ropsten,
Olympic,
Classic,
Expanse,
Dev,
Custom(String),
}
impl Default for SpecType {
fn | () -> Self {
SpecType::Mainnet
}
}
impl str::FromStr for SpecType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let spec = match s {
"frontier" | "homestead" | "mainnet" => SpecType::Mainnet,
"frontier-dogmatic" | "homestead-dogmatic" | "classic" => SpecType::Classic,
"morden"... | default | identifier_name |
params.rs | ricer, GasPriceCalibratorOptions};
use user_defaults::UserDefaults;
#[derive(Debug, PartialEq)]
pub enum SpecType {
Mainnet,
Testnet,
Ropsten,
Olympic,
Classic,
Expanse,
Dev,
Custom(String),
}
impl Default for SpecType {
fn default() -> Self {
SpecType::Mainnet
}
}
impl str::FromStr for SpecType {
type ... |
}
}
}
#[derive(Debug, PartialEq)]
pub struct MinerExtras {
pub author: Address,
pub extra_data: Vec<u8>,
pub gas_floor_target: U256,
pub gas_ceil_target: U256,
pub transactions_limit: usize,
}
impl Default for MinerExtras {
fn default() -> Self {
MinerExtras {
author: Default::default(),
extra_data:... | {
GasPricer::new_calibrated(GasPriceCalibratorOptions {
usd_per_tx: usd_per_tx,
recalibration_period: recalibration_period,
})
} | conditional_block |
params.rs | <Spec, String> {
match *self {
SpecType::Mainnet => Ok(ethereum::new_frontier()),
SpecType::Testnet => Ok(ethereum::new_morden()),
SpecType::Ropsten => Ok(ethereum::new_ropsten()),
SpecType::Olympic => Ok(ethereum::new_olympic()),
SpecType::Classic => Ok(ethereum::new_classic()),
SpecType::Expanse =... | {
assert_eq!(Switch::default(), Switch::Auto);
} | identifier_body | |
params.rs | Pricer, GasPriceCalibratorOptions};
use user_defaults::UserDefaults;
#[derive(Debug, PartialEq)]
pub enum SpecType {
Mainnet,
Testnet,
Ropsten,
Olympic,
Classic,
Expanse,
Dev,
Custom(String),
}
impl Default for SpecType {
fn default() -> Self {
SpecType::Mainnet
}
}
impl str::FromStr for SpecType {
type... | author: Default::default(),
extra_data: version_data(),
gas_floor_target: U256::from(4_700_000),
gas_ceil_target: U256::from(6_283_184),
transactions_limit: 1024,
}
}
}
/// 3-value enum.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Switch {
/// True.
On,
/// False.
Off,
/// Auto.
Auto,
}
... | fn default() -> Self {
MinerExtras { | random_line_split |
groomer.js | /**
* Interactive Linter Copyright (c) 2015 Miguel Castillo.
*
* Licensed under MIT
*/
define(function (/*require, exports, module*/) {
"use strict";
function getType(message) {
return (message.fatal || message.severity === 2) ? "error" : "warning";
}
/**
* Generates codemirror toke... | (message /*, settings*/) {
message.type = getType(message);
message.evidence = "[" + message.ruleId + "] - " + message.source;
message.token = {
start: {
line: (message.line - 1),
ch: (message.column - 1)
},
end: {
... | groom | identifier_name |
groomer.js | /**
* Interactive Linter Copyright (c) 2015 Miguel Castillo.
*
* Licensed under MIT
*/
define(function (/*require, exports, module*/) {
"use strict";
function getType(message) {
return (message.fatal || message.severity === 2) ? "error" : "warning";
}
/**
* Generates codemirror toke... |
return {
groom: groom
};
});
| {
message.type = getType(message);
message.evidence = "[" + message.ruleId + "] - " + message.source;
message.token = {
start: {
line: (message.line - 1),
ch: (message.column - 1)
},
end: {
line: (message.... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.