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 |
|---|---|---|---|---|
yesterday_dump.py | import time
from pymongo import MongoClient
from datetime import datetime, timedelta
import json
from bson import Binary, Code
from bson.json_util import dumps
client = MongoClient('localhost', 27017)
db = client['election-2016']
| def dumpData(yesterdayStr):
collectionName = 't' + yesterdayStr
cursor = db[collectionName].find()
count = cursor.count()
print(collectionName + ' found ' + str(count) + ' tweets')
# dump only if data count is greater than 0
if count > 0:
file = open('out/' + yesterdayStr + '.json', '... | random_line_split | |
GFXRenderer.js | /*
* GFXRenderer v1.0.4 Copyright (c) 2016 AJ Savino
* https://github.com/koga73/GFXRenderer/
*
* 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 limitat... |
if (!_vars._renderInterval){
requestAnimationFrame(_methods._render);
}
},
_resize:function(){
_methods._updateSize();
if (_instance.onResize){
_instance.onResize();
}
},
_updateSize:function(){
var canvas = _instance.canvas;
... | { //As to not "jump" when returning to page
_instance.onRender(delta);
} | conditional_block |
GFXRenderer.js | /*
* GFXRenderer v1.0.4 Copyright (c) 2016 AJ Savino
* https://github.com/koga73/GFXRenderer/
*
* 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 limitat... |
var _methods = {
init:function(){
if (window.addEventListener){
window.addEventListener("resize", _methods._handler_resize, false);
window.addEventListener("orientationchange", _methods._handler_resize, false);
} else if (window.attachEvent){
window.attachEvent("onresize", _methods._h... | callbackDelay:300, //Time in ms to wait before calling onResize
_lastOrientation:window.orientation,
_timeout:null,
}; | random_line_split |
scielo_wos_scieloci_update.py | # coding: utf-8
'''
This script reads data from various sources to process and store in MongoDB.
'''
import pyexcel
import logging
import models
from transform_date import *
from accent_remover import *
logging.basicConfig(filename='logs/scieloci.info.txt', level=logging.INFO)
logger = logging.getLogger(__name__)
#... | (filename):
sheet = pyexcel.get_sheet(
file_name=filename,
sheet_name='import',
name_columns_by_row=0)
sheet_json = sheet.to_records()
for rec in sheet_json:
# # remove empty keys
# rec = {k: v for k, v in rec.items() if v or v == 0}
query = models.Scielo.ob... | scieloci | identifier_name |
scielo_wos_scieloci_update.py | # coding: utf-8
'''
This script reads data from various sources to process and store in MongoDB.
'''
import pyexcel
import logging
import models
from transform_date import *
from accent_remover import *
logging.basicConfig(filename='logs/scieloci.info.txt', level=logging.INFO)
logger = logging.getLogger(__name__)
#... |
def main():
# SciELO docs counts Network xlsx
# scieloci('data/scielo/td_wos_all_downloads.xlsx')
# scieloci('data/wos/td_wos_all.xlsx')
scieloci('data/wos/td_wos_scieloci_2017_2018.xlsx')
if __name__ == "__main__":
main()
| oc.modify(**data)
| conditional_block |
scielo_wos_scieloci_update.py | # coding: utf-8
'''
This script reads data from various sources to process and store in MongoDB.
'''
import pyexcel
import logging
import models
from transform_date import *
from accent_remover import *
logging.basicConfig(filename='logs/scieloci.info.txt', level=logging.INFO)
logger = logging.getLogger(__name__)
#... | print('não encontrou: ' + str(rec['issn_scielo']))
if data:
doc.modify(**data)
def main():
# SciELO docs counts Network xlsx
# scieloci('data/scielo/td_wos_all_downloads.xlsx')
# scieloci('data/wos/td_wos_all.xlsx')
scieloci('data/wos/td_wos_scieloci_2017_2018.xlsx')
... | sheet = pyexcel.get_sheet(
file_name=filename,
sheet_name='import',
name_columns_by_row=0)
sheet_json = sheet.to_records()
for rec in sheet_json:
# # remove empty keys
# rec = {k: v for k, v in rec.items() if v or v == 0}
query = models.Scielo.objects.filter(iss... | identifier_body |
scielo_wos_scieloci_update.py | # coding: utf-8
'''
This script reads data from various sources to process and store in MongoDB.
'''
import pyexcel
import logging
import models
from transform_date import *
from accent_remover import *
logging.basicConfig(filename='logs/scieloci.info.txt', level=logging.INFO)
logger = logging.getLogger(__name__)
#... | print('não encontrou: ' + str(rec['issn_scielo']))
if data:
doc.modify(**data)
def main():
# SciELO docs counts Network xlsx
# scieloci('data/scielo/td_wos_all_downloads.xlsx')
# scieloci('data/wos/td_wos_all.xlsx')
scieloci('data/wos/td_wos_scieloci_2017_2018.xlsx')
... | random_line_split | |
plotLineValVsTint.py | #!/usr/bin/env python
"""
"""
import os,sys
import numpy as np
import matplotlib
#matplotlib.use('Agg')
import pylab as p
import cPickle as pkl
from scipy import interpolate
matplotlib.rc('xtick',labelsize=25)
matplotlib.rc('ytick',labelsize=25)
modeTitle=['Total Intensity','Invariant Interval','Matrix Template Ma... | return y
if __name__ == "__main__":
from optparse import OptionParser
o = OptionParser()
o.set_usage('%prog [options] [pklReduceDict.py DICT]')
o.set_description(__doc__)
o.add_option('-c','--cal',dest='calMode',default='cal',
help='cal mode to use: cal or uncal, default: cal')
o.a... | if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than window size."
if window_len<3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
rais... | identifier_body |
plotLineValVsTint.py | #!/usr/bin/env python
"""
"""
import os,sys
import numpy as np
import matplotlib
#matplotlib.use('Agg')
import pylab as p
import cPickle as pkl
from scipy import interpolate
matplotlib.rc('xtick',labelsize=25)
matplotlib.rc('ytick',labelsize=25)
modeTitle=['Total Intensity','Invariant Interval','Matrix Template Ma... | (x,window_len=31,window='hanning'):
if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than window size."
if window_len<3:
return x
if not window in ['flat', 'hanning', 'hamming... | smooth | identifier_name |
plotLineValVsTint.py | #!/usr/bin/env python
"""
"""
import os,sys
import numpy as np
import matplotlib
#matplotlib.use('Agg')
import pylab as p
import cPickle as pkl
from scipy import interpolate
matplotlib.rc('xtick',labelsize=25)
matplotlib.rc('ytick',labelsize=25)
modeTitle=['Total Intensity','Invariant Interval','Matrix Template Ma... |
#lines of constant time (5, 1, .5 us)
p.hlines([5,1,.5],np.min(snrs),np.max(snrs),linestyles=['dashed','dashdot','dotted'])
#slightly hardcoded plot limits
#print np.min(snrs),np.max(snrs)
#print np.min(simVals),np.max(simVals)
#p.xlim(np.min(snrs),np.max(snrs))
p.xlim(np.min(snrs),0.1)
... | idx=np.argwhere(polLeakdbs==pVal)
subSnrs=snrs[idx]
subSimVals=simVals[idx]
sIdx=np.argsort(subSnrs[:,0])
rgb=(np.exp(pVal/10.),0.,1.-np.exp(pVal/10.))
#slightly hardcoded plots and labels
#if pVal > -0.0001: labelStr='%0.f dB'%(-1.*pVal) #-0 to 0
if pVal > -0.1: ... | conditional_block |
plotLineValVsTint.py | #!/usr/bin/env python
"""
"""
import os,sys
import numpy as np
import matplotlib
#matplotlib.use('Agg')
import pylab as p
import cPickle as pkl
from scipy import interpolate
matplotlib.rc('xtick',labelsize=25)
matplotlib.rc('ytick',labelsize=25)
modeTitle=['Total Intensity','Invariant Interval','Matrix Template Ma... | help='cal mode to use: cal or uncal, default: cal')
o.add_option('-m','--mode',dest='mode',default='rms',
help='Data mode: rms, chi2, sigma ; default: rms')
o.add_option('-r','--rms', dest='rmsMode', default=0, type='int',
help='Set RMS mode, 0: total intesity, 1: invariant interval, 2: ... | o.set_description(__doc__)
o.add_option('-c','--cal',dest='calMode',default='cal', | random_line_split |
test_utils.py | version_factory
from olympia.devhub import tasks, utils
from olympia.files.models import FileUpload
class TestValidatorBase(TestCase):
def setUp(self):
# Create File objects for version 1.0 and 1.1.
self.addon = addon_factory(
guid='test-desktop@nowhere', slug='test-amo-addon',
... | (self, types):
"""Take a list of error types and make a
validation results dict."""
validation = {
'messages': [],
'errors': 0,
'warnings': 0,
'notices': 0,
}
severities = ['low', 'medium', 'high']
for type_ in types:
... | make_validation | identifier_name |
test_utils.py | version_factory
from olympia.devhub import tasks, utils
from olympia.files.models import FileUpload
class TestValidatorBase(TestCase):
def setUp(self):
# Create File objects for version 1.0 and 1.1.
self.addon = addon_factory(
guid='test-desktop@nowhere', slug='test-amo-addon',
... |
class TestFixAddonsLinterOutput(TestCase):
def test_fix_output(self):
original_output = {
'count': 4,
'summary': {
'errors': 0,
'notices': 0,
'warnings': 4
},
'metadata': {
'manifestVersion': ... | validation = self.make_validation(
['error', 'warning', 'notice', 'error'])
utils.limit_validation_results(validation)
limited = validation['messages']
assert len(limited) == 3
assert '2 messages were truncated' in limited[0]['message']
assert limited[1]['type'] == 'e... | identifier_body |
test_utils.py | version_factory
from olympia.devhub import tasks, utils
from olympia.files.models import FileUpload
class TestValidatorBase(TestCase):
def setUp(self):
# Create File objects for version 1.0 and 1.1.
self.addon = addon_factory( | self.file_1_1 = self.version_1_1.files.get()
# Creating the files and versions above resets this.
self.addon.update(status=amo.STATUS_PUBLIC)
# Create a FileUpload object for an XPI containing version 1.1.
path = os.path.join(settings.ROOT,
'src/olym... | guid='test-desktop@nowhere', slug='test-amo-addon',
version_kw={'version': '1.0'})
self.version = self.addon.current_version
self.file = self.version.files.get()
self.version_1_1 = version_factory(addon=self.addon, version='1.1') | random_line_split |
test_utils.py | 1 = version_factory(addon=self.addon, version='1.1')
self.file_1_1 = self.version_1_1.files.get()
# Creating the files and versions above resets this.
self.addon.update(status=amo.STATUS_PUBLIC)
# Create a FileUpload object for an XPI containing version 1.1.
path = os.path.join... | assert fixed['metadata'][key] == value | conditional_block | |
webglvertexarrayobjectoes.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 canvas_traits::webgl::WebGLVertexArrayId;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bin... |
pub fn borrow_bound_attrib_buffers(&self) -> Ref<HashMap<u32, Dom<WebGLBuffer>>> {
self.bound_attrib_buffers.borrow()
}
pub fn bound_attrib_buffers(&self) -> Vec<DomRoot<WebGLBuffer>> {
self.bound_attrib_buffers.borrow().iter().map(|(_, b)| DomRoot::from_ref(&**b)).collect()
}
pub... |
pub fn set_ever_bound(&self) {
self.ever_bound.set(true);
} | random_line_split |
webglvertexarrayobjectoes.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 canvas_traits::webgl::WebGLVertexArrayId;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bin... | (global: &GlobalScope, id: WebGLVertexArrayId) -> DomRoot<WebGLVertexArrayObjectOES> {
reflect_dom_object(Box::new(WebGLVertexArrayObjectOES::new_inherited(id)),
global,
WebGLVertexArrayObjectOESBinding::Wrap)
}
pub fn id(&self) -> WebGLVertexArrayI... | new | identifier_name |
webglvertexarrayobjectoes.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 canvas_traits::webgl::WebGLVertexArrayId;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bin... |
pub fn set_deleted(&self) {
self.is_deleted.set(true)
}
pub fn ever_bound(&self) -> bool {
return self.ever_bound.get()
}
pub fn set_ever_bound(&self) {
self.ever_bound.set(true);
}
pub fn borrow_bound_attrib_buffers(&self) -> Ref<HashMap<u32, Dom<WebGLBuffer>>> ... | {
self.is_deleted.get()
} | identifier_body |
config.rs | use actix_web::web;
/// Run custom configuration as part of the application building
/// process.
///
/// This function should contain all custom configuration for your function application.
///
/// ```rust
/// fn configure(cfg: &mut web::ServiceConfig) {
/// let db_driver = my_db();
/// cfg.data(db_driver.clo... |
/// An example of the function configuration structure.
pub struct HandlerConfig {
pub name: String,
}
impl Default for HandlerConfig {
fn default() -> HandlerConfig {
HandlerConfig {
name: String::from("world"),
}
}
}
| {
log::info!("Configuring service");
cfg.data(HandlerConfig::default());
} | identifier_body |
config.rs | use actix_web::web;
/// Run custom configuration as part of the application building
/// process.
///
/// This function should contain all custom configuration for your function application.
///
/// ```rust
/// fn configure(cfg: &mut web::ServiceConfig) {
/// let db_driver = my_db();
/// cfg.data(db_driver.clo... | (cfg: &mut web::ServiceConfig) {
log::info!("Configuring service");
cfg.data(HandlerConfig::default());
}
/// An example of the function configuration structure.
pub struct HandlerConfig {
pub name: String,
}
impl Default for HandlerConfig {
fn default() -> HandlerConfig {
HandlerConfig {
... | configure | identifier_name |
config.rs | use actix_web::web;
/// Run custom configuration as part of the application building
/// process.
///
/// This function should contain all custom configuration for your function application.
///
/// ```rust
/// fn configure(cfg: &mut web::ServiceConfig) {
/// let db_driver = my_db();
/// cfg.data(db_driver.clo... | }
} | name: String::from("world"),
} | random_line_split |
helpers.rs | extern crate diesel;
extern crate chrono;
extern crate dotenv;
extern crate serde;
extern crate wiko;
use std::path; | use wiko::models::*;
fn load_test_env() {
let mut path = path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("test.env");
dotenv::from_path(&path).expect("Invalid dotenv");
}
pub struct TestHelper;
impl TestHelper {
pub fn get_test_connection() -> WikoConnection {
load_test_env();
... | use self::diesel::*;
use wiko::{Wiko,WikoConnection}; | random_line_split |
helpers.rs | extern crate diesel;
extern crate chrono;
extern crate dotenv;
extern crate serde;
extern crate wiko;
use std::path;
use self::diesel::*;
use wiko::{Wiko,WikoConnection};
use wiko::models::*;
fn load_test_env() {
let mut path = path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("test.env");
dote... | () -> Wiko {
let conn = Self::get_test_connection();
Wiko::new(conn)
}
pub fn insert_post() -> Post {
let new_post = NewPost::default();
Self::new_wiko().create_post(&new_post).expect("Error creating new post")
}
pub fn get_post() -> Post {
let inserted = Self::... | new_wiko | identifier_name |
helpers.rs | extern crate diesel;
extern crate chrono;
extern crate dotenv;
extern crate serde;
extern crate wiko;
use std::path;
use self::diesel::*;
use wiko::{Wiko,WikoConnection};
use wiko::models::*;
fn load_test_env() {
let mut path = path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("test.env");
dote... |
pub fn get_post() -> Post {
let inserted = Self::insert_post();
Self::new_wiko().get_post(inserted.id).expect("Error getting post")
}
pub fn insert_post_revision() -> PostRevision {
let post = Self::get_post();
let new_post_revision = NewPostRevision::from_post(&post);
... | {
let new_post = NewPost::default();
Self::new_wiko().create_post(&new_post).expect("Error creating new post")
} | identifier_body |
gulpfile.ts | /* /gulpfile.ts */
import {Gulpclass, SequenceTask, Task} from 'gulpclass';
import * as gulp from 'gulp';
import * as mocha from 'gulp-mocha';
import * as rename from 'gulp-rename';
import * as shell from 'gulp-shell';
import tslint from 'gulp-tslint';
import * as del from 'del';
@Gulpclass()
export class Gulpfile ... | return ['clean', 'compile', 'copyConfig'];
}
@SequenceTask()
public test() {
return ['tslint', 'runTests'];
}
} |
@SequenceTask()
public build() { | random_line_split |
gulpfile.ts | /* /gulpfile.ts */
import {Gulpclass, SequenceTask, Task} from 'gulpclass';
import * as gulp from 'gulp';
import * as mocha from 'gulp-mocha';
import * as rename from 'gulp-rename';
import * as shell from 'gulp-shell';
import tslint from 'gulp-tslint';
import * as del from 'del';
@Gulpclass()
export class Gulpfile ... | () {
return gulp.src('./config.template.yml')
.pipe(rename('./config.yml'))
.pipe(gulp.dest('./'));
}
// -------------------------
// Run test tasks
// -------------------------
// Run tslint.
@Task()
public tslint() {
return gulp.src(['./src/**/*.ts', './test/**/*.t... | renameConfig | identifier_name |
gulpfile.ts | /* /gulpfile.ts */
import {Gulpclass, SequenceTask, Task} from 'gulpclass';
import * as gulp from 'gulp';
import * as mocha from 'gulp-mocha';
import * as rename from 'gulp-rename';
import * as shell from 'gulp-shell';
import tslint from 'gulp-tslint';
import * as del from 'del';
@Gulpclass()
export class Gulpfile ... |
// Copy config.yml.
@Task()
public copyConfig() {
return gulp.src('./config.yml')
.pipe(gulp.dest('./build'));
}
// Rename config.template.yml to config.yml.
@Task()
public renameConfig() {
return gulp.src('./config.template.yml')
.pipe(rename('./config.yml'))
... | {
return gulp.src('package.json', { read: false })
.pipe(shell(['npm run compile']));
} | identifier_body |
properties.rs | use regex;
use serde_json::Value;
use std::collections;
use url;
use super::super::errors;
use super::super::scope;
#[derive(Debug)]
pub enum AdditionalKind {
Boolean(bool),
Schema(url::Url),
}
#[allow(missing_copy_implementations)]
pub struct Properties {
pub properties: collections::HashMap<String, url... | (&self, val: &Value, path: &str, scope: &scope::Scope) -> super::ValidationState {
let object = nonstrict_process!(val.as_object(), path);
let mut state = super::ValidationState::new();
'main: for (key, value) in object.iter() {
let is_property_passed = if self.properties.contains_k... | validate | identifier_name |
properties.rs | use regex;
use serde_json::Value;
use std::collections;
use url;
use super::super::errors;
use super::super::scope;
#[derive(Debug)]
pub enum AdditionalKind {
Boolean(bool),
Schema(url::Url),
}
#[allow(missing_copy_implementations)]
pub struct Properties {
pub properties: collections::HashMap<String, url... | }
AdditionalKind::Schema(ref url) => {
let schema = scope.resolve(url);
if schema.is_some() {
let value_path = [path, key.as_ref()].join("/");
state.append(schema.unwrap().validate_in(value, value_pa... | AdditionalKind::Boolean(allowed) if !allowed => {
state.errors.push(Box::new(errors::Properties {
path: path.to_string(),
detail: format!("Additional property '{}' is not allowed", key)
})) | random_line_split |
XMLSettingsHandler.js | /*!
GPII XML Settings Handler
Copyright 2012 Raising the Floor - International
Licensed under the New BSD license. You may not use this file except in
compliance with this License.
You may obtain a copy of the License at
https://github.com/gpii/universal/LICENSE.txt
*/
(function () {
"use strict";
var flu... | for (var i = 0; i < pad; i++) {
padding += " ";
}
formatted += padding + node + "\r\n";
pad += indent;
});
return formatted;
};
/**
* Convert XML into JSON.
* In case options.rules is present, trasform with those rules.... |
var padding = ""; | random_line_split |
cargo_generate_lockfile.rs | use std::collections::{BTreeMap, HashSet};
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Resolve, SourceId, Workspace};
use core::resolver::Method;
use ops;
use util::config::Config;
use util::CargoResult;
pub struct UpdateOptions<'a> {
pub config: &'a Config,
pub to_update: &'a [String... | fill_with_deps(&previous_resolve, dep, &mut to_avoid,
&mut HashSet::new());
} else {
to_avoid.insert(dep);
sources.push(match opts.precise {
Some(precise) => {
// TODO: see comment in `... | {
if opts.aggressive && opts.precise.is_some() {
bail!("cannot specify both aggressive and precise simultaneously")
}
let previous_resolve = match try!(ops::load_pkg_lockfile(ws)) {
Some(resolve) => resolve,
None => return generate_lockfile(ws),
};
let mut registry = Packag... | identifier_body |
cargo_generate_lockfile.rs | use std::collections::{BTreeMap, HashSet};
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Resolve, SourceId, Workspace};
use core::resolver::Method;
use ops;
use util::config::Config;
use util::CargoResult;
pub struct UpdateOptions<'a> {
pub config: &'a Config,
pub to_update: &'a [String... | <'a>(resolve: &'a Resolve, dep: &'a PackageId,
set: &mut HashSet<&'a PackageId>,
visited: &mut HashSet<&'a PackageId>) {
if !visited.insert(dep) {
return
}
set.insert(dep);
for dep in resolve.deps(dep) {
fill_wit... | fill_with_deps | identifier_name |
cargo_generate_lockfile.rs | use std::collections::{BTreeMap, HashSet};
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Resolve, SourceId, Workspace};
use core::resolver::Method;
use ops;
use util::config::Config;
use util::CargoResult;
pub struct UpdateOptions<'a> {
pub config: &'a Config,
pub to_update: &'a [String... | None => {
dep.source_id().clone().with_precise(None)
}
});
}
}
try!(registry.add_sources(&sources));
}
let resolve = try!(ops::resolve_with_previous(&mut registry,
... | random_line_split | |
FacebookRoutes.js | import FacebookSetAccessTokenRoute from "./helpers/FacebookSetAccessTokenRoute";
import RouteLogger from "./RouteLogger";
import FacebookSourceRoute from "./helpers/FacebookSourceRoute";
import FacebookTokenDocumentRoute from "./helpers/FacebookTokenDocumentRoute";
export default (app) => {
app.post("/facebook-se... | new FacebookSetAccessTokenRoute(request, response, next).handle();
});
app.post("/facebook-sources", (request, response, next) => {
RouteLogger.instance().info("FacebookRoutes:: /facebook-sources request received. url = %s", request.url);
new FacebookSourceRoute(request, response, next)... | random_line_split | |
lib.rs | //! Serving contents of static directory.
//!
//! ```no_run
//! extern crate staticdir;
//! extern crate iron; | //! Iron::new(StaticDir::new(".", AsJson)).http("localhost:3000").unwrap();
//! }
//! ```
//!
//! This will provide JSON similar to this:
//!
//!```ignore
//! [
//! {
//! "file_type": "File", // "File", "Dir" or "Symlink"
//! "file_name": ".gitignore",
//! "size": 7,
//! "creation_time": null, // ... | //!
//! use iron::prelude::*;
//! use staticdir::{ StaticDir, AsJson };
//!
//! fn main() { | random_line_split |
resilient_backpropagation.py | from ..tools import add_bias, confirm
from ..activation_functions import softmax_function
from ..cost_functions import softmax_neg_loss
import numpy as np
def resilient_backpropagation(network, trainingset, testset, cost_function, ERROR_LIMIT=1e-3, max_iterations = (), weight_step_max = 50., weight_step_min = 0., sta... | # Calculate sign changes and note where they have changed
diffs = np.multiply( dEdW, previous_dEdW[i] )
pos_indexes = np.where( diffs > 0 )
neg_indexes = np.where( diffs < 0 )
zero_indexes = np.where( diffs == 0 )
... | delta = weight_delta * derivatives[i-1]
| random_line_split |
resilient_backpropagation.py | from ..tools import add_bias, confirm
from ..activation_functions import softmax_function
from ..cost_functions import softmax_neg_loss
import numpy as np
def | (network, trainingset, testset, cost_function, ERROR_LIMIT=1e-3, max_iterations = (), weight_step_max = 50., weight_step_min = 0., start_step = 0.5, learn_max = 1.2, learn_min = 0.5, print_rate = 1000, save_trained_network = False ):
# Implemented according to iRprop+
# http://sci2s.ugr.es/keel/pdf/algorithm/a... | resilient_backpropagation | identifier_name |
resilient_backpropagation.py | from ..tools import add_bias, confirm
from ..activation_functions import softmax_function
from ..cost_functions import softmax_neg_loss
import numpy as np
def resilient_backpropagation(network, trainingset, testset, cost_function, ERROR_LIMIT=1e-3, max_iterations = (), weight_step_max = 50., weight_step_min = 0., sta... |
print "[training] Finished:"
print "[training] Converged to error bound (%.4g) with error %.4g." % ( ERROR_LIMIT, error )
print "[training] Measured quality: %.4g" % network.measure_quality( training_data, training_targets, cost_function )
print "[training] Trained for %d epochs." % epoch
... | print "[training] Current error:", error, "\tEpoch:", epoch | conditional_block |
resilient_backpropagation.py | from ..tools import add_bias, confirm
from ..activation_functions import softmax_function
from ..cost_functions import softmax_neg_loss
import numpy as np
def resilient_backpropagation(network, trainingset, testset, cost_function, ERROR_LIMIT=1e-3, max_iterations = (), weight_step_max = 50., weight_step_min = 0., sta... |
# Storing the previous derivative
previous_dEdW = [ 1 ] * len( network.weights )
# Storing the previous error measurement
prev_error = ( ) # inf
input_signals, derivatives = network.update( training_data, trace=True )
out ... | assert softmax_function != network.layers[-1][1] or cost_function == softmax_neg_loss,\
"When using the `softmax` activation function, the cost function MUST be `softmax_neg_loss`."
assert cost_function != softmax_neg_loss or softmax_function == network.layers[-1][1],\
"When using the `softmax_neg_l... | identifier_body |
assertions_on_constants.rs | //FIXME: suggestions are wrongly expanded, this should be fixed along with #7843
#![allow(non_fmt_panics)]
macro_rules! assert_const {
($len:expr) => {
assert!($len > 0);
debug_assert!($len < 0);
};
}
fn | () {
assert!(true);
assert!(false);
assert!(true, "true message");
assert!(false, "false message");
let msg = "panic message";
assert!(false, "{}", msg.to_uppercase());
const B: bool = true;
assert!(B);
const C: bool = false;
assert!(C);
assert!(C, "C message");
debug... | main | identifier_name |
assertions_on_constants.rs | //FIXME: suggestions are wrongly expanded, this should be fixed along with #7843
#![allow(non_fmt_panics)]
macro_rules! assert_const {
($len:expr) => {
assert!($len > 0);
debug_assert!($len < 0);
};
}
fn main() {
assert!(true);
assert!(false);
assert!(true, "true message");
asse... | assert_const!(-1);
// Don't lint on this:
assert!(cfg!(feature = "hey") || cfg!(not(feature = "asdf")));
} |
debug_assert!(true);
// Don't lint this, since there is no better way for expressing "Only panic in debug mode".
debug_assert!(false); // #3948
assert_const!(3); | random_line_split |
assertions_on_constants.rs | //FIXME: suggestions are wrongly expanded, this should be fixed along with #7843
#![allow(non_fmt_panics)]
macro_rules! assert_const {
($len:expr) => {
assert!($len > 0);
debug_assert!($len < 0);
};
}
fn main() | assert_const!(-1);
// Don't lint on this:
assert!(cfg!(feature = "hey") || cfg!(not(feature = "asdf")));
}
| {
assert!(true);
assert!(false);
assert!(true, "true message");
assert!(false, "false message");
let msg = "panic message";
assert!(false, "{}", msg.to_uppercase());
const B: bool = true;
assert!(B);
const C: bool = false;
assert!(C);
assert!(C, "C message");
debug_as... | identifier_body |
vector_plot.py | import numpy as np
from numpy import ma
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap as bm
from mpl_toolkits.basemap import addcyclic
import palettable
class vector_plot:
def __init__(self, ucompos, vcompos):
self.ucompos = ucompos
self.vcompos = vcompos
se... | pivot='middle', scale=scale)
l,b,w,h = ax.get_position().bounds
qk = plt.quiverkey(Q, l+w-0.1, b-0.03, 5, "5 m/s", labelpos='E', fontproperties={'size':14}, coordinates='figure')
m.drawcoastlines()
return f | self.uanoms.data[::stepp,::stepp], self.vanoms.data[::stepp,::stepp], \ | random_line_split |
vector_plot.py | import numpy as np
from numpy import ma
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap as bm
from mpl_toolkits.basemap import addcyclic
import palettable
class vector_plot:
def __init__(self, ucompos, vcompos):
self.ucompos = ucompos
self.vcompos = vcompos
se... | (self, domain = [0., 360., -90., 90.], res='c', stepp=2, scale=20):
latitudes = self.windspeed.latitudes.data
longitudes = self.windspeed.longitudes.data
m = bm(projection='cyl',llcrnrlat=latitudes.min(),urcrnrlat=latitudes.max(),\
llcrnrlon=longitudes.min(),urcrnrlon=longitudes.max(),... | plotmap | identifier_name |
vector_plot.py | import numpy as np
from numpy import ma
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap as bm
from mpl_toolkits.basemap import addcyclic
import palettable
class vector_plot:
def __init__(self, ucompos, vcompos):
|
def plotmap(self, domain = [0., 360., -90., 90.], res='c', stepp=2, scale=20):
latitudes = self.windspeed.latitudes.data
longitudes = self.windspeed.longitudes.data
m = bm(projection='cyl',llcrnrlat=latitudes.min(),urcrnrlat=latitudes.max(),\
llcrnrlon=longitudes.min(),urcrnrlon=... | self.ucompos = ucompos
self.vcompos = vcompos
self.uanoms = self.ucompos.dset['composite_anomalies']
self.vanoms = self.vcompos.dset['composite_anomalies']
self.windspeed = np.sqrt(np.power(self.uanoms, 2) + np.power(self.vanoms, 2)) | identifier_body |
jquery.timeago.am.js | (function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'));
} else |
}(function (jQuery) {
// Amharic
jQuery.timeago.settings.strings = {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "በፊት",
suffixFromNow: "በኋላ",
seconds: "ከአንድ ደቂቃ በታች",
minute: "ከአንድ ደቂቃ ገደማ",
minutes: "ከ%d ደቂቃ",
hour: "ከአንድ ሰዓት ገደማ",
hours: "ከ%d ሰዓት ገደማ",
day: "ከአንድ ቀን",... | {
factory(jQuery);
} | conditional_block |
RouteUtils.js | 'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isReactChi... | *
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
function createRoutesFromReactChildren(children) {
var routes = [];
_react2['default'].Children.forEach(children, function (element) {
if ((0, _react.isValidElement)(element)) {
// Component c... | * </Route>
* ); | random_line_split |
RouteUtils.js | 'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isReactChi... | (object) {
return object == null || (0, _react.isValidElement)(object);
}
function isReactChildren(object) {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent';
fo... | isValidChild | identifier_name |
RouteUtils.js | 'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isReactChi... |
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent';
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, componentName);
if (error instanceof Error) (0, _warning2['... | {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
} | identifier_body |
RouteUtils.js | 'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isReactChi... |
return routes;
} | {
routes = [routes];
} | conditional_block |
view.js | (function(window) {
var DEFAULT_ERROR_ID = 'error-default';
/**
* Very simple base class for views.
* Provides functionality for active/inactive.
*
* The first time the view is activated
* the onactive function/event will fire.
*
* The .seen property is added to each object
* with view in i... | ,
/**
* Creates a string id for a given model.
*
* view.idForModel('foo-', { _id: 1 }); // => foo-1
* view.idForModel('foo-', '2'); // => foo-2
*
* @param {String} prefix of string.
* @param {Object|String|Numeric} objectOrString representation of model.
*/
idForMo... | {
return this._findElement('errors');
} | identifier_body |
view.js | (function(window) {
var DEFAULT_ERROR_ID = 'error-default';
/**
* Very simple base class for views.
* Provides functionality for active/inactive.
*
* The first time the view is activated
* the onactive function/event will fire.
*
* The .seen property is added to each object
* with view in i... |
element = element || document;
var cacheName;
var selector;
if (typeof(all) === 'undefined') {
all = false;
}
if (name in this.selectors) {
cacheName = '_' + name + 'Element';
selector = this.selectors[name];
if (!this[cacheName]) {
if ... | {
element = all;
all = false;
} | conditional_block |
view.js | (function(window) {
var DEFAULT_ERROR_ID = 'error-default';
/**
* Very simple base class for views.
* Provides functionality for active/inactive.
*
* The first time the view is activated
* the onactive function/event will fire.
*
* The .seen property is added to each object
* with view in i... | cssClean: function(string) {
if (typeof(string) !== 'string')
return string;
//TODO: I am worried about the performance
//of using this all over the place =/
//consider sanitizing all keys to ensure
//they don't blow up when used as a selector?
return string.replace(INVA... | * Converts illegal chars to legal ones.
*/ | random_line_split |
view.js | (function(window) {
var DEFAULT_ERROR_ID = 'error-default';
/**
* Very simple base class for views.
* Provides functionality for active/inactive.
*
* The first time the view is activated
* the onactive function/event will fire.
*
* The .seen property is added to each object
* with view in i... | () {
return this._findElement('status');
},
get errors() {
return this._findElement('errors');
},
/**
* Creates a string id for a given model.
*
* view.idForModel('foo-', { _id: 1 }); // => foo-1
* view.idForModel('foo-', '2'); // => foo-2
*
* @param {St... | status | identifier_name |
bbox.py | import scipy.ndimage as ndi
class BBox(object):
def __init__(self, x1, y1, x2, y2):
'''
(x1, y1) is the upper left corner,
(x2, y2) is the lower right corner,
with (0, 0) being in the upper left corner.
'''
if x1 > x2: x1, x2 = x2, x1
if y1 > y2: y1, y2 = y2, y1
self.... | (self):
'''
Return the taxicab distance from (x1,y1) to (x2,y2)
'''
return self.x2 - self.x1 + self.y2 - self.y1
def overlaps(self, other):
'''
Return True iff self and other overlap.
'''
return not ((self.x1 > other.x2)
or (self.x2 < other.x1)
... | taxicab_diagonal | identifier_name |
bbox.py | import scipy.ndimage as ndi
class BBox(object):
def __init__(self, x1, y1, x2, y2):
'''
(x1, y1) is the upper left corner,
(x2, y2) is the lower right corner,
with (0, 0) being in the upper left corner.
'''
if x1 > x2: x1, x2 = x2, x1
if y1 > y2: y1, y2 = y2, y1
self.... |
def slice_to_bbox(slices):
for s in slices:
dy, dx = s[:2]
yield BBox(dx.start, dy.start, dx.stop+1, dy.stop+1)
| """Detects and isolates contiguous regions in the input array"""
# Blur the input data a bit so the paws have a continous footprint
data = ndi.uniform_filter(data, smooth_radius)
# Threshold the blurred data (this needs to be a bit > 0 due to the blur)
thresh = data < threshold
# Fill any interior holes... | identifier_body |
bbox.py | import scipy.ndimage as ndi
class BBox(object):
def __init__(self, x1, y1, x2, y2):
'''
(x1, y1) is the upper left corner,
(x2, y2) is the lower right corner,
with (0, 0) being in the upper left corner.
'''
if x1 > x2: x1, x2 = x2, x1
if y1 > y2: y1, y2 = y2, y1
self.... | dy, dx = s[:2]
yield BBox(dx.start, dy.start, dx.stop+1, dy.stop+1) | conditional_block | |
bbox.py | import scipy.ndimage as ndi
class BBox(object):
def __init__(self, x1, y1, x2, y2):
'''
(x1, y1) is the upper left corner,
(x2, y2) is the lower right corner,
with (0, 0) being in the upper left corner.
'''
if x1 > x2: x1, x2 = x2, x1
if y1 > y2: y1, y2 = y2, y1
self.... | # Isolate the extent of each paw
# find_objects returns a list of 2-tuples: (slice(...), slice(...))
# which represents a rectangular box around the object
data_slices = ndi.find_objects(coded_paws)
return data_slices
def slice_to_bbox(slices):
for s in slices:
dy, dx = s[:2]
yield BBox(d... | coded_paws, num_paws = ndi.label(filled) | random_line_split |
story.js | import path from 'path'
import fs from 'fs'
import mkdirp from 'mkdirp'
/**
* All files in dir
*/
function getFileList (dir) {
return fs.readdirSync(dir).reduce((list, file) => {
const name = path.join(dir, file)
const isDir = fs.statSync(name).isDirectory()
if (isDir) {
list.push({
isDir... |
return list
}, [])
};
/**
* Write files recursively
*/
function writeFiles (fileName, componentName, componentPath, templatePath, dirName = '') {
if (fileName.isDir) {
fs.mkdirSync(path.join(componentPath, fileName.dirName))
fileName.files.forEach((file) => {
writeFiles(file, componentName, co... | {
list.push(file)
} | conditional_block |
story.js | import path from 'path'
import fs from 'fs'
import mkdirp from 'mkdirp'
/**
* All files in dir
*/
function getFileList (dir) {
return fs.readdirSync(dir).reduce((list, file) => {
const name = path.join(dir, file)
const isDir = fs.statSync(name).isDirectory()
if (isDir) {
list.push({
isDir... | () {
let componentPath = process.argv[process.argv.length - 1] || ''
if (componentPath.length === 0) {
console.error('Error: Specify story name, for example: npm run generate:story Todo')
return
}
const paths = componentPath.split('/')
let componentName = paths[paths.length - 1]
// Capitalize com... | generate | identifier_name |
story.js | import path from 'path'
import fs from 'fs'
import mkdirp from 'mkdirp'
/**
* All files in dir
*/
function getFileList (dir) {
return fs.readdirSync(dir).reduce((list, file) => {
const name = path.join(dir, file)
const isDir = fs.statSync(name).isDirectory()
if (isDir) {
list.push({
isDir... |
/**
* Create story folder in stories
*/
async function generate () {
let componentPath = process.argv[process.argv.length - 1] || ''
if (componentPath.length === 0) {
console.error('Error: Specify story name, for example: npm run generate:story Todo')
return
}
const paths = componentPath.split('/')... | {
if (fileName.isDir) {
fs.mkdirSync(path.join(componentPath, fileName.dirName))
fileName.files.forEach((file) => {
writeFiles(file, componentName, componentPath, templatePath, fileName.dirName)
})
} else {
const data = fs.readFileSync(path.join(templatePath, dirName, fileName), 'utf-8')
c... | identifier_body |
story.js | import path from 'path'
import fs from 'fs'
import mkdirp from 'mkdirp'
/**
* All files in dir
*/
function getFileList (dir) {
return fs.readdirSync(dir).reduce((list, file) => {
const name = path.join(dir, file)
const isDir = fs.statSync(name).isDirectory()
if (isDir) {
list.push({
isDir... | }
mkdirp(componentPath, {}, () => {
const templatePath = path.join('helpers', 'scripts', 'generator', 'templates', 'story')
// foreach template
getFileList(templatePath).forEach((fileName) => {
writeFiles(fileName, componentName, componentPath, templatePath)
})
// register component to ... | random_line_split | |
MeetingSeriesItemList-test.js | import { E2EGlobal } from './helpers/E2EGlobal';
import { E2EApp } from './helpers/E2EApp';
import { E2EMeetingSeries } from './helpers/E2EMeetingSeries';
import { E2EMinutes } from './helpers/E2EMinutes';
import { E2ETopics } from './helpers/E2ETopics';
import { formatDateISO8601 } from '../../imports/helpers/date';
... |
E2ETopics.addTopicToMinutes('some other topic');
E2ETopics.addInfoItemToTopic({subject: 'some information of another topic'}, 1);
E2ETopics.addInfoItemToTopic({subject: 'some action item of another topic', itemType: "actionItem"}, 1);
E2EMinutes.finalizeCurrentMinutes();
E2EMi... | it("displays all info- and action-items of all topics", function () {
E2ETopics.addTopicToMinutes('some topic');
E2ETopics.addInfoItemToTopic({subject: 'some information'}, 1);
E2ETopics.addInfoItemToTopic({subject: 'some action item', itemType: "actionItem"}, 1); | random_line_split |
base64.js | var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad="=";
function hex2b64(h) {
var i;
var c;
var ret = "";
for(i = 0; i+3 <= h.length; i+=3) {
c = parseInt(h.substring(i,i+3),16);
ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
}
if(i+1... |
}
if(k == 1)
ret += int2char(slop << 2);
return ret;
}
// convert a base64 string to a byte/number array
function b64toBA(s) {
//piggyback on b64tohex for now, optimize later
var h = b64tohex(s);
var i;
var a = new Array();
for(i = 0; 2*i < h.length; ++i) {
a[i] = parseI... | {
ret += int2char((slop << 2) | (v >> 4));
ret += int2char(v & 0xf);
k = 0;
} | conditional_block |
base64.js | var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad="=";
function hex2b64(h) {
var i;
var c;
var ret = "";
for(i = 0; i+3 <= h.length; i+=3) {
c = parseInt(h.substring(i,i+3),16);
ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
}
if(i+1... | (s) {
//piggyback on b64tohex for now, optimize later
var h = b64tohex(s);
var i;
var a = new Array();
for(i = 0; 2*i < h.length; ++i) {
a[i] = parseInt(h.substring(2*i,2*i+2),16);
}
return a;
}
| b64toBA | identifier_name |
base64.js | var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad="=";
function hex2b64(h) {
var i;
var c;
var ret = "";
for(i = 0; i+3 <= h.length; i+=3) {
c = parseInt(h.substring(i,i+3),16);
ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
}
if(i+1... | k = 2;
}
else if(k == 2) {
ret += int2char(slop);
ret += int2char(v >> 2);
slop = v & 3;
k = 3;
}
else {
ret += int2char((slop << 2) | (v >> 4));
ret += int2char(v & 0xf);
k = 0;
}
... | else if(k == 1) {
ret += int2char((slop << 2) | (v >> 4));
slop = v & 0xf; | random_line_split |
base64.js | var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad="=";
function hex2b64(h) |
// convert a base64 string to hex
function b64tohex(s) {
var ret = ""
var i;
var k = 0; // b64 state, 0-3
var slop;
for(i = 0; i < s.length; ++i) {
if(s.charAt(i) == b64pad) break;
v = b64map.indexOf(s.charAt(i));
if(v < 0) continue;
if(k == 0) {
ret += i... | {
var i;
var c;
var ret = "";
for(i = 0; i+3 <= h.length; i+=3) {
c = parseInt(h.substring(i,i+3),16);
ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
}
if(i+1 == h.length) {
c = parseInt(h.substring(i,i+1),16);
ret += b64map.charAt(c << 2);
}
else i... | identifier_body |
iterationWJSProviderOnlyListTest.js | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language go... | random_line_split | |
slice-2.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 ... | x[mut]; //~ ERROR cannot take a mutable slice of a value with type `Foo`
x[mut Foo..]; //~ ERROR cannot take a mutable slice of a value with type `Foo`
x[mut ..Foo]; //~ ERROR cannot take a mutable slice of a value with type `Foo`
x[mut Foo..Foo]; //~ ERROR cannot take a mutable slice of a value with ty... | x[]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo`
x[..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` | random_line_split |
slice-2.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 ... | () {
let x = Foo;
x[]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo`
x[..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
x[mut]; //~ ... | main | identifier_name |
mod.rs | //
// 0 1 0 Mnemosyne: a functional systems programming language.
// 0 0 1 (c) 2015 Hawk Weisman
// 1 1 1 hi@hawkweisman.me
//
// Mnemosyne is released under the MIT License. Please refer to
// the LICENSE file at the top-level directory of this distribution
// or at https://github.com/hawkw/mnemosyne/.
//
//!... | .take($to)
.collect::<String>() )
}
pub mod ast;
pub mod types;
pub mod annotations;
impl<'a> AnnotateTypes<'a> for Unscoped<'a, Form<'a, UnscopedState>> {
#[allow(unused_variables)]
fn annotate_types(self, scope: SymbolTable) -> Scoped<'a, Self> {
unimp... | #[macro_use]
macro_rules! indent {
($to:expr) => ( iter::repeat('\t') | random_line_split |
mod.rs | //
// 0 1 0 Mnemosyne: a functional systems programming language.
// 0 0 1 (c) 2015 Hawk Weisman
// 1 1 1 hi@hawkweisman.me
//
// Mnemosyne is released under the MIT License. Please refer to
// the LICENSE file at the top-level directory of this distribution
// or at https://github.com/hawkw/mnemosyne/.
//
//!... |
}
| {
match *self {
SymbolAnnotation::TypeDef(ref ty) =>
match *ty { Type::Prim(_) => true
, _ => false
}
, _ => false
}
} | identifier_body |
mod.rs | //
// 0 1 0 Mnemosyne: a functional systems programming language.
// 0 0 1 (c) 2015 Hawk Weisman
// 1 1 1 hi@hawkweisman.me
//
// Mnemosyne is released under the MIT License. Please refer to
// the LICENSE file at the top-level directory of this distribution
// or at https://github.com/hawkw/mnemosyne/.
//
//!... | (&self) -> bool {
match *self {
SymbolAnnotation::TypeDef(ref ty) =>
match *ty { Type::Prim(_) => true
, _ => false
}
, _ => false
}
}
}
| is_prim_type | identifier_name |
issue-30018-nopanic.rs | // run-pass
#![allow(unreachable_code)]
// More thorough regression test for Issues #30018 and #30822. This
// attempts to explore different ways that array element construction
// (for both scratch arrays and non-scratch ones) interacts with
// breaks in the control-flow, in terms of the order of evaluation of
// the ... | assert_eq!(&log.borrow()[..], &[20, 21, 22]);
log.borrow_mut().clear();
// CASE 3: (Borrow of) slice-index of array is stored in _r slot.
loop {
let _r = &[D(log, 30),
D(log, 31),
D(log, 32)][..];
break;
}
assert_eq!(&log.borrow()[..], &[30,... | {
let log = &RefCell::new(Vec::new());
// CASE 1: Fixed-size array itself is stored in _r slot.
loop {
let _r = [D(log, 10),
D(log, 11),
D(log, 12)];
break;
}
assert_eq!(&log.borrow()[..], &[10, 11, 12]);
log.borrow_mut().clear();
// CASE... | identifier_body |
issue-30018-nopanic.rs | // run-pass
#![allow(unreachable_code)]
// More thorough regression test for Issues #30018 and #30822. This
// attempts to explore different ways that array element construction
// (for both scratch arrays and non-scratch ones) interacts with
// breaks in the control-flow, in terms of the order of evaluation of
// the ... | break;
}
assert_eq!(&log.borrow()[..], &[30, 31, 32]);
log.borrow_mut().clear();
} | loop {
let _r = &[D(log, 30),
D(log, 31),
D(log, 32)][..]; | random_line_split |
issue-30018-nopanic.rs | // run-pass
#![allow(unreachable_code)]
// More thorough regression test for Issues #30018 and #30822. This
// attempts to explore different ways that array element construction
// (for both scratch arrays and non-scratch ones) interacts with
// breaks in the control-flow, in terms of the order of evaluation of
// the ... | <'a>(&'a RefCell<Vec<i32>>, i32);
impl<'a> Drop for D<'a> {
fn drop(&mut self) {
println!("Dropping D({})", self.1);
(self.0).borrow_mut().push(self.1);
}
}
fn main() {
println!("Start");
break_during_elem();
break_after_whole();
println!("Finis");
}
fn break_during_elem() {
... | D | identifier_name |
idb.filesystem.js | param {FileEntry} opt_fileEntry Optional FileEntry to initialize this
* object from.
* @constructor
* @extends {Entry}
*/
function FileEntry(opt_fileEntry) {
this.file_ = null;
Object.defineProperty(this, 'isFile', {
enumerable: true,
get: function() {
return true;
}
});
Object.defin... | {
storageType_ = type == exports.TEMPORARY ? 'Temporary' : 'Persistent';
this.name = (location.protocol + location.host).replace(/:/g, '_') +
':' + storageType_;
this.root = new DirectoryEntry();
this.root.fullPath = DIR_SEPARATOR;
this.root.filesystem = this;
this.root.name = '';
} | identifier_body | |
idb.filesystem.js | path = resolveToFullPath_(cwdFullPath, path);
// path = fs_.root.toURL() + path.substring(1);
// return path;
// };
/**
* Interface to wrap the native File interface.
*
* This interface is necessary for creating zero-length (empty) files,
* something the Filesystem API allows you to do. Unfortunately, File'... | (fileEntry) {
if (!fileEntry) {
throw Error('Expected fileEntry argument to write.');
}
var position_ = 0;
var blob_ = fileEntry.file_ ? fileEntry.file_.blob_ : null;
Object.defineProperty(this, 'position', {
get: function() {
return position_;
}
});
Object.defineProperty(this, 'lengt... | FileWriter | identifier_name |
idb.filesystem.js | };
var Base64ToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {type: contentType});
}
var parts = da... | random_line_split | ||
fillable.rs | use errors::*;
use std::cmp;
/// Fillable is a range from [0,size) that can be filled by subranges.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Fillable {
size: u64,
contents: Vec<Interval>,
}
impl Fillable {
pub fn new(size: u64) -> Self {
Fillable {
size: size,
... | if start >= self.size {
bail!("first_unfilled_starting_at start:{} >= size:{}",
start,
self.size);
}
if self.contents.is_empty() {
return Ok(Some(start));
}
for interval in self.contents.iter() {
if interval.... |
/// Get the index of the first unfilled byte starting at offset.
/// Returns some offset in [start, self.size)
/// Returns None if everything from then on is filled.
pub fn first_unfilled_starting_at(&self, start: u64) -> Result<Option<u64>> { | random_line_split |
fillable.rs | use errors::*;
use std::cmp;
/// Fillable is a range from [0,size) that can be filled by subranges.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Fillable {
size: u64,
contents: Vec<Interval>,
}
impl Fillable {
pub fn new(size: u64) -> Self {
Fillable {
size: size,
... | (&self) -> u64 {
return self.size;
}
pub fn has(&self, n: u64) -> bool {
for i in self.contents.iter() {
if n < i.end {
return i.start <= n;
}
}
return false;
}
/// Fill the range [a, b)
/// Returns whether this piece is _newl... | size | identifier_name |
fillable.rs | use errors::*;
use std::cmp;
/// Fillable is a range from [0,size) that can be filled by subranges.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Fillable {
size: u64,
contents: Vec<Interval>,
}
impl Fillable {
pub fn new(size: u64) -> Self {
Fillable {
size: size,
... |
pub fn is_empty(&self) -> bool {
self.contents.len() == 0
}
pub fn size(&self) -> u64 {
return self.size;
}
pub fn has(&self, n: u64) -> bool {
for i in self.contents.iter() {
if n < i.end {
return i.start <= n;
}
}
... | {
let r = self.contents.len() == 1 && self.contents[0].start == 0 && self.contents[0].end == self.size;
// println!("is_full {:?} = {}", self, r);
return r;
} | identifier_body |
views.py | from django.http import HttpResponse, Http404
from django.template.loader import get_template
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage
from django.utils.translation import ugettext as _
from tagging.models import Tag
from messages.models import Message
from sett... |
elif filter == _('posts'):
c['filter'] = 'posts'
posts = Post.objects.all()
objects = Contribution.objects.filter(post__in=posts).select_related('user', 'question', 'revision', 'collection', 'post', 'tagaction')
else:
objects = Contribution.objects.all().select_related('user', 'question', 'revision... | c['filter'] = 'collections'
collections = Collection.objects.all()
objects = Contribution.objects.filter(collection__in=collections).select_related('user', 'question', 'revision', 'collection', 'post', 'tagaction') | conditional_block |
views.py | from django.http import HttpResponse, Http404
from django.template.loader import get_template
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage
from django.utils.translation import ugettext as _
from tagging.models import Tag
from messages.models import Message
from sett... | objects = Contribution.objects.filter(collection__in=collections).select_related('user', 'question', 'revision', 'collection', 'post', 'tagaction')
elif filter == _('posts'):
c['filter'] = 'posts'
posts = Post.objects.all()
objects = Contribution.objects.filter(post__in=posts).select_related('user', '... | """
Serves the home page for logged-in users
"""
t = get_template('home_members.html')
c = RequestContext(request)
filter = request.GET.get(_('filter'), False)
# behold some serious django-fu!
if filter == _('questions'):
c['filter'] = 'questions'
questions = Question.objects.all()
objec... | identifier_body |
views.py | from django.http import HttpResponse, Http404
from django.template.loader import get_template
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage
from django.utils.translation import ugettext as _
from tagging.models import Tag
from messages.models import Message
from sett... | (request):
"""
Serves the home page, which depends on whether the user is logged in or not.
"""
if request.user.is_authenticated():
return participate(request)
else:
c = RequestContext(request)
if lang == "nl":
c['frontpage'] = 'frontpage_nl.html'
else:
c['frontpage'] = 'frontpage_... | home | identifier_name |
views.py | from django.http import HttpResponse, Http404
from django.template.loader import get_template
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage
from django.utils.translation import ugettext as _
from tagging.models import Tag
from messages.models import Message
from sett... | c['filter'] = 'posts'
posts = Post.objects.all()
objects = Contribution.objects.filter(post__in=posts).select_related('user', 'question', 'revision', 'collection', 'post', 'tagaction')
else:
objects = Contribution.objects.all().select_related('user', 'question', 'revision', 'collection', 'post', 'taga... | elif filter == _('posts'): | random_line_split |
issue-2804.rs | // Copyright 2012-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... | }
fn lookup(table: json::JsonObject, key: String, default: String) -> String
{
match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => {
s.to_string()
}
option::Some(value) => {
println!("{} was expected to be a string but is a {:?}", key, value);
... |
enum object {
bool_value(bool),
int_value(i64), | random_line_split |
issue-2804.rs |
// Copyright 2012-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-M... | {
bool_value(bool),
int_value(i64),
}
fn lookup(table: json::JsonObject, key: String, default: String) -> String
{
match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => {
s.to_string()
}
option::Some(value) => {
println!("{} was expected... | object | identifier_name |
issue-2804.rs |
// Copyright 2012-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-M... |
fn add_interface(_store: int, managed_ip: String, data: json::Json) -> (String, object)
{
match &data {
&json::Object(ref interface) => {
let name = lookup(interface.clone(),
"ifDescr".to_string(),
"".to_string());
let lab... | {
match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => {
s.to_string()
}
option::Some(value) => {
println!("{} was expected to be a string but is a {:?}", key, value);
default
}
option::None => {
default
... | identifier_body |
test_products.py | from sympy import (symbols, product, factorial, rf, sqrt, cos, | assert product(2, (k, a, n)) == 2**(n-a+1)
assert product(k, (k, 1, n)) == factorial(n)
assert product(k**3, (k, 1, n)) == factorial(n)**3
assert product(k+1, (k, 0, n-1)) == factorial(n)
assert product(k+1, (k, a, n-1)) == rf(1+a, n-a)
assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)... | Function, Product, Rational)
a, k, n = symbols('a,k,n', integer=True)
def test_simple_products(): | random_line_split |
test_products.py | from sympy import (symbols, product, factorial, rf, sqrt, cos,
Function, Product, Rational)
a, k, n = symbols('a,k,n', integer=True)
def test_simple_products():
assert product(2, (k, a, n)) == 2**(n-a+1)
assert product(k, (k, 1, n)) == factorial(n)
assert product(k**3, (k, 1, n)) == fac... | from sympy.abc import i, n
# 1710
a = Function('a')
assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n))
# 1711
assert product(2**i, (i, 1, n)) == 2**(n/2 + n**2/2) | identifier_body | |
test_products.py | from sympy import (symbols, product, factorial, rf, sqrt, cos,
Function, Product, Rational)
a, k, n = symbols('a,k,n', integer=True)
def test_simple_products():
assert product(2, (k, a, n)) == 2**(n-a+1)
assert product(k, (k, 1, n)) == factorial(n)
assert product(k**3, (k, 1, n)) == fac... | ():
# Wallis product
assert product((4*k)**2 / (4*k**2-1), (k, 1, n)) == \
4**n*factorial(n)**2/rf(Rational(1, 2), n)/rf(Rational(3, 2), n)
# Euler's product formula for sin
assert product(1 + a/k**2, (k, 1, n)) == \
rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2
def test__eva... | test_special_products | identifier_name |
monkey-patch-turbolinks.js | const Turbolinks = require('turbolinks');
// Monkey patch Turbolinks to render 403, 404 & 500 normally
// See https://github.com/turbolinks/turbolinks/issues/179
Turbolinks.HttpRequest.prototype.requestLoaded = function() {
return this.endRequest(function() {
var code = this.xhr.status;
if (200 <= ... | var nonceTag = document.querySelector("meta[name='csp-nonce']");
if (nonceTag) event.data.xhr.setRequestHeader('X-Turbolinks-Nonce', nonceTag.content);
});
document.addEventListener('turbolinks:before-cache', function() {
Array.prototype.forEach.call(document.querySelectorAll('script[nonce]'), function(elem... | document.addEventListener('turbolinks:request-start', function(event) { | random_line_split |
mutex.rs | use futures::channel::mpsc;
use futures::executor::block_on;
use futures::future::{ready, FutureExt};
use futures::lock::Mutex;
use futures::stream::StreamExt;
use futures::task::{Context, SpawnExt};
use futures_test::future::FutureTestExt;
use futures_test::task::{new_count_waker, panic_context};
use std::sync::Arc;
... | () {
let mutex = Mutex::new(());
for _ in 0..10 {
assert!(mutex.lock().poll_unpin(&mut panic_context()).is_ready());
}
}
#[test]
fn mutex_wakes_waiters() {
let mutex = Mutex::new(());
let (waker, counter) = new_count_waker();
let lock = mutex.lock().poll_unpin(&mut panic_context());
... | mutex_acquire_uncontested | identifier_name |
mutex.rs | use futures::channel::mpsc;
use futures::executor::block_on;
use futures::future::{ready, FutureExt};
use futures::lock::Mutex;
use futures::stream::StreamExt;
use futures::task::{Context, SpawnExt};
use futures_test::future::FutureTestExt;
use futures_test::task::{new_count_waker, panic_context};
use std::sync::Arc;
... | assert_eq!(num_tasks, *lock);
})
} | let lock = mutex.lock().await; | random_line_split |
mutex.rs | use futures::channel::mpsc;
use futures::executor::block_on;
use futures::future::{ready, FutureExt};
use futures::lock::Mutex;
use futures::stream::StreamExt;
use futures::task::{Context, SpawnExt};
use futures_test::future::FutureTestExt;
use futures_test::task::{new_count_waker, panic_context};
use std::sync::Arc;
... |
#[test]
fn mutex_contested() {
let (tx, mut rx) = mpsc::unbounded();
let pool = futures::executor::ThreadPool::builder()
.pool_size(16)
.create()
.unwrap();
let tx = Arc::new(tx);
let mutex = Arc::new(Mutex::new(0));
let num_tasks = 1000;
for _ in 0..num_tasks {
... | {
let mutex = Mutex::new(());
let (waker, counter) = new_count_waker();
let lock = mutex.lock().poll_unpin(&mut panic_context());
assert!(lock.is_ready());
let mut cx = Context::from_waker(&waker);
let mut waiter = mutex.lock();
assert!(waiter.poll_unpin(&mut cx).is_pending());
assert_e... | identifier_body |
enc_dec.rs | 016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::str::from_utf8;
use crate::error::Error;
use super::Resu... |
s >>= 6;
s |= (dec as u32) << 26;
processed += 1;
if processed == len {
break;
}
}
if processed < len {
return Err(Error::InsufficientLength);
}
Ok(s >> (32 - 6 * len))
}
pub fn encode_val(mut val: u32, mut nhex: usize) -> String {
let mut val_arr = [0u8; 4];
if nhex > 4 {
nhex = 4... | {
return Err(Error::EncodingError);
} | conditional_block |
enc_dec.rs | 2016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::str::from_utf8;
use crate::error::Error;
use super::Res... | if dec_idx == decbuf.len() {
break;
}
cbuild = dec & (0x3F >> cpos);
}
cpos += 2;
if cpos > 6 {
cpos = 0;
}
}
Ok(())
}
pub fn bcrypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_encode(bs, &BCRYPT_HASH64)
}
pub fn crypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_enco... | {
let mut cbuild = 0u8;
let mut cpos = 0;
let mut dec_idx = 0;
for b in enc.chars() {
let b = b as u32 - 0x20;
if b > 0x60 {
return Err(Error::EncodingError);
}
let dec = BCRYPT_HASH64_ENC_MAP[b as usize];
if dec == 64 {
return Err(Error::EncodingError);
}
if cpos == 0 {
cbuild = d... | identifier_body |
enc_dec.rs | 2016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::str::from_utf8;
use crate::error::Error;
use super::Res... | (enc: &str, decbuf: &mut [u8]) -> Result<()> {
let mut cbuild = 0u8;
let mut cpos = 0;
let mut dec_idx = 0;
for b in enc.chars() {
let b = b as u32 - 0x20;
if b > 0x60 {
return Err(Error::EncodingError);
}
let dec = BCRYPT_HASH64_ENC_MAP[b as usize];
if dec == 64 {
return Err(Error::Encod... | bcrypt_hash64_decode | identifier_name |
enc_dec.rs | 2016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::str::from_utf8;
use crate::error::Error;
use super::Res... | if dec_idx == decbuf.len() {
break;
}
cbuild = dec & (0x3F >> cpos);
}
cpos += 2;
if cpos > 6 {
cpos = 0;
}
}
Ok(())
}
pub fn bcrypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_encode(bs, &BCRYPT_HASH64)
}
pub fn crypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_encod... | decbuf[dec_idx] = cbuild;
dec_idx += 1; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.