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 |
|---|---|---|---|---|
transmute_int_to_float.rs | use super::TRANSMUTE_INT_TO_FLOAT;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
/// Checks for `transmute_int_to_float` lint.
/// Returns `true` if it's triggered, otherwis... | "consider using",
format!("{}::from_bits({})", to_ty, arg.to_string()),
Applicability::Unspecified,
);
},
);
true
},
_ => false,
}
}
| {
match (&from_ty.kind(), &to_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => {
span_lint_and_then(
cx,
TRANSMUTE_INT_TO_FLOAT,
e.span,
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
... | identifier_body |
transmute_int_to_float.rs | use super::TRANSMUTE_INT_TO_FLOAT;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
/// Checks for `transmute_int_to_float` lint.
/// Returns `true` if it's triggered, otherwis... | <'tcx>(
cx: &LateContext<'tcx>,
e: &'tcx Expr<'_>,
from_ty: Ty<'tcx>,
to_ty: Ty<'tcx>,
args: &'tcx [Expr<'_>],
const_context: bool,
) -> bool {
match (&from_ty.kind(), &to_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => {
span_lint_and_then(
... | check | identifier_name |
trace_time.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ctypes
import ctypes.util
import logging
import os
import platform
import sys
import time
import threading
GET_TICK_COUNT_LAST_NOW = 0
# If GET_TICK... | logging.exception('Error when determining if QPC is usable.')
return False
return True
def InitializeWinNowFunction(plat):
"""Sets a monotonic clock for windows platforms.
Args:
plat: Platform that is being run on.
"""
global _CLOCK # pylint: disable=global-statement
global _NOW_FUNCTIO... | """Determines if system can query the performance counter.
The performance counter is a high resolution timer on windows systems.
Some chipsets have unreliable performance counters, so this checks that one
of those chipsets is not present.
Returns:
True if QPC is useable, false otherwise.
"""
... | identifier_body |
trace_time.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ctypes
import ctypes.util
import logging
import os
import platform
import sys
import time
import threading
GET_TICK_COUNT_LAST_NOW = 0
# If GET_TICK... |
Args:
plat: Platform that is being run on. Unused in GetMacNowFunction. Passed
for consistency between initilaizers.
"""
del plat # Unused
global _CLOCK # pylint: disable=global-statement
global _NOW_FUNCTION # pylint: disable=global-statement
_CLOCK = _MAC_CLOCK
libc = ctypes.CDLL('/u... | def InitializeMacNowFunction(plat):
"""Sets a monotonic clock for the Mac platform. | random_line_split |
trace_time.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ctypes
import ctypes.util
import logging
import os
import platform
import sys
import time
import threading
GET_TICK_COUNT_LAST_NOW = 0
# If GET_TICK... |
else:
_CLOCK = _WIN_LORES
kernel32 = (ctypes.cdll.kernel32
if plat.startswith(_PLATFORMS['cygwin'])
else ctypes.windll.kernel32)
get_tick_count_64 = getattr(kernel32, 'GetTickCount64', None)
# Windows Vista or newer
if get_tick_count_64:
get_tick_count_64.r... | _CLOCK = _WIN_HIRES
qpc_return = ctypes.c_int64()
qpc_frequency = ctypes.c_int64()
ctypes.windll.Kernel32.QueryPerformanceFrequency(
ctypes.byref(qpc_frequency))
qpc_frequency = float(qpc_frequency.value)
qpc = ctypes.windll.Kernel32.QueryPerformanceCounter
def WinNowFunctionImpl():
... | conditional_block |
trace_time.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ctypes
import ctypes.util
import logging
import os
import platform
import sys
import time
import threading
GET_TICK_COUNT_LAST_NOW = 0
# If GET_TICK... | (plat):
"""Sets a monotonic clock for windows platforms.
Args:
plat: Platform that is being run on.
"""
global _CLOCK # pylint: disable=global-statement
global _NOW_FUNCTION # pylint: disable=global-statement
if IsQPCUsable():
_CLOCK = _WIN_HIRES
qpc_return = ctypes.c_int64()
qpc_fre... | InitializeWinNowFunction | identifier_name |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx... | "c:a",
"aac",
"-b:a",
"160000",
"-ac",
"2",
"s",
"854x480",
"-c:v",
"libx264",
"-b:v",
"800000",
"-hls_time",
"10",
"-hls_list_size",
... | format!("{}", input_address).as_str(),
"-y", | random_line_split |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx... |
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("o", "", "set output file name", "NAME");
opts.optopt("i", "", "set input file name", "NAME");
opts.optflag("h", "help", "print this help menu");
let match... | {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
} | identifier_body |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx... | (program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("o", "", "set output file name", "... | print_usage | identifier_name |
main.rs | extern crate ffmpeg_next as ffmpeg;
extern crate pretty_env_logger;
use std::env;
use std::process::Command;
use std::thread;
use std::time;
use futures::{FutureExt, StreamExt};
use http::Uri;
use warp::Filter;
use getopts::Options;
//ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx... |
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if !matches.opt_str("o").is_some() || !matches.opt_str("i").is_some() {
print_usage(&program, opts);
return;
}
let input = matches.opt_str("i").expect("Expected input file");
let output... | {
panic!(f.to_string())
} | conditional_block |
menuShortcuts.py | # coding=utf-8
from qtpy import QtWidgets
class MenuShortcuts(QtWidgets.QWidget):
"""
Window displaying the application shortcuts
"""
def __init__(self):
| QtWidgets.QWidget.__init__(self)
self.setWindowTitle('Shortcuts')
l = QtWidgets.QGridLayout()
self.setLayout(l)
lk = QtWidgets.QLabel('<b>Key</b>')
ld = QtWidgets.QLabel('<b>Description</b>')
l.addWidget(lk, 0, 0)
l.addWidget(ld, 0, 1)
... | random_line_split | |
menuShortcuts.py | # coding=utf-8
from qtpy import QtWidgets
class MenuShortcuts(QtWidgets.QWidget):
"""
Window displaying the application shortcuts
"""
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setWindowTitle('Shortcuts')
l = QtWidgets.QGridLayout()
self.s... | lk = QtWidgets.QLabel(key)
ld = QtWidgets.QLabel(description)
l = self.layout()
l.addWidget(lk, self._r, 0)
l.addWidget(ld, self._r, 1)
self._r += 1 | identifier_body | |
menuShortcuts.py | # coding=utf-8
from qtpy import QtWidgets
class | (QtWidgets.QWidget):
"""
Window displaying the application shortcuts
"""
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setWindowTitle('Shortcuts')
l = QtWidgets.QGridLayout()
self.setLayout(l)
lk = QtWidgets.QLabel('<b>Key</b>')
l... | MenuShortcuts | identifier_name |
minicurl.py | #!/usr/bin/python
import sys
import urlparse
import os
import requests
def chunkedFetchUrl(url, local_filename=None, **kwargs):
|
url=sys.argv[1]
parsed=urlparse.urlparse(url)
(h,t) = os.path.split(parsed.path)
t = t or 'index.html'
bits = parsed.netloc.split('.')
if len(bits)==3:
d=bits[1]
elif len(bits)==2:
d=bits[0]
else:
d=parsed.netloc
full=os.path.join(d,h[1:])
try:
os.makedirs(full)
except Exception as e:
print >> sys... | """Adapted from http://stackoverflow.com/q/16694907"""
if not local_filename:
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter
r = requests.get(url, stream=True, **kwargs)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
... | identifier_body |
minicurl.py | #!/usr/bin/python
import sys
import urlparse
import os
import requests
def chunkedFetchUrl(url, local_filename=None, **kwargs):
"""Adapted from http://stackoverflow.com/q/16694907"""
if not local_filename:
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter
r = requests.get(u... |
return local_filename
url=sys.argv[1]
parsed=urlparse.urlparse(url)
(h,t) = os.path.split(parsed.path)
t = t or 'index.html'
bits = parsed.netloc.split('.')
if len(bits)==3:
d=bits[1]
elif len(bits)==2:
d=bits[0]
else:
d=parsed.netloc
full=os.path.join(d,h[1:])
try:
os.makedirs(full)
except Except... | if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush() | conditional_block |
minicurl.py | #!/usr/bin/python
import sys
import urlparse
import os
import requests
def | (url, local_filename=None, **kwargs):
"""Adapted from http://stackoverflow.com/q/16694907"""
if not local_filename:
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter
r = requests.get(url, stream=True, **kwargs)
with open(local_filename, 'wb') as f:
for chunk in r.i... | chunkedFetchUrl | identifier_name |
minicurl.py | #!/usr/bin/python
import sys
import urlparse
import os
import requests
def chunkedFetchUrl(url, local_filename=None, **kwargs):
"""Adapted from http://stackoverflow.com/q/16694907"""
if not local_filename:
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter
r = requests.get(u... | f.flush()
return local_filename
url=sys.argv[1]
parsed=urlparse.urlparse(url)
(h,t) = os.path.split(parsed.path)
t = t or 'index.html'
bits = parsed.netloc.split('.')
if len(bits)==3:
d=bits[1]
elif len(bits)==2:
d=bits[0]
else:
d=parsed.netloc
full=os.path.join(d,h[1:])
try:
os.mak... | if chunk: # filter out keep-alive new chunks
f.write(chunk) | random_line_split |
upload_latest.rs | use crate::{api_client::{self,
Client},
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
use habitat_core::{crypto::keys::{Key,
... | {
Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?,
Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => {
ui.status(Status::Using,
format!("public key revision {} which already exists in the depot",
public_ke... | {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?;
ui.begin(format!("Uploading latest public origin key {}", &origin))?;
// Figure out the latest public key
let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?;
// The path to the key in the c... | identifier_body |
upload_latest.rs | use crate::{api_client::{self,
Client},
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
use habitat_core::{crypto::keys::{Key,
... | (ui: &mut UI,
bldr_url: &str,
token: &str,
origin: &Origin,
with_secret: bool,
key_cache: &KeyCache)
-> Result<()> {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?;
ui.begin(format!... | start | identifier_name |
upload_latest.rs | use crate::{api_client::{self,
Client},
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result}, | PRODUCT,
VERSION};
use habitat_core::{crypto::keys::{Key,
KeyCache,
PublicOriginSigningKey,
SecretOriginSigningKey},
origin::Origin};
use reqwest::StatusCode;
pub async fn st... | random_line_split | |
models.py | from __future__ import absolute_import, unicode_literals
from six import text_type
from django.db import models
from django.db.models.query import QuerySet
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.text import slugify
from django.utils.translatio... |
def __str__(self):
return self.title
| from .forms import VoteForm
return VoteForm(self) | identifier_body |
models.py | from __future__ import absolute_import, unicode_literals
from six import text_type
from django.db import models
from django.db.models.query import QuerySet
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.text import slugify
from django.utils.translatio... | :
verbose_name = _('poll')
verbose_name_plural = _('polls')
panels = [
FieldPanel('title'),
InlinePanel('questions', label=_('Questions'), min_num=1)
]
search_fields = (
index.SearchField('title', partial_match=True, boost=5),
index.SearchField('id', boost=1... | Meta | identifier_name |
models.py | from __future__ import absolute_import, unicode_literals
from six import text_type
from django.db import models
from django.db.models.query import QuerySet
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.text import slugify
from django.utils.translatio... | )
objects = PollQuerySet.as_manager()
def get_nice_url(self):
return slugify(text_type(self))
def get_template(self, request):
try:
return self.template
except AttributeError:
return '{0}/{1}.html'.format(self._meta.app_label, self._meta.model_name)
... | search_fields = (
index.SearchField('title', partial_match=True, boost=5),
index.SearchField('id', boost=10), | random_line_split |
leaflet-tilelayer-cordova.js | ' parameter here to initialize()
// offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png
// tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates
var myself = this;
myself._url_online = mysel... |
goOnline: function () {
// use this layer in online mode
this.setUrl( this._url_online );
},
goOffline: function () {
// use this layer in online mode
this.setUrl( this._url_offline );
},
/*
* Returns current online/offline state.
*/
isOnline: function() {
r... | * essentially this just calls setURL() with either the ._url_online or ._url_offline, and lets L.TileLayer reload the tiles... or try, anyway
*/ | random_line_split |
leaflet-tilelayer-cordova.js | parameter here to initialize()
// offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png
// tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates
var myself = this;
myself._url_online = myself... | () {
// the download was skipped and not an error, so call the progress callback; then either move on to the next one, or else call our success callback
// if the progress callback returns false (not null, not undefiend... false) then do not proceed to the next tile; this allows cancella... | doneWithIt | identifier_name |
leaflet-tilelayer-cordova.js | filesystem activity starts.
if (! window.requestFileSystem && this.options.debug) console.log("L.TileLayer.Cordova: device does not support requestFileSystem");
if (! window.requestFileSystem) throw "L.TileLayer.Cordova: device does not support requestFileSystem";
if (myself.options.debug) cons... | {
// the download was skipped and not an error, so call the progress callback; then either move on to the next one, or else call our success callback
// if the progress callback returns false (not null, not undefiend... false) then do not proceed to the next tile; this allows cancellatio... | identifier_body | |
leaflet-tilelayer-cordova.js | parameter here to initialize()
// offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png
// tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates
var myself = this;
myself._url_online = myself... |
// done!
return xyzlist;
},
calculateXYZListFromBounds: function(bounds, zmin, zmax) {
// Given a bounds (such as that obtained by calling MAP.getBounds()) and a range of zoom levels, returns the list of XYZ trios comprising that view.
// The caller may then call downloadXYZList() with progr... | {
var t_x = this.getX(lon, z);
var t_y = this.getY(lat, z);
var radius = z==zmin ? 0 : Math.pow(2 , z - zmin - 1);
if (this.options.debug) console.log("Calculate pyramid: Z " + z + " : " + "Radius of " + radius );
for (var x=t_x-radius; x<=t_x+radius; x++) {... | conditional_block |
Branch.js | var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) {
this.gid = Math.round(Math.random() * maxSegments);
this.topPoint = origin;
this.radius = baseRadius;
this.maxSegments = maxSegments;
this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.gene... | (dimension) {
return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght);
}
//calculate segment lenght for new segment
thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim;
if (thisBranch.lenghtSubbranch !== 0 && this... | newPos | identifier_name |
Branch.js | var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) {
this.gid = Math.round(Math.random() * maxSegments);
this.topPoint = origin;
this.radius = baseRadius;
this.maxSegments = maxSegments;
this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.gene... |
};
| {
return true;
} | conditional_block |
Branch.js | var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) {
this.gid = Math.round(Math.random() * maxSegments);
this.topPoint = origin;
this.radius = baseRadius;
this.maxSegments = maxSegments;
this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.gene... |
//calculate segment lenght for new segment
thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim;
if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) {
thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius... | {
return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght);
} | identifier_body |
Branch.js | var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) {
this.gid = Math.round(Math.random() * maxSegments);
this.topPoint = origin;
this.radius = baseRadius;
this.maxSegments = maxSegments;
this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.gene... | }
var destination = new THREE.Vector3(newX, newY, newZ);
var lcurve = new THREE.LineCurve3(this.topPoint, destination);
var geometry = new THREE.TubeGeometry(
lcurve, //path
thisBranch.tree.genes.segmentLenght, //segments
thisBranch.radius, //radius
8, //radiusSegments
true //o... | random_line_split | |
pypi_cache_server.py | '''
Pypi cache server
Original author: Victor-mortal
'''
import os
import httplib
import urlparse
import logging
import locale
import json
import hashlib
import webob
import gevent
from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey
CACHE_DIR = '.cache'
wsgi = wsgi_fast # comment to use pywsgi
host = '0.0.0... | (self, chunkSize=4096, timeout=60, dropHeaders=['transfer-encoding'], pypiHost=None, log=None):
"""
@param log: logger of logging library
"""
self.log = log
if self.log is None:
self.log = logging.getLogger('proxy')
self.chunkSize = chunkSize
self.tim... | __init__ | identifier_name |
pypi_cache_server.py | '''
Pypi cache server
Original author: Victor-mortal
'''
import os
import httplib
import urlparse
import logging
import locale
import json
import hashlib
import webob
import gevent
from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey
CACHE_DIR = '.cache'
wsgi = wsgi_fast # comment to use pywsgi
host = '0.0.0... |
self.log.debug('Request from %s to %s', req.remote_addr, path)
url = path
conn = httplib.HTTPConnection(self.pypiHost, timeout=self.timeout)
#headers['X-Forwarded-For'] = req.remote_addr
#headers['X-Real-IP'] = req.remote_addr
try:
conn.request(req.method,... | o = json.load( open(cache_file+'.js', 'rb') )
start_response(o['response'], o['headers'])
return self.yieldData( open(cache_file) ) | conditional_block |
pypi_cache_server.py | '''
Pypi cache server
Original author: Victor-mortal
'''
import os
import httplib
import urlparse
import logging
import locale
import json
import hashlib
import webob
import gevent
from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey
CACHE_DIR = '.cache'
wsgi = wsgi_fast # comment to use pywsgi
host = '0.0.0... | def _rewrite(self, req, start_response):
path = req.path_info
if req.query_string:
path += '?' + req.query_string
parts = urlparse.urlparse(path)
headers = req.headers
md = hashlib.md5()
md.update(' '.join('%s:%s'%v for v in headers.iteritems()))
... | if cache_file:
cache_file.close()
| random_line_split |
pypi_cache_server.py | '''
Pypi cache server
Original author: Victor-mortal
'''
import os
import httplib
import urlparse
import logging
import locale
import json
import hashlib
import webob
import gevent
from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey
CACHE_DIR = '.cache'
wsgi = wsgi_fast # comment to use pywsgi
host = '0.0.0... | #headers['X-Forwarded-For'] = req.remote_addr
#headers['X-Real-IP'] = req.remote_addr
try:
conn.request(req.method, url, headers=headers, body=req.body)
response = conn.getresponse()
except Exception, e:
msg = str(e)
if os.name == 'nt':
... | path = req.path_info
if req.query_string:
path += '?' + req.query_string
parts = urlparse.urlparse(path)
headers = req.headers
md = hashlib.md5()
md.update(' '.join('%s:%s'%v for v in headers.iteritems()))
md.update(path)
cache_file = os.path.join(CA... | identifier_body |
IR_dec_comb.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 22 07:54:05 2014
@author: charleslelosq
Carnegie Institution for Science
"""
import sys
sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/")
import csv
import numpy as np
import scipy
import matplotlib
import matplotlib.gridspec as gridspec
from pylab ... | return (model - data)/eps
##### CORE OF THE CALCULATION BELOW
#### CALLING THE DATA NAMES
tkMessageBox.showinfo(
"Open file",
"Please open the list of spectra")
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "... | a1 = pars['a1'].value
a2 = pars['a2'].value
f1 = pars['f1'].value
f2 = pars['f2'].value
l1 = pars['l1'].value
l2 = pars['l2'].value
# Gaussian model
peak1 = gaussian(x,a1,f1,l1)
peak2 = gaussian(x,a2,f2,l2)
model = peak1 + peak2
if data is No... | identifier_body |
IR_dec_comb.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 22 07:54:05 2014
@author: charleslelosq
Carnegie Institution for Science
"""
import sys
sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/")
import csv
import numpy as np
import scipy
import matplotlib
import matplotlib.gridspec as gridspec
from pylab ... | # (Name, Value, Vary, Min, Max, Expr)
params.add_many(('a1', 1, True, 0, None, None),
('f1', 5200, True, 750, None, None),
('l1', 1, True, 0, None, None),
('a2', 1, True, 0, None, None),
... | name = str(results[lg]).strip('[]')
name = name[1:-1] # to remove unwanted ""
sample = np.genfromtxt(name) # get the sample to deconvolute
# we set here the lower and higher bonds for the interest region
lb = 4700 ### MAY NEED TO AJUST THAT
hb = 6000
interestspectra = sample[np.where((samp... | conditional_block |
IR_dec_comb.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 22 07:54:05 2014
@author: charleslelosq
Carnegie Institution for Science
"""
import sys
sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/")
import csv
import numpy as np
import scipy
import matplotlib
import matplotlib.gridspec as gridspec
from pylab ... | interestspectra[:,1] = interestspectra[:,1]/np.amax(interestspectra[:,1])*100 # normalise spectra to maximum, easier to handle after
sigma = abs(ese0*interestspectra[:,1]) #calculate good ese
#sigma = None # you can activate that if you are not sure about the errors
xfit = interestspectra[:,0] # regio... | ese0 = interestspectra[:,2]/abs(interestspectra[:,1]) #take ese as a percentage, we assume that the treatment was made correctly for error determination... if not, please put sigma = None | random_line_split |
IR_dec_comb.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 22 07:54:05 2014
@author: charleslelosq
Carnegie Institution for Science
"""
import sys
sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/")
import csv
import numpy as np
import scipy
import matplotlib
import matplotlib.gridspec as gridspec
from pylab ... | (pars, x, data=None, eps=None):
# unpack parameters:
# extract .value attribute for each parameter
a1 = pars['a1'].value
a2 = pars['a2'].value
f1 = pars['f1'].value
f2 = pars['f2'].value
l1 = pars['l1'].value
l2 = pars['l2'].value
# Gaussian model
peak1 =... | residual | identifier_name |
mod.rs | pub mod buffers;
pub mod cursor;
pub mod position;
pub mod movement;
pub mod insert;
use gfx::Screen;
use config::Players;
use px8::PX8Config;
use px8::editor::State;
use self::buffers::BufferManager;
use self::cursor::Cursor;
use px8::editor::text::buffers::TextBuffer;
use px8::editor::text::buffers::SplitBuffer;
u... | else { c };
let pos_char_x = 4 * (x - scroll_x) as i32;
let pos_char_y = 8 * (y - scroll_y) as i32;
//info!("OFF C {:?} X {:?} {:?}", c, pos_char_x, pos_char_y);
screen.print_char(c,
pos_char_x,
... | { ' ' } | conditional_block |
mod.rs | pub mod buffers;
pub mod cursor;
pub mod position;
pub mod movement;
pub mod insert;
use gfx::Screen;
use config::Players;
use px8::PX8Config;
use px8::editor::State;
use self::buffers::BufferManager;
use self::cursor::Cursor;
use px8::editor::text::buffers::TextBuffer;
use px8::editor::text::buffers::SplitBuffer;
u... | let y = self.cursor().y;
self.buffers.current_buffer_mut().focus_hint_y(y);
self.buffers.current_buffer_mut().focus_hint_x(x);
}
pub fn draw(&mut self, players: Arc<Mutex<Players>>, screen: &mut Screen) {
let (scroll_x, scroll_y) = {
let current_buffer = self.buffer... |
let x = self.cursor().x; | random_line_split |
mod.rs | pub mod buffers;
pub mod cursor;
pub mod position;
pub mod movement;
pub mod insert;
use gfx::Screen;
use config::Players;
use px8::PX8Config;
use px8::editor::State;
use self::buffers::BufferManager;
use self::cursor::Cursor;
use px8::editor::text::buffers::TextBuffer;
use px8::editor::text::buffers::SplitBuffer;
u... | (&mut self, config: Arc<Mutex<PX8Config>>, screen: &mut Screen, filename: String, code: String) {
info!("[GFX_EDITOR] Init");
info!("[GFX_EDITOR] {:?}", self.pos());
let mut new_buffer: Buffer = SplitBuffer::from_str(&code).into();
new_buffer.title = Some(filename);
let new_bu... | init | identifier_name |
json.js | dojo.provide("tests._base.json"); | [
//Not testing dojo.toJson() on its own since Rhino will output the object properties in a different order.
//Still valid json, but just in a different order than the source string.
// take a json-compatible object, convert it to a json string, then put it back into json.
function toAndFromJson(t){
var te... |
tests.register("tests._base.json", | random_line_split |
iconWarning.tsx | import React from 'react';
import SvgIcon from './svgIcon';
type Props = React.ComponentProps<typeof SvgIcon>;
| return (
<SvgIcon {...props} ref={ref}>
<path d="M13.87,15.26H2.13A2.1,2.1,0,0,1,0,13.16a2.07,2.07,0,0,1,.27-1L6.17,1.8a2.1,2.1,0,0,1,1.27-1,2.11,2.11,0,0,1,2.39,1L15.7,12.11a2.1,2.1,0,0,1-1.83,3.15ZM8,2.24a.44.44,0,0,0-.16,0,.58.58,0,0,0-.37.28L1.61,12.86a.52.52,0,0,0-.08.3.6.6,0,0,0,.6.6H13.87a.54.54,0,0,... | const IconWarning = React.forwardRef(function IconWarning(
props: Props,
ref: React.Ref<SVGSVGElement>
) { | random_line_split |
Status.js | 'use strict';
var util = require('util');
var Promise = require('bluebird');
var uuid = require('../../utils/uuid');
var errors = require('../../errors');
var EmbeddedModel = require('../../EmbeddedModel');
// Schema Validator
// ----------------
var validator = require('jjv')();
vali... |
// EmbeddedModel Configuration
// ---------------------------
Status.key = 'statuses';
Status.collections = {};
Status.validate = function(data) {
return validator.validate('http://www.gandhi.io/schema/cycle#/definitions/status', data, {useDefault: true, removeAdditional: true});
};
Status.create = function(conn, ... | {
return EmbeddedModel.call(this, conn, data, parent)
.then(function(self) {
// check authorizations
if(!self.parent.authorizations['cycle/statuses:read'])
return Promise.reject(new errors.ForbiddenError());
// cycle_id
self.cycle_id = self.parent.id;
return self;
});
} | identifier_body |
Status.js | 'use strict';
var util = require('util');
var Promise = require('bluebird');
var uuid = require('../../utils/uuid');
var errors = require('../../errors');
var EmbeddedModel = require('../../EmbeddedModel');
// Schema Validator
// ----------------
var validator = require('jjv')();
vali... | };
module.exports = Status; |
if(!self.parent.authorizations['cycle/statuses:write'])
return Promise.reject(new errors.ForbiddenError());
return EmbeddedModel.prototype.delete.call(self, conn); | random_line_split |
Status.js | 'use strict';
var util = require('util');
var Promise = require('bluebird');
var uuid = require('../../utils/uuid');
var errors = require('../../errors');
var EmbeddedModel = require('../../EmbeddedModel');
// Schema Validator
// ----------------
var validator = require('jjv')();
vali... | (conn, data, parent) {
return EmbeddedModel.call(this, conn, data, parent)
.then(function(self) {
// check authorizations
if(!self.parent.authorizations['cycle/statuses:read'])
return Promise.reject(new errors.ForbiddenError());
// cycle_id
self.cycle_id = self.parent.id;
return self;
});
}
// Emb... | Status | identifier_name |
macros.rs |
/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
/// On panic, this macro will print the values of the expressions.
///
/// # Example
///
/// ```
/// let a = 3i;
/// let b = 1i + 2i;
/// assert_eq!(a, b);
/// ```
#[macro_export]
macro_rules! assert_eq(
($given:... | ) | random_line_split | |
tutils.py | from io import BytesIO
import tempfile
import os
import time
import shutil
from contextlib import contextmanager
import six
import sys
from netlib import utils, tcp, http
def treader(bytes):
"""
Construct a tcp.Read object from bytes.
"""
fp = BytesIO(bytes)
return tcp.Reader(fp)
@contextma... | _check_exception(expected_exception, actual, sys.exc_info()[2])
else:
raise AssertionError("No exception raised. Return value: {}".format(ret))
class RaisesContext(object):
def __init__(self, expected_exception):
self.expected_exception = expected_exception
def __ente... | """
Assert that a callable raises a specified exception.
:exc An exception class or a string. If a class, assert that an
exception of this type is raised. If a string, assert that the string
occurs in the string representation of the exception, based on a
case-insenstivie match.... | identifier_body |
tutils.py | from io import BytesIO
import tempfile
import os
import time
import shutil
from contextlib import contextmanager
import six
import sys
from netlib import utils, tcp, http
def treader(bytes): | """
fp = BytesIO(bytes)
return tcp.Reader(fp)
@contextmanager
def tmpdir(*args, **kwargs):
orig_workdir = os.getcwd()
temp_workdir = tempfile.mkdtemp(*args, **kwargs)
os.chdir(temp_workdir)
yield temp_workdir
os.chdir(orig_workdir)
shutil.rmtree(temp_workdir)
def _check_excepti... | """
Construct a tcp.Read object from bytes. | random_line_split |
tutils.py | from io import BytesIO
import tempfile
import os
import time
import shutil
from contextlib import contextmanager
import six
import sys
from netlib import utils, tcp, http
def treader(bytes):
"""
Construct a tcp.Read object from bytes.
"""
fp = BytesIO(bytes)
return tcp.Reader(fp)
@contextma... | (self):
return
def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_type:
raise AssertionError("No exception raised.")
else:
_check_exception(self.expected_exception, exc_val, exc_tb)
return True
test_data = utils.Data(__name__)
# FIXME: Temporary work... | __enter__ | identifier_name |
tutils.py | from io import BytesIO
import tempfile
import os
import time
import shutil
from contextlib import contextmanager
import six
import sys
from netlib import utils, tcp, http
def treader(bytes):
"""
Construct a tcp.Read object from bytes.
"""
fp = BytesIO(bytes)
return tcp.Reader(fp)
@contextma... |
else:
if not isinstance(actual, expected):
six.reraise(AssertionError, AssertionError(
"Expected %s, but caught %s %s" % (
expected.__name__, actual.__class__.__name__, repr(actual)
)
), exc_tb)
def raises(expected_exception, obj... | if expected.lower() not in str(actual).lower():
six.reraise(AssertionError, AssertionError(
"Expected %s, but caught %s" % (
repr(expected), repr(actual)
)
), exc_tb) | conditional_block |
lib.es6.set.d.ts | /*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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.... |
interface SetConstructor {
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
prototype: Set<any>;
}
declare var Set: SetConstructor; | random_line_split | |
issue-3753.rs | // run-pass
// Issue #3656
// Issue Name: pub method preceded by attribute can't be parsed
// Abstract: Visibility parsing failed when compiler parsing
use std::f64;
#[derive(Copy, Clone)]
pub struct Point {
x: f64,
y: f64
}
#[derive(Copy, Clone)]
pub enum | {
Circle(Point, f64),
Rectangle(Point, Point)
}
impl Shape {
pub fn area(&self, sh: Shape) -> f64 {
match sh {
Shape::Circle(_, size) => f64::consts::PI * size * size,
Shape::Rectangle(Point {x, y}, Point {x: x2, y: y2}) => (x2 - x) * (y2 - y)
}
}
}
pub fn main... | Shape | identifier_name |
issue-3753.rs | // run-pass
// Issue #3656
// Issue Name: pub method preceded by attribute can't be parsed
// Abstract: Visibility parsing failed when compiler parsing
use std::f64;
#[derive(Copy, Clone)] | pub struct Point {
x: f64,
y: f64
}
#[derive(Copy, Clone)]
pub enum Shape {
Circle(Point, f64),
Rectangle(Point, Point)
}
impl Shape {
pub fn area(&self, sh: Shape) -> f64 {
match sh {
Shape::Circle(_, size) => f64::consts::PI * size * size,
Shape::Rectangle(Point {... | random_line_split | |
PieChart.js | import SVG from './SVG';
import Radium from 'radium';
import { layout, svg } from 'd3';
import { Spring } from 'react-motion';
import { Component, PropTypes } from 'react';
export default class PieChart extends Component {
static defaultProps = {
data: PropTypes.array.isRequired,
width: PropTypes.number.isRe... |
state = { ...[...Array(this.props.data.length)].map(() => false) }
onMouseOver = (i) => () => this.setState({ [i]: true })
onMouseOut = (i) => () => this.setState({ [i]: false })
render() {
const { innerRadius, outerRadius, width, height } = this.props;
const pie = layout.pie().padAngle(.02);
co... | } | random_line_split |
PieChart.js | import SVG from './SVG';
import Radium from 'radium';
import { layout, svg } from 'd3';
import { Spring } from 'react-motion';
import { Component, PropTypes } from 'react';
export default class PieChart extends Component {
static defaultProps = {
data: PropTypes.array.isRequired,
width: PropTypes.number.isRe... |
}
| {
return (
<path
style={{
fill: '#CCCCCC',
stroke: '#333333',
strokeWidth: 1.5,
transition: 'fill 250ms linear',
cursor: 'pointer',
':hover': {
fill: '#999999',
stroke: '#000000'
}
}}
d={this.... | identifier_body |
PieChart.js | import SVG from './SVG';
import Radium from 'radium';
import { layout, svg } from 'd3';
import { Spring } from 'react-motion';
import { Component, PropTypes } from 'react';
export default class PieChart extends Component {
static defaultProps = {
data: PropTypes.array.isRequired,
width: PropTypes.number.isRe... | extends Component {
render() {
return (
<path
style={{
fill: '#CCCCCC',
stroke: '#333333',
strokeWidth: 1.5,
transition: 'fill 250ms linear',
cursor: 'pointer',
':hover': {
fill: '#999999',
stroke: '#000000'
... | Path | identifier_name |
rustbox.rs | : 0, y: 0 };
#[derive(Debug)]
pub enum EventError {
TermboxError,
Unknown(isize),
}
impl fmt::Display for EventError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
}
}
impl Error for EventError {
fn description(&self) -> &str {
match *self ... | {
unsafe { termbox::tb_present() }
} | identifier_body | |
rustbox.rs | (Key::Unknown(ev.key))
}
}),
2 => Ok(Event::ResizeEvent(ev.w, ev.h)),
3 => {
let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left);
Ok(Event::MouseEvent(mouse, ev.x, ev.y))
},
// `unwrap` is safe here because FromPrimitive for Eve... | drop | identifier_name | |
rustbox.rs | #[derive(Clone, Copy, PartialEq)]
#[repr(C,u16)]
pub enum Color {
Default = 0x00,
Black = 0x01,
Red = 0x02,
Green = 0x03,
Yellow = 0x04,
Blue = 0x05,
Magenta = 0x06,
Cyan = 0x07,
White = 0x08,
}
mod style {
bitflags! {
#[repr(C)]
flags S... | impl Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::BufferStderrFailed(_) => "Could not redirect stderr",
InitError::AlreadyOpen => "RustBox is already open",
InitError::UnsupportedTerminal => "Unsupported terminal",
InitError::... | }
| random_line_split |
ipc.ts | import { ipcMain, IpcMainInvokeEvent, WebContents, webContents } from 'electron'
import { Result } from 'stencila'
import { InvokeTypes } from '../../preload/types'
export function valueToSuccessResult<V>(
value?: V,
errors?: Result['errors']
): Result<V>
export function | (
value?: undefined,
errors?: Result['errors']
): Result<undefined> {
return {
ok: true,
value,
errors: errors ?? [],
}
}
// Send the passed IPC message to all open windows of the configuration change.
// Each window should register a corresponding listener and react as needed to the changes.
expor... | valueToSuccessResult | identifier_name |
ipc.ts | import { ipcMain, IpcMainInvokeEvent, WebContents, webContents } from 'electron'
import { Result } from 'stencila'
import { InvokeTypes } from '../../preload/types'
export function valueToSuccessResult<V>(
value?: V,
errors?: Result['errors']
): Result<V>
export function valueToSuccessResult(
value?: undefined,
... | {
ipcMain.handle(channel, listener)
} | identifier_body | |
ipc.ts | import { ipcMain, IpcMainInvokeEvent, WebContents, webContents } from 'electron'
import { Result } from 'stencila'
import { InvokeTypes } from '../../preload/types'
export function valueToSuccessResult<V>(
value?: V,
errors?: Result['errors']
): Result<V>
export function valueToSuccessResult(
value?: undefined,
... | * type safe invocation of both the Invoke and Handle aspects.
* For details see `/preload/types.d.ts`
*/
export function handle<F extends InvokeTypes>(
channel: F['channel'],
listener: (ipcEvent: IpcMainInvokeEvent, ...args: F['args']) => F['result']
): void
export function handle<F extends InvokeTypes>(
chann... | random_line_split | |
pluginconf_d.py | """
pluginconf.d configuration file - Files
=======================================
Shared mappers for parsing and extracting data from
``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained
in this module are:
PluginConfD - files ``/etc/yum/pluginconf.d/*.conf``
---------------------------------------------------... | (self, content):
deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.")
plugin_dict = {}
section_dict = {}
key = None
for line in get_active_lines(content):
if line.startswith('['):
section_dict = {}
plugin_dict[line[1:-1]... | parse_content | identifier_name |
pluginconf_d.py | """
pluginconf.d configuration file - Files
=======================================
Shared mappers for parsing and extracting data from
``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained
in this module are:
PluginConfD - files ``/etc/yum/pluginconf.d/*.conf``
---------------------------------------------------... |
self.data = plugin_dict
def __iter__(self):
for sec in self.data:
yield sec
@parser(Specs.pluginconf_d)
class PluginConfDIni(IniConfigFile):
"""
Read yum plugin config files, in INI format, using the standard INI file
parser class.
Sample configuration::
[ma... | if key:
section_dict[key] = ','.join([section_dict[key], line]) | conditional_block |
pluginconf_d.py | """
pluginconf.d configuration file - Files
=======================================
Shared mappers for parsing and extracting data from
``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained
in this module are:
PluginConfD - files ``/etc/yum/pluginconf.d/*.conf``
---------------------------------------------------... |
@parser(Specs.pluginconf_d)
class PluginConfDIni(IniConfigFile):
"""
Read yum plugin config files, in INI format, using the standard INI file
parser class.
Sample configuration::
[main]
enabled = 0
gpgcheck = 1
timeout = 120
# You can specify options per cha... | for sec in self.data:
yield sec | identifier_body |
pluginconf_d.py | """
pluginconf.d configuration file - Files
=======================================
Shared mappers for parsing and extracting data from
``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained
in this module are:
PluginConfD - files ``/etc/yum/pluginconf.d/*.conf``
---------------------------------------------------... | http://mirror_example.com/repos/test/
Examples:
>>> type(conf)
<class 'insights.parsers.pluginconf_d.PluginConfDIni'>
>>> conf.sections()
['main', 'test']
>>> conf.has_option('main', 'gpgcheck')
True
>>> conf.get("main", "enabl... | test_multiline_config = http://example.com/repos/test/ | random_line_split |
color.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 azure::AzFloat;
use azure::azure_hl::Color as AzColor;
| r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
}
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
} | pub type Color = AzColor;
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor {
AzColor { | random_line_split |
color.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 azure::AzFloat;
use azure::azure_hl::Color as AzColor;
pub type Color = AzColor;
#[inline]
pub fn rgb(r: u8,... |
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
| {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
} | identifier_body |
color.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 azure::AzFloat;
use azure::azure_hl::Color as AzColor;
pub type Color = AzColor;
#[inline]
pub fn rgb(r: u8,... | (r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
| rgba | identifier_name |
extension_tests.py | """Tests for cement.core.extension."""
from cement.core import exc, backend, extension, handler, output, interface
from cement.utils import test
class IBogus(interface.Interface):
class IMeta:
label = 'bogus'
class BogusExtensionHandler(extension.CementExtensionHandler):
class Meta:
inter... | (self):
# the handler type bogus doesn't exist
handler.register(BogusExtensionHandler)
def test_load_extensions(self):
ext = extension.CementExtensionHandler()
ext._setup(self.app)
ext.load_extensions(['cement.ext.ext_configparser'])
def test_load_extensions_again(self)... | test_invalid_extension_handler | identifier_name |
extension_tests.py | """Tests for cement.core.extension."""
from cement.core import exc, backend, extension, handler, output, interface
from cement.utils import test
class IBogus(interface.Interface):
class IMeta:
|
class BogusExtensionHandler(extension.CementExtensionHandler):
class Meta:
interface = IBogus
label = 'bogus'
class ExtensionTestCase(test.CementCoreTestCase):
@test.raises(exc.FrameworkError)
def test_invalid_extension_handler(self):
# the handler type bogus doesn't exist
... | label = 'bogus' | identifier_body |
extension_tests.py | """Tests for cement.core.extension."""
from cement.core import exc, backend, extension, handler, output, interface
from cement.utils import test
class IBogus(interface.Interface):
class IMeta:
label = 'bogus'
class BogusExtensionHandler(extension.CementExtensionHandler):
class Meta:
inter... | ext._setup(self.app)
ext.load_extensions(['cement.ext.ext_configparser'])
ext.load_extensions(['cement.ext.ext_configparser'])
@test.raises(exc.FrameworkError)
def test_load_bogus_extension(self):
ext = extension.CementExtensionHandler()
ext._setup(self.app)
ext.... | ext._setup(self.app)
ext.load_extensions(['cement.ext.ext_configparser'])
def test_load_extensions_again(self):
ext = extension.CementExtensionHandler() | random_line_split |
changeImgsParams.js | define([ ], ( ) => {
function handleChange(imgSArr, callback) {
let name = sessionStorage.getItem('fancy-gallery-order');
let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal';
let shuffled = parseInt(sessionStorage.getItem('fancy-gal... |
}
function changeImgsParams(imgSArr, callback) {
window.ee.addListener('orderChanged', () => {
handleChange(imgSArr, callback);
});
}
return changeImgsParams;
}); | {
imgSArr[i].setSequence({
name: name,
direction,
shuffled,
speed
});
// imgSArr[i].setElementsX();
} | conditional_block |
changeImgsParams.js | define([ ], ( ) => {
function handleChange(imgSArr, callback) {
let name = sessionStorage.getItem('fancy-gallery-order');
let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal';
let shuffled = parseInt(sessionStorage.getItem('fancy-gal... | for (let i = 0, max = imgSArr.length; i < max; i++) {
imgSArr[i].setSequence({
name: name,
direction,
shuffled,
speed
});
// imgSArr[i].setElementsX();
}
}
function changeImgsParams(im... |
insertCss(JSON.parse(sessionStorage.getItem('fancy-gallery-configJSON')), plugin, callback);
;
| random_line_split |
changeImgsParams.js | define([ ], ( ) => {
function handleChange(imgSArr, callback) {
let name = sessionStorage.getItem('fancy-gallery-order');
let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal';
let shuffled = parseInt(sessionStorage.getItem('fancy-gal... |
return changeImgsParams;
}); | {
window.ee.addListener('orderChanged', () => {
handleChange(imgSArr, callback);
});
} | identifier_body |
changeImgsParams.js | define([ ], ( ) => {
function handleChange(imgSArr, callback) {
let name = sessionStorage.getItem('fancy-gallery-order');
let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal';
let shuffled = parseInt(sessionStorage.getItem('fancy-gal... | (imgSArr, callback) {
window.ee.addListener('orderChanged', () => {
handleChange(imgSArr, callback);
});
}
return changeImgsParams;
}); | changeImgsParams | identifier_name |
nileServer.js | const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser')
// const formidable = require('formidable');
// const createTorrent = require('create-torrent');
// const WebTorrent = require('webtorrent');
const socketController = require('./socketCo... | // Pass server instance to use socket controller
const socket = new socketController(server, socketLimit);
// create nile.js mini-app through express Router
const nileServer = express.Router();
// endpoint for receiving magnet URI from Broadcaster
nileServer.post('/magnet', (req, res, next) => {
socke... | // max # of sockets to keep open
const socketLimit = 1;
// takes in Node Server instance and returns Express Router
module.exports = function nileServer(server) { | random_line_split |
export-glob-imports-target.rs | // xfail-fast
// 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
// <... | use foo::bar::*;
pub mod bar {
pub static a : int = 10;
}
pub fn zum() {
let _b = a;
}
}
pub fn main() { } |
mod foo { | random_line_split |
export-glob-imports-target.rs | // xfail-fast
// 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
// <... | { } | identifier_body | |
export-glob-imports-target.rs | // xfail-fast
// 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
// <... | () { }
| main | identifier_name |
StringData.js | /**
* Data that contains a string.
* @param {string} value
* @param {boolean} [isValid=true]
* @constructor
*/
function StringData(value, isValid) {
Data.call(this, Data.types.string, value, isValid);
}
StringData.prototype = Object.create(Data.prototype);
StringData.prototype.constructor = StringData;
/**
* If... | * @return {boolean}
*/
StringData.prototype.isNumber = function() {
//from https://en.wikipedia.org/wiki/Regular_expression
const numberRE = /^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/;
return numberRE.test(this.getValue());
};
/**
* Imports StringData from XML
* @param {Node} dataNode
* @return {StringData|nu... | return this;
};
/**
* Checks to see if the number can be converted to a valid number | random_line_split |
StringData.js | /**
* Data that contains a string.
* @param {string} value
* @param {boolean} [isValid=true]
* @constructor
*/
function StringData(value, isValid) |
StringData.prototype = Object.create(Data.prototype);
StringData.prototype.constructor = StringData;
/**
* If the value could represent a number, it is converted to valid NumData. Otherwise, invalid NumData(0) is returned
* @return {NumData}
*/
StringData.prototype.asNum = function() {
if (this.isNumber()) {
r... | {
Data.call(this, Data.types.string, value, isValid);
} | identifier_body |
StringData.js | /**
* Data that contains a string.
* @param {string} value
* @param {boolean} [isValid=true]
* @constructor
*/
function | (value, isValid) {
Data.call(this, Data.types.string, value, isValid);
}
StringData.prototype = Object.create(Data.prototype);
StringData.prototype.constructor = StringData;
/**
* If the value could represent a number, it is converted to valid NumData. Otherwise, invalid NumData(0) is returned
* @return {NumData}
... | StringData | identifier_name |
mod.rs | use std::ops::{Deref, DerefMut};
use std::io::Read;
use rocket::outcome::Outcome;
use rocket::request::Request;
use rocket::data::{self, Data, FromData};
use rocket::response::{self, Responder, content};
use rocket::http::Status;
use serde::{Serialize, Deserialize};
use serde_json;
pub use serde_json::Value;
pub us... | /// # use rocket_contrib::JSON;
/// let string = "Hello".to_string();
/// let my_json = JSON(string);
/// assert_eq!(my_json.into_inner(), "Hello".to_string());
/// ```
pub fn into_inner(self) -> T {
self.0
}
}
/// Maximum size of JSON is 1MB.
/// TODO: Determine this size from some... | /// ```rust | random_line_split |
mod.rs | use std::ops::{Deref, DerefMut};
use std::io::Read;
use rocket::outcome::Outcome;
use rocket::request::Request;
use rocket::data::{self, Data, FromData};
use rocket::response::{self, Responder, content};
use rocket::http::Status;
use serde::{Serialize, Deserialize};
use serde_json;
pub use serde_json::Value;
pub us... |
}
/// Maximum size of JSON is 1MB.
/// TODO: Determine this size from some configuration parameter.
const MAX_SIZE: u64 = 1048576;
impl<T: Deserialize> FromData for JSON<T> {
type Error = SerdeError;
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> {
if !request.content... | {
self.0
} | identifier_body |
mod.rs | use std::ops::{Deref, DerefMut};
use std::io::Read;
use rocket::outcome::Outcome;
use rocket::request::Request;
use rocket::data::{self, Data, FromData};
use rocket::response::{self, Responder, content};
use rocket::http::Status;
use serde::{Serialize, Deserialize};
use serde_json;
pub use serde_json::Value;
pub us... | (self) -> T {
self.0
}
}
/// Maximum size of JSON is 1MB.
/// TODO: Determine this size from some configuration parameter.
const MAX_SIZE: u64 = 1048576;
impl<T: Deserialize> FromData for JSON<T> {
type Error = SerdeError;
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeEr... | into_inner | identifier_name |
archive_ro.rs | // Copyright 2013-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-MI... | else {
Some(slice::from_raw_parts(ptr as *const u8, size as usize))
}
}
}
}
impl Drop for ArchiveRO {
fn drop(&mut self) {
unsafe {
::LLVMRustDestroyArchive(self.ptr);
}
}
}
| {
None
} | conditional_block |
archive_ro.rs | // Copyright 2013-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-MI... | }
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let file = CString::new(file).unwrap();
let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(),
... | #[cfg(windows)]
fn path2cstr(p: &Path) -> CString {
CString::new(p.to_str().unwrap()).unwrap()
} | random_line_split |
archive_ro.rs | // Copyright 2013-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-MI... | (p: &Path) -> CString {
CString::new(p.to_str().unwrap()).unwrap()
}
}
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let file = CString::new(file).unwrap();
... | path2cstr | identifier_name |
archive_ro.rs | // Copyright 2013-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-MI... |
}
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let file = CString::new(file).unwrap();
let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(),
... | {
CString::new(p.to_str().unwrap()).unwrap()
} | identifier_body |
sup.server.protocol.ts | import { Upload } from './../models/upload/upload.model';
import { SUPController } from './sup.server.controller';
const yellow = '\x1b[33m%s\x1b[0m: ';
export class SUP {
constructor(private io: SocketIOClient.Manager) { }
registerIO() {
this.io.on('connection', (socket: So... | (data, cb): void {
SUPController.pause(data, cb);
}
static continue(data, cb): void {
SUPController.continue(data, cb);
}
static abort(data, cb): void {
SUPController.abort(data, cb);
}
}
| pause | identifier_name |
sup.server.protocol.ts | import { Upload } from './../models/upload/upload.model';
import { SUPController } from './sup.server.controller';
const yellow = '\x1b[33m%s\x1b[0m: ';
export class SUP {
constructor(private io: SocketIOClient.Manager) { }
registerIO() {
this.io.on('connection', (socket: So... | console.log(yellow, 'Receiving next File.');
SUPController.nextFile(data, socket);
});
});
}
static handshake(data, cb): void {
SUPController.handshake(data, cb);
}
static pause(data, cb): void {
SUPController.pause(data, cb);
}
static continue(... | socket.on('NextChunk', (data) => {
console.log(yellow, 'Receiving data.');
SUPController.nextChunk(data, socket);
});
socket.on('NextFile', (data) => { | random_line_split |
sup.server.protocol.ts | import { Upload } from './../models/upload/upload.model';
import { SUPController } from './sup.server.controller';
const yellow = '\x1b[33m%s\x1b[0m: ';
export class SUP {
constructor(private io: SocketIOClient.Manager) { }
registerIO() {
this.io.on('connection', (socket: So... |
static pause(data, cb): void {
SUPController.pause(data, cb);
}
static continue(data, cb): void {
SUPController.continue(data, cb);
}
static abort(data, cb): void {
SUPController.abort(data, cb);
}
}
| {
SUPController.handshake(data, cb);
} | identifier_body |
anchorGenerator.py | # anchorGenerator
from models.anchor import *
# main function
if __name__=='__main__':
# TEMP: Wipe existing anchors
# anchors = Anchor.all(size=1000)
# Anchor.delete_all(anchors)
# THIS IS TEMPORARY:
| "analyze_wildcard": True
}
}
}
},
"aggs": {
"2": {
"terms": {
"field": "title",
"size": 100,
"order": {
"_count": "desc"
}
}
}
}
}
response = es.search(index="crowdynews"', 'body=query)
retrieved = now()
anchors = {}
#... | anchors = {'Vaccination', 'Vaccinations', 'Vaccine', 'Vaccines', 'Inoculation', 'Immunization', 'Shot', 'Chickenpox', 'Disease', 'Diseases', 'Hepatitis A', 'Hepatitis B', 'infection', 'infections', 'measles', 'outbreak', 'mumps', 'rabies', 'tetanus', 'virus', 'autism'}
seed = 'vaccination'
for anchor in anchors:
a... | conditional_block |
anchorGenerator.py | # anchorGenerator
from models.anchor import *
# main function
if __name__=='__main__':
# TEMP: Wipe existing anchors
# anchors = Anchor.all(size=1000)
# Anchor.delete_all(anchors)
# THIS IS TEMPORARY:
anchors = {'Vaccination', 'Vaccinations', 'Vaccine', 'Vaccines', 'Inoculation', 'Immunization', 'Shot', 'Chicken... | "aggs": {
"2": {
"terms": {
"field": "title",
"size": 100,
"order": {
"_count": "desc"
}
}
}
}
}
response = es.search(index="crowdynews"', 'body=query)
retrieved = now()
anchors = {}
# go through each retrieved document
for hit in response['aggreg... | }, | random_line_split |
postmessage.js | // @license
// Redistribution and use in source and binary forms ...
// Class for sending and receiving postMessages.
// Based off the library by Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com)
//
// Dependencies:
// * None
//
// Copyright 2014 Carnegie Mellon University. All rights reserved.
//
... |
}
listeners[type] = newListeners;
}
} else {
// Remove all listeners by type
delete listeners[type];
}
} else {
// Unbind all listeners of all types
for (var i in listeners) {
delete listeners[i]... | {
newListeners.push(obj);
} | conditional_block |
postmessage.js | // @license
// Redistribution and use in source and binary forms ...
// Class for sending and receiving postMessages.
// Based off the library by Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com)
//
// Dependencies:
// * None
//
// Copyright 2014 Carnegie Mellon University. All rights reserved.
//
... | "use strict";
(function(window) {
// Send postMessages.
window.pm = function(options) {
pm.send(options);
};
// Bind a handler to a postMessage response.
window.pm.bind = function(type, fn) {
pm.bind(type, fn);
};
// Unbind postMessage handlers
window.pm.unbind = function(type, fn) {
pm.... | random_line_split | |
plane.rs | --------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// |... | (
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(ob... | draw_pipe_tip | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.