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 |
|---|---|---|---|---|
es6-shim.js | (function(definition) {
// RequireJS.
if (typeof define === 'function') {
define(definition);
// CommonJS and <script>.
} else {
definition();
}
})(function() {
'use strict';
var globall = (typeof global === 'undefined') ? window : global;
var global_isNaN = globall.isNaN;
var global_isFinite... |
defineProperties(Map.prototype, {
get: function(key) {
var index = indexOfIdentical(this.keys, key);
return index < 0 ? undefined : this.values[index];
},
has: function(key) {
return indexOfIdentical(this.keys, key) >= 0;
},
set: function(k... | {
if (!(this instanceof Map)) return new Map;
defineProperty(this, 'keys', []);
defineProperty(this, 'values', []);
} | identifier_body |
es6-shim.js | (function(definition) {
// RequireJS.
if (typeof define === 'function') {
define(definition);
// CommonJS and <script>.
} else {
definition();
}
})(function() {
'use strict';
var globall = (typeof global === 'undefined') ? window : global;
var global_isNaN = globall.isNaN;
var global_isFinite... | },
of: function() {
return Array.prototype.slice.call(arguments);
}
});
defineProperties(Number, {
isInteger: function(value) {
return typeof value === 'number' && global_isFinite(value) &&
value > -9007199254740992 && value < 9007199254740992 &&
Math.floor(value) === ... | return array; | random_line_split |
es6-shim.js | (function(definition) {
// RequireJS.
if (typeof define === 'function') {
define(definition);
// CommonJS and <script>.
} else {
definition();
}
})(function() {
'use strict';
var globall = (typeof global === 'undefined') ? window : global;
var global_isNaN = globall.isNaN;
var global_isFinite... | () {
if (!(this instanceof Set)) return new Set;
defineProperty(this, 'map', Map());
}
defineProperties(Set.prototype, {
has: function(key) {
return this.map.has(key);
},
add: function(key) {
this.map.set(key, true);
},
'delete':... | Set | identifier_name |
es6-shim.js | (function(definition) {
// RequireJS.
if (typeof define === 'function') {
define(definition);
// CommonJS and <script>.
} else |
})(function() {
'use strict';
var globall = (typeof global === 'undefined') ? window : global;
var global_isNaN = globall.isNaN;
var global_isFinite = globall.isFinite;
var defineProperty = function(object, name, method) {
if (!object[name]) {
Object.defineProperty(object, name, {
configu... | {
definition();
} | conditional_block |
login.module.spec.js | 'use strict';
describe('LoginController', function () {
// Load the parent app
beforeEach(module('demoSite'));
var $controller;
var $scope, controller, $window;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
$scope = {};
$window = { location: {}... | }
});
it('should handle lack of connection to the server', function () {
expect($scope.showError).toBe(false);
$scope.handleGetURLError();
expect($scope.errorMessage).toBe($scope.errorMessages["no_connection"]);
expect($scope.showError).toBe(... | $scope.showErrorFromCode(property);
expect($scope.errorMessage).toBe($scope.errorMessages[property]);
expect($scope.showError).toBe(true);
}
| conditional_block |
login.module.spec.js | 'use strict';
describe('LoginController', function () {
// Load the parent app
beforeEach(module('demoSite'));
var $controller;
var $scope, controller, $window;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
$scope = {};
$window = { location: {}... | dataHasReturned = false;
returnedData = new Object();
});
it('should handle manually closing of the popup window', function () {
$scope.popupWindow = window.open();
$scope.popupWindow.close();
$scope.pollPopupForCompletedAuth();
e... | describe('polling framework', function () {
beforeEach(function () {
// Because the framework utilizes a popup, these variables are NOT inside the controller. | random_line_split |
views.py | from app import app, grabber, merge, segment
from flask import render_template, request, url_for, jsonify
import cv2
import numpy as np
import os, re
def rm(dir, pattern):
for f in os.listdir(dir):
|
@app.route('/')
@app.route('/index')
def home():
return render_template('index.html')
@app.route('/grabber/', methods=['POST'])
def doGrabber():
# clean up folders
rm('app/static/img', 'dg*')
rm('app/ma_prediction_400','dg*')
data = request.form
lat = data['lat']
lon = data['lon']
z... | if re.search(pattern, f):
os.remove(os.path.join(dir, f)) | conditional_block |
views.py | from app import app, grabber, merge, segment
from flask import render_template, request, url_for, jsonify
import cv2
import numpy as np
import os, re
def rm(dir, pattern):
for f in os.listdir(dir):
if re.search(pattern, f):
os.remove(os.path.join(dir, f))
@app.route('/')
@app.route('/index')
d... |
# 'smart' means that the image went through the neural net prediction script
smart_contours = segment.predict(time,'app/ma_prediction_400/dg%s.png'%(time), 'app/static/img/nn_dg'+time+'.png')
smart_areas = segment.get_areas(smart_contours.values())
# 'dumb' meanas that the segmentation was on the orig... |
# get the location from digital globe
g = grabber.Grabber('app/static/img', token,'png')
time = g.grab(lat, lon, zoom) | random_line_split |
views.py | from app import app, grabber, merge, segment
from flask import render_template, request, url_for, jsonify
import cv2
import numpy as np
import os, re
def | (dir, pattern):
for f in os.listdir(dir):
if re.search(pattern, f):
os.remove(os.path.join(dir, f))
@app.route('/')
@app.route('/index')
def home():
return render_template('index.html')
@app.route('/grabber/', methods=['POST'])
def doGrabber():
# clean up folders
rm('app/static/im... | rm | identifier_name |
views.py | from app import app, grabber, merge, segment
from flask import render_template, request, url_for, jsonify
import cv2
import numpy as np
import os, re
def rm(dir, pattern):
for f in os.listdir(dir):
if re.search(pattern, f):
os.remove(os.path.join(dir, f))
@app.route('/')
@app.route('/index')
d... | dumb_areas = segment.get_areas(dumb_contours.values())
# uses 'smart' locations to pick out contours in the 'dumb' image
buildings = merge.intersect(smart_contours, dumb_contours)
merge.mkimage('app/static/img/dg'+time+'.png','app/static/img/merge_dg'+time+'.png', buildings)
areas = segment.get_are... | rm('app/static/img', 'dg*')
rm('app/ma_prediction_400','dg*')
data = request.form
lat = data['lat']
lon = data['lon']
zoom = data['zoom']
with open('app/static/secrets.txt') as f: token = f.read()
# get the location from digital globe
g = grabber.Grabber('app/static/img', token,'png')... | identifier_body |
__init__.py | #!/usr/bin/env python
# -*- coding: UTF8 -*-
# | # Provides access to portaudio.
# Copyright (C) 2010 Josiah Gordon <josiahg@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | random_line_split | |
urls.py | # Copyright 2014 Dev in Cachu authors. All rights reserved. | from django.conf import settings
from django.conf.urls import include, patterns, url
from django.views.decorators import csrf
from django.views.generic import base
from django.contrib import admin
admin.autodiscover()
from devincachu.destaques import views as dviews
from devincachu.inscricao import views as iviews
fr... | # Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
| random_line_split |
urls.py | # Copyright 2014 Dev in Cachu authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.views.decorators import csrf
from django.views.generic impor... | urlpatterns += patterns("",
url(r"^media/(?P<path>.*)$",
"django.views.static.serve",
{"document_root": settings.MEDIA_ROOT}),
) | conditional_block | |
macro-crate-cannot-read-embedded-ident.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 = 0;
assert_eq!(3, forged_ident!());
} | identifier_body | |
macro-crate-cannot-read-embedded-ident.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 ... | // aux-build:macro_crate_test.rs
// ignore-stage1
// error-pattern: unknown start of token: \u{0}
// Issue #15750 and #15962 : this test is checking that the standard
// parser rejects embedded idents. pnkfelix did not want to attempt
// to make a test file that itself used the embedded ident input form,
// since he ... | random_line_split | |
macro-crate-cannot-read-embedded-ident.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 = 0;
assert_eq!(3, forged_ident!());
}
| main | identifier_name |
react-table-config.d.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | UseRowSelectState,
UseRowStateCellProps,
UseRowStateInstanceProps,
UseRowStateOptions,
UseRowStateRowProps,
UseRowStateState,
UseSortByColumnOptions,
UseSortByColumnProps,
UseSortByHooks,
UseSortByInstanceProps,
UseSortByOptions,
UseSortByState,
} from 'react-table';
import { ColumnSizer } from ... | random_line_split | |
package.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Blueprint, render_template, Markup, url_for
from flask_toolbox.models import Package
package_page = Blueprint('package_page', __name__,
template_folder='templates')
@package_page.route(... | return render_template(
'score.html', package=the_package, flask=flask,
related_packages=related_packages, sidebar_title=sidebar_title) | random_line_split | |
package.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Blueprint, render_template, Markup, url_for
from flask_toolbox.models import Package
package_page = Blueprint('package_page', __name__,
template_folder='templates')
@package_page.route(... | flask = Package.query.filter_by(name="Flask").first()
the_package = Package.query.filter_by(name=package).first_or_404()
category = the_package.category
related_packages = [item.name for item in category.packages.order_by(Package.score.desc()).all()
if item.name != package]
sideb... | identifier_body | |
package.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Blueprint, render_template, Markup, url_for
from flask_toolbox.models import Package
package_page = Blueprint('package_page', __name__,
template_folder='templates')
@package_page.route(... | (package):
the_package = Package.query.filter_by(name=package).first_or_404()
category = the_package.category
related_packages = [item.name for item in category.packages.order_by(Package.score.desc()).all()
if item.name != package]
sidebar_title = (
Markup("Other related ... | show | identifier_name |
forms.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... |
def handle(self, request, data):
try:
api.add_tenant_user_role(request,
data['tenant_id'],
data['user_id'],
data['role_id'])
messages.success(request, _('Successfully adde... | roles = kwargs.pop('roles')
super(AddUser, self).__init__(*args, **kwargs)
role_choices = [(role.id, role.name) for role in roles]
self.fields['role_id'].choices = role_choices | identifier_body |
forms.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | role_id = forms.ChoiceField(label=_("Role"))
def __init__(self, *args, **kwargs):
roles = kwargs.pop('roles')
super(AddUser, self).__init__(*args, **kwargs)
role_choices = [(role.id, role.name) for role in roles]
self.fields['role_id'].choices = role_choices
def handle(self... |
class AddUser(forms.SelfHandlingForm):
tenant_id = forms.CharField(widget=forms.widgets.HiddenInput())
user_id = forms.CharField(widget=forms.widgets.HiddenInput()) | random_line_split |
forms.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | (self, *args, **kwargs):
roles = kwargs.pop('roles')
super(AddUser, self).__init__(*args, **kwargs)
role_choices = [(role.id, role.name) for role in roles]
self.fields['role_id'].choices = role_choices
def handle(self, request, data):
try:
api.add_tenant_user_rol... | __init__ | identifier_name |
cache.rs | use std::os::raw::c_void;
use std::ptr;
use std::sync::atomic::{AtomicPtr, Ordering};
use crate::runtime::{Class, Sel, self};
/// Allows storing a `Sel` in a static and lazily loading it.
#[doc(hidden)]
pub struct CachedSel {
ptr: AtomicPtr<c_void>
}
impl CachedSel {
/// Constructs a new `CachedSel`.
pub... |
}
| {
// `Relaxed` should be fine since `objc_getClass` is thread-safe.
let ptr = self.ptr.load(Ordering::Relaxed);
if ptr.is_null() {
let cls = runtime::objc_getClass(name.as_ptr() as *const _);
self.ptr.store(cls as *mut _, Ordering::Relaxed);
cls.as_ref()
... | identifier_body |
cache.rs | use std::os::raw::c_void;
use std::ptr;
use std::sync::atomic::{AtomicPtr, Ordering};
use crate::runtime::{Class, Sel, self};
/// Allows storing a `Sel` in a static and lazily loading it.
#[doc(hidden)]
pub struct CachedSel {
ptr: AtomicPtr<c_void>
}
impl CachedSel {
/// Constructs a new `CachedSel`.
pub... | #[inline(always)]
pub unsafe fn get(&self, name: &str) -> Option<&'static Class> {
// `Relaxed` should be fine since `objc_getClass` is thread-safe.
let ptr = self.ptr.load(Ordering::Relaxed);
if ptr.is_null() {
let cls = runtime::objc_getClass(name.as_ptr() as *const _);
... |
/// Returns the cached class. If no class is yet cached, gets one with
/// the given name and stores it. | random_line_split |
cache.rs | use std::os::raw::c_void;
use std::ptr;
use std::sync::atomic::{AtomicPtr, Ordering};
use crate::runtime::{Class, Sel, self};
/// Allows storing a `Sel` in a static and lazily loading it.
#[doc(hidden)]
pub struct CachedSel {
ptr: AtomicPtr<c_void>
}
impl CachedSel {
/// Constructs a new `CachedSel`.
pub... |
}
}
/// Allows storing a `Class` reference in a static and lazily loading it.
#[doc(hidden)]
pub struct CachedClass {
ptr: AtomicPtr<Class>
}
impl CachedClass {
/// Constructs a new `CachedClass`.
pub const fn new() -> CachedClass {
CachedClass {
ptr: AtomicPtr::new(ptr::null_mut(... | {
Sel::from_ptr(ptr)
} | conditional_block |
cache.rs | use std::os::raw::c_void;
use std::ptr;
use std::sync::atomic::{AtomicPtr, Ordering};
use crate::runtime::{Class, Sel, self};
/// Allows storing a `Sel` in a static and lazily loading it.
#[doc(hidden)]
pub struct | {
ptr: AtomicPtr<c_void>
}
impl CachedSel {
/// Constructs a new `CachedSel`.
pub const fn new() -> CachedSel {
CachedSel {
ptr: AtomicPtr::new(ptr::null_mut())
}
}
/// Returns the cached selector. If no selector is yet cached, registers
/// one with the given name... | CachedSel | identifier_name |
comment.py | #
# livef1
#
# f1comment.py - classes to store the live F1 comments
#
# Copyright (c) 2014 Marc Bertens <marc.bertens@pe2mbs.nl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eit... | ( self, div_tag_name ):
output = ""
for elem in self.lines:
if elem.clock:
sep = "-"
else:
sep = ""
#endif
output = "<tr valign='top'><td>%s</td><td>%s</td><td>%s</td></tr>" % (
... | gethtml | identifier_name |
comment.py | #
# livef1
#
# f1comment.py - classes to store the live F1 comments
#
# Copyright (c) 2014 Marc Bertens <marc.bertens@pe2mbs.nl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eit... |
def reset( self ):
self.timestamp = 0
self.clock = ""
self.text = ""
return
class F1Commentary( object ):
def __init__( self, log ):
self.lines = []
self.log = log
return
def reset( self ):
self.lines... | self.timestamp = ts
self.clock = c
self.text = t
return | identifier_body |
comment.py | #
# livef1
#
# f1comment.py - classes to store the live F1 comments
#
# Copyright (c) 2014 Marc Bertens <marc.bertens@pe2mbs.nl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eit... |
def GetCommentary():
global comment
if comment == None:
comment = F1Commentary( logging.getLogger( 'live-f1' ) )
return comment
# end def | random_line_split | |
comment.py | #
# livef1
#
# f1comment.py - classes to store the live F1 comments
#
# Copyright (c) 2014 Marc Bertens <marc.bertens@pe2mbs.nl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eit... |
self.lines.append( F1Text( new.timestamp, new.clock, new.text ) )
return
def dump( self ):
for elem in self.lines:
self.log.info( "Commentary : %s" % ( elem.text ) )
# next
return
comment = None
def GetCommentary():
global comment
... | secs = new.timestamp % 60
mins = new.timestamp // 60
hours = 0
if ( mins > 60 ):
hours = mins // 60
mins = mins % 60
# endif
# add time stamp
new.clock = "%02i:%02i" % ( hours, mins ) | conditional_block |
test_submit_group.py | # This file is part of the Simulation Manager project for VecNet.
# For copyright and licensing information about this project, see the
# NOTICE.txt and LICENSE.md files in its top-level directory; they are
# available at https://github.com/vecnet/simulation-manager
#
# This Source Code Form is subject to the terms of ... |
def assertGroupScriptStatus(self, expected_status):
group = SimulationGroup.objects.get(id=self.group_id)
self.assertEqual(group.script_status, expected_status)
def generate_job_id():
return str(random.randint(1, 100000)) | self.check_expected_state = None | conditional_block |
test_submit_group.py | # This file is part of the Simulation Manager project for VecNet.
# For copyright and licensing information about this project, see the
# NOTICE.txt and LICENSE.md files in its top-level directory; they are
# available at https://github.com/vecnet/simulation-manager
#
# This Source Code Form is subject to the terms of ... | (self, expected_status):
group = SimulationGroup.objects.get(id=self.group_id)
self.assertEqual(group.script_status, expected_status)
def generate_job_id():
return str(random.randint(1, 100000)) | assertGroupScriptStatus | identifier_name |
test_submit_group.py | # This file is part of the Simulation Manager project for VecNet.
# For copyright and licensing information about this project, see the
# NOTICE.txt and LICENSE.md files in its top-level directory; they are
# available at https://github.com/vecnet/simulation-manager
#
# This Source Code Form is subject to the terms of ... |
def expect_cached_files(self):
"""
Confirm that the submission script cached input files.
"""
self.assertGroupScriptStatus(submission_status.CACHING_FILES)
self.assertTrue(input_files.TestingApi.add_to_cache_mock.called)
args, kwargs = input_files.TestingApi.add_to_... | """
Confirm that the submission script was started.
"""
self.assertGroupScriptStatus(submission_status.STARTED_SCRIPT)
self.check_expected_state = self.expect_cached_files | identifier_body |
test_submit_group.py | # This file is part of the Simulation Manager project for VecNet.
# For copyright and licensing information about this project, see the
# NOTICE.txt and LICENSE.md files in its top-level directory; they are
# available at https://github.com/vecnet/simulation-manager
#
# This Source Code Form is subject to the terms of ... | test_utils.Mocks.submit_job.reset_mock()
if self.simulations_created < len(self.sim_group.simulations):
test_utils.Mocks.submit_job.return_value = generate_job_id()
else:
self.check_expected_state = None
def assertGroupScriptStatus(self, expected_status):
gr... | executable, working_dir, cmd_args = args[0], args[1], args[2:]
self.assertEqual(executable, sys.executable)
self.assertEqual(working_dir, simulation.working_dir)
self.assertEqual(list(cmd_args), [self.simulation_script])
self.assertEqual(simulation.batch_job_id, test_utils.Mocks.... | random_line_split |
Mobile-Keyboard.js | // add/remove body classes based on viewport width
var bodyViewportClasses = function() {
if(document.getElementById("mobileNavToggle"))
{
$('#mobileNavToggle').remove();
}
// testing the display property on the element
var nav_display = $('.off-canvas-nav-links').css('display');
// tes... |
// testing for display:none (changed in css via media queries)
if (nav_display === 'none') {
$("body").removeClass("active-sidebar active-nav small-screen")
.addClass("multi-column");
}
}
// function for sidebar display toggle
var showSidebar = function() {
$('body').removeClass("a... | {
$("body").removeClass("multi-column").addClass("small-screen");
} | conditional_block |
Mobile-Keyboard.js | // add/remove body classes based on viewport width
var bodyViewportClasses = function() {
if(document.getElementById("mobileNavToggle"))
{
$('#mobileNavToggle').remove();
}
// testing the display property on the element
var nav_display = $('.off-canvas-nav-links').css('display');
// tes... | // Toggle for sidebar
$('.sidebar-button').click(function(e) {
e.preventDefault();
showSidebar();
});
// Escape Key to Close
$(document).keyup(function(e) {
if (e.keyCode == 27 ) {
showSidebar();
}
});
bodyViewportClasses();
})... | random_line_split | |
encode.rs | use criterion::*;
use std::io::Cursor;
fn encode_buffer(c: &mut Criterion) {
let buf = (0..32_768).map(|c| (c % 256) as u8).collect::<Vec<u8>>();
let length = buf.len();
let mut output = Vec::with_capacity(32_768 * 102 / 100);
let mut group = c.benchmark_group("encode");
group
.bench_functi... | (c: &mut Criterion) {
let mut group = c.benchmark_group("encode_stream");
group
.bench_function("encode_stream 32k", |b| {
b.iter(|| {
let buf = (0..32_768).map(|c| (c % 256) as u8).collect::<Vec<u8>>();
assert_eq!(32_768, buf.len());
let lengt... | encode_stream | identifier_name |
encode.rs | use criterion::*;
use std::io::Cursor;
fn encode_buffer(c: &mut Criterion) {
let buf = (0..32_768).map(|c| (c % 256) as u8).collect::<Vec<u8>>();
let length = buf.len();
let mut output = Vec::with_capacity(32_768 * 102 / 100);
let mut group = c.benchmark_group("encode");
group
.bench_functi... | assert_eq!(32_768, buf.len());
let length = buf.len();
let options = yenc::EncodeOptions::new().end(length as u64).begin(1);
let output = vec![0; length * 110 / 100];
let mut input_r = Cursor::new(buf);
let mut output_r = Cu... | group
.bench_function("encode_stream 32k", |b| {
b.iter(|| {
let buf = (0..32_768).map(|c| (c % 256) as u8).collect::<Vec<u8>>(); | random_line_split |
encode.rs | use criterion::*;
use std::io::Cursor;
fn encode_buffer(c: &mut Criterion) {
let buf = (0..32_768).map(|c| (c % 256) as u8).collect::<Vec<u8>>();
let length = buf.len();
let mut output = Vec::with_capacity(32_768 * 102 / 100);
let mut group = c.benchmark_group("encode");
group
.bench_functi... |
criterion_group!(benches, encode_buffer, encode_stream);
criterion_main!(benches);
| {
let mut group = c.benchmark_group("encode_stream");
group
.bench_function("encode_stream 32k", |b| {
b.iter(|| {
let buf = (0..32_768).map(|c| (c % 256) as u8).collect::<Vec<u8>>();
assert_eq!(32_768, buf.len());
let length = buf.len();
... | identifier_body |
atomic.rs | /// Copyright (c) Migrant Coder, 2015
/// All rights reserved.
use std::boxed;
use std::boxed::Box;
use std::mem;
use std::num::ToPrimitive;
use std::ops::{ Deref, DerefMut };
use std::sync::atomic::{ AtomicPtr, Ordering };
/// A non-owning pointer type that supports tagging and atomic compare and set.
pub struct Ta... | (&self) -> u64 {
unsafe { mem::transmute(self.value()) }
}
/// Return the tag value.
pub fn get_tag(&self) -> u16 {
unsafe {
let ptr = self.ptr.load(Ordering::Relaxed);
let u64ptr: u64 = mem::transmute(ptr);
(u64ptr >> 48).to_u16().unwrap()
}
}
/// Set the tag value.
pub fn s... | to_u64 | identifier_name |
atomic.rs | /// Copyright (c) Migrant Coder, 2015
/// All rights reserved.
use std::boxed;
use std::boxed::Box;
use std::mem;
use std::num::ToPrimitive;
use std::ops::{ Deref, DerefMut };
use std::sync::atomic::{ AtomicPtr, Ordering };
/// A non-owning pointer type that supports tagging and atomic compare and set.
pub struct Ta... |
}
pub fn is_nil(&self) -> bool {
unsafe { mem::transmute(self.get()) == 0u64 }
}
/// Set the value.
pub fn set(&self, ptr: *mut T) {
self.ptr.store(ptr, Ordering::Relaxed);
}
/// Return the untagged pointer value.
pub fn get(&self) -> *mut T {
unsafe {
let ptr = self.ptr.load(Order... | {
let value = self.get();
unsafe { self.set(mem::transmute(0x0u64)); }
Some(unsafe { Box::from_raw(value) })
} | conditional_block |
atomic.rs | /// Copyright (c) Migrant Coder, 2015
/// All rights reserved.
use std::boxed;
use std::boxed::Box;
use std::mem;
use std::num::ToPrimitive;
use std::ops::{ Deref, DerefMut };
use std::sync::atomic::{ AtomicPtr, Ordering };
/// A non-owning pointer type that supports tagging and atomic compare and set.
pub struct Ta... |
}
impl<T> Deref for TaggedPtr<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.get() }
}
}
impl<T> DerefMut for TaggedPtr<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { & mut *self.get() }
}
}
impl<T> Clone for TaggedPtr<T> {
fn clone(&self) -> Self {
Tag... | {
self.ptr.load(Ordering::Relaxed) == rhs.ptr.load(Ordering::Relaxed)
} | identifier_body |
atomic.rs | /// Copyright (c) Migrant Coder, 2015
/// All rights reserved.
use std::boxed;
use std::boxed::Box;
use std::mem;
use std::num::ToPrimitive;
use std::ops::{ Deref, DerefMut };
use std::sync::atomic::{ AtomicPtr, Ordering };
/// A non-owning pointer type that supports tagging and atomic compare and set.
pub struct Ta... | }
impl<T> Clone for TaggedPtr<T> {
fn clone(&self) -> Self {
TaggedPtr::from_raw(self.value())
}
}
unsafe impl<T> Sync for TaggedPtr<T> {} | unsafe { & mut *self.get() }
} | random_line_split |
DevProjects.js | import React, {Component} from "react";
import { addAnimationId } from './modules/animationFunctions.js'
import '../scss/dev-projects.css';
import close from "../assets/close.png";
export default class DevProjects extends Component {
componentDidMount() { addAnimationId('dev-projects', 'dev-section-fadein') }
| () {
return (
<div id="dev-projects">
<i onClick={this.props.closeButtonClick} className="fal fa-times"></i>
<div className="project-container">
<div>
<p>PERSONAL SITE PROJECT</p>
<p>BUILT A NEW PERSONAL SITE USING REACT.JS WHILE UTILIZING VARIOUS ANIMATIONS A... | render | identifier_name |
DevProjects.js | import React, {Component} from "react";
import { addAnimationId } from './modules/animationFunctions.js'
import '../scss/dev-projects.css';
import close from "../assets/close.png";
export default class DevProjects extends Component {
componentDidMount() { addAnimationId('dev-projects', 'dev-section-fadein') }
re... | }
}; | ); | random_line_split |
test-amp-fit-text.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
ft.textContent = text;
iframe.doc.body.appendChild(ft);
return new Timer(window).promise(16).then(() => {
ft.implementation_.layoutCallback();
return ft;
});
});
}
it('renders', () => {
var text = 'Lorem ipsum';
return getFitText(text).then(ft => {
var con... | {
ft.setAttribute('layout', 'responsive');
} | conditional_block |
test-amp-fit-text.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
it('should always fit on one line', () => {
measurer./*OK*/innerHTML = 'A';
updateOverflow_(content, measurer, 24, 20);
expect(classToggles['-amp-fit-text-content-overflown']).to.equal(false);
expect(getLineClamp()).to.equal('');
expect(content.style.maxHeight).to.equal('');
});
it('should ... | {
for (const k in content.style) {
if (k == 'lineClamp' || k.match(/.*LineClamp/)) {
return content.style[k];
}
}
return null;
} | identifier_body |
test-amp-fit-text.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | (text, opt_responsive) {
return createIframePromise().then(iframe => {
var ft = iframe.doc.createElement('amp-fit-text');
ft.setAttribute('width', '111');
ft.setAttribute('height', '222');
ft.style.fontFamily = 'Arial';
ft.style.fontSize = '17px';
ft.style.lineHeight = '17px';
... | getFitText | identifier_name |
test-amp-fit-text.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
describe('amp-fit-text updateOverflow', () => {
let content;
let classToggles;
let measurer;
beforeEach(() => {
classToggles = {};
content = {
style: {},
classList: {
toggle: (className, on) => {
classToggles[className] = on;
}
}
};
measurer = doc... | it('should always fit on two lines', () => {
element./*OK*/innerHTML = 'A<br>B';
expect(calculateFontSize_(element, 20, 6, 72)).to.equal(10);
});
}); | random_line_split |
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... |
fn read_sequence(used_seq : Option<&str>) -> String {
let mut seq = String::new();
loop {
seq.clear();
println!("Please, enter sequence of 3 coins: H (heads) or T (tails): ");
stdin().read_line(&mut seq).ok().expect("failed to read line");
seq = seq.trim().to_uppercase();
... | {
let mut seq = String::new();
match seed {
Some(s) => {
let c0 = s.chars().next().unwrap();
if c0 == 'H' {seq.push('T')
} else {seq.push('H')}
seq.push(c0);
seq.push(s.chars().nth(1).unwrap());
},
None => {
for ... | identifier_body |
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... | () {
println!("--Penney's game--");
loop {
let useq : String;
let aiseq : String;
if thread_rng().gen::<bool>() {
println!("You choose first!");
useq = read_sequence(None);
println!("Your sequence: {}", useq);
aiseq = gen_sequence( Some(&us... | main | identifier_name |
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... |
if coins.contains(&aiseq) {
println!("\nI win!");
break;
}
}
println!(" Play again? Y to play, Q to exit.");
let mut input = String::new();
stdin().read_line(&mut input).ok().expect("failed to read line");
match input.char... | {
println!("\nYou win!");
break;
} | conditional_block |
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... | let mut seq = String::new();
match seed {
Some(s) => {
let c0 = s.chars().next().unwrap();
if c0 == 'H' {seq.push('T')
} else {seq.push('H')}
seq.push(c0);
seq.push(s.chars().nth(1).unwrap());
},
None => {
for _ ... | }
fn gen_sequence(seed : Option<&str>) -> String { | random_line_split |
Gruntfile.js | module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
release: {
options: {
'force': true
},
src: [
'dist/css',
'dist/fonts',
'dist/img',
'dist/js',
'dist/favicon.ico'... | },
cssmin: {
options: {
shorthandCompacting: false,
roundingPrecision: -1
},
dist: {
files: {
'dist/css/main.css': ['src/css/**/*.css']
}
}
},
jshint: {
all: [
'Gruntfile.js',
'src/js/app/**/*.js',
'src/js/ap... | }
})
} | random_line_split |
controllers.js | angular.module('perCapita.controllers', [])
.controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService',
function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) {
$scope.loginData = $localStorage.getOb... |
}])
.controller('AboutController', ['$scope', function ($scope) {
}])
.controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) {
$scope.shouldShowDelete = f... | {
$scope.doLookup();
} | conditional_block |
controllers.js | angular.module('perCapita.controllers', [])
.controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService',
function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) {
$scope.loginData = $localStorage.getOb... | if ($stateParams.id) {
console.log("param " + $stateParams.id);
$scope.city = $rootScope.cities.filter(function (obj) {
return obj._id === $stateParams.id;
})[0];
console.log($scope.city);
} else {
$scope.doLookup();
}
}])
.controller('AboutController', ['$scope... | random_line_split | |
jar.py | # This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import hashlib
import zipfile
from viper.common.abstracts import Module
from viper.core.session import __sessions__
class Jar(Module):
|
super(Jar, self).run()
if self.args is None:
return
arg_dump = self.args.dump
if not __sessions__.is_set():
self.log('error', "No open session")
return
if not zipfile.is_zipfile(__sessions__.current.file.path):
self.log('error',... | cmd = 'jar'
description = 'Parse Java JAR archives'
authors = ['Kevin Breen']
def __init__(self):
super(Jar, self).__init__()
self.parser.add_argument('-d ', '--dump', metavar='dump_path', help='Extract all items from jar')
def run(self):
def read_manifest(manifest):
... | identifier_body |
jar.py | # This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import hashlib
import zipfile
from viper.common.abstracts import Module
from viper.core.session import __sessions__
class Jar(Module):
cmd = 'jar'
description = 'Parse Java JAR archives'
... |
self.log('info', "Manifest File:")
self.log('table', dict(header=['Item', 'Value'], rows=rows))
super(Jar, self).run()
if self.args is None:
return
arg_dump = self.args.dump
if not __sessions__.is_set():
self.log('error', "No open sess... | if len(line) > 1:
item, value = line.split(':')
rows.append([item, value]) | conditional_block |
jar.py | # This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import hashlib
import zipfile
from viper.common.abstracts import Module
from viper.core.session import __sessions__
class Jar(Module):
cmd = 'jar'
description = 'Parse Java JAR archives'
... | (manifest):
rows = []
lines = manifest.split('\r\n')
for line in lines:
if len(line) > 1:
item, value = line.split(':')
rows.append([item, value])
self.log('info', "Manifest File:")
self.log('table', dic... | read_manifest | identifier_name |
jar.py | # This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import hashlib
import zipfile
from viper.common.abstracts import Module
from viper.core.session import __sessions__
class Jar(Module):
cmd = 'jar'
description = 'Parse Java JAR archives'
... | rows.append([item, value])
self.log('info', "Manifest File:")
self.log('table', dict(header=['Item', 'Value'], rows=rows))
super(Jar, self).run()
if self.args is None:
return
arg_dump = self.args.dump
if not __sessions__.is_set(... | if len(line) > 1:
item, value = line.split(':') | random_line_split |
ProofResourceStrategy.py | """
ProofResourceStrategy is the real implementation of initializing the resource
data for ProofResource. There can be multiple strategies for one ProofResource.
Main considerations are configure file, database (may use a ProofInstance),
XML file.
This is the base class with all interfaces needed by ProofResource. Eac... | pass | identifier_body | |
ProofResourceStrategy.py | """
ProofResourceStrategy is the real implementation of initializing the resource
data for ProofResource. There can be multiple strategies for one ProofResource.
Main considerations are configure file, database (may use a ProofInstance),
XML file. | By separating the strategy process from resource interfaces, we can make
ProofInstance work both as stand-alone and shared persistent data layer.
It also make testing easier by creating some dummy strategy implementations.
"""
__version__='$Revision: 117 $'[11:-2]
__author__ = "Duan Guoqiang (mattgduan@gmail.com)"
i... |
This is the base class with all interfaces needed by ProofResource. Each different
strategies can futher extend from this class to include strategic specific
functions.
| random_line_split |
ProofResourceStrategy.py | """
ProofResourceStrategy is the real implementation of initializing the resource
data for ProofResource. There can be multiple strategies for one ProofResource.
Main considerations are configure file, database (may use a ProofInstance),
XML file.
This is the base class with all interfaces needed by ProofResource. Eac... | :
def __init__(self, logger=None):
pass
def __parseXMLDBMap(self, schema, xml):
pass
def getDatabaseMap(self, schema):
pass
| ProofResourceStrategy | identifier_name |
htmltableheadercellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableHeaderCellElementBinding;
use dom::bindings::js::Root;
use dom::bin... | (localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableHeaderCellElement> {
Node::reflect_node(box HTMLTableHeaderCellElement::new_inherited(localName, prefix, document),
document,
HTMLTableHeaderCell... | new | identifier_name |
htmltableheadercellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableHeaderCellElementBinding;
use dom::bindings::js::Root;
use dom::bin... |
}
| {
Node::reflect_node(box HTMLTableHeaderCellElement::new_inherited(localName, prefix, document),
document,
HTMLTableHeaderCellElementBinding::Wrap)
} | identifier_body |
htmltableheadercellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableHeaderCellElementBinding;
use dom::bindings::js::Root; |
#[dom_struct]
pub struct HTMLTableHeaderCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableHeaderCellElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLTableHeaderCellElement {
HTMLTableHea... | use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmltablecellelement::HTMLTableCellElement;
use dom::node::Node;
use string_cache::Atom; | random_line_split |
catalog.rs | Keyword;
use crate::keywordtree::KeywordTree;
use crate::libraryfiles::LibraryFile;
use crate::lrobject::{LrId, LrObject};
const LR2_VERSION: i32 = 2;
const LR3_VERSION: i32 = 3;
const LR4_VERSION: i32 = 4;
const LR6_VERSION: i32 = 6;
/// Catalog version.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CatalogVersi... |
}
&self.libfiles
}
/// Get the libfiles. This assume the libfiles have been loaded first.
/// This allow non-mutable borrowing that would be caused by `load_libfiles()`.
pub fn libfiles(&self) -> &Vec<LibraryFile> {
&self.libfiles
}
/// Load images.
pub fn load_ima... | {
let mut result = Catalog::load_objects::<LibraryFile>(conn, self.catalog_version);
self.libfiles.append(&mut result);
} | conditional_block |
catalog.rs | Keyword;
use crate::keywordtree::KeywordTree;
use crate::libraryfiles::LibraryFile;
use crate::lrobject::{LrId, LrObject};
const LR2_VERSION: i32 = 2;
const LR3_VERSION: i32 = 3;
const LR4_VERSION: i32 = 4;
const LR6_VERSION: i32 = 6;
/// Catalog version.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CatalogVersi... | };
}
if let Some(root_keyword_id) = self.get_variable::<f64>("AgLibraryKeyword_rootTagID") {
self.root_keyword_id = root_keyword_id.round() as LrId;
}
}
/// Generic object loader leveraging the FromDb protocol
fn load_objects<T: FromDb>(conn: &Connection, ca... | random_line_split | |
catalog.rs | Keyword;
use crate::keywordtree::KeywordTree;
use crate::libraryfiles::LibraryFile;
use crate::lrobject::{LrId, LrObject};
const LR2_VERSION: i32 = 2;
const LR3_VERSION: i32 = 3;
const LR4_VERSION: i32 = 4;
const LR6_VERSION: i32 = 6;
/// Catalog version.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CatalogVersi... | (&self) -> &BTreeMap<LrId, Keyword> {
&self.keywords
}
/// Load folders.
pub fn load_folders(&mut self) -> &Folders {
if self.folders.is_empty() {
if let Some(ref conn) = self.dbconn {
let folders = Catalog::load_objects::<RootFolder>(conn, self.catalog_version);... | keywords | identifier_name |
catalog.rs | Keyword;
use crate::keywordtree::KeywordTree;
use crate::libraryfiles::LibraryFile;
use crate::lrobject::{LrId, LrObject};
const LR2_VERSION: i32 = 2;
const LR3_VERSION: i32 = 3;
const LR4_VERSION: i32 = 4;
const LR6_VERSION: i32 = 6;
/// Catalog version.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CatalogVersi... |
/// Load collectons.
pub fn load_collections(&mut self) -> &Vec<Collection> {
if self.collections.is_empty() {
if let Some(ref conn) = self.dbconn {
let mut collections =
Catalog::load_objects::<Collection>(conn, self.catalog_version);
fo... | {
&self.images
} | identifier_body |
previewPane.js | (function (global) {
'use strict';
$ = global.jQuery;
let branding_style = $('.govuk-radios__item input[name="branding_style"]:checked');
if (!branding_style.length) { return; }
branding_style = branding_style.val();
const $paneWrapper = $('<div class="govuk-grid-column-full"></div>');
const $form =... | (e) {
const $target = $(e.target);
if ($target.attr('name') == 'branding_style') {
branding_style = $target.val();
}
$previewPane.attr('src', `/_${previewType}?${buildQueryString(['branding_style', branding_style])}`);
}
$paneWrapper.append($previewPane);
$form.find('.govuk-grid-row').eq(0... | setPreviewPane | identifier_name |
previewPane.js | (function (global) {
|
let branding_style = $('.govuk-radios__item input[name="branding_style"]:checked');
if (!branding_style.length) { return; }
branding_style = branding_style.val();
const $paneWrapper = $('<div class="govuk-grid-column-full"></div>');
const $form = $('form');
const previewType = $form.data('previewType');... | 'use strict';
$ = global.jQuery; | random_line_split |
previewPane.js | (function (global) {
'use strict';
$ = global.jQuery;
let branding_style = $('.govuk-radios__item input[name="branding_style"]:checked');
if (!branding_style.length) { return; }
branding_style = branding_style.val();
const $paneWrapper = $('<div class="govuk-grid-column-full"></div>');
const $form =... |
$previewPane.attr('src', `/_${previewType}?${buildQueryString(['branding_style', branding_style])}`);
}
$paneWrapper.append($previewPane);
$form.find('.govuk-grid-row').eq(0).prepend($paneWrapper);
$form.attr('action', location.pathname.replace(new RegExp(`set-${previewType}-branding$`), `preview-${previe... | {
branding_style = $target.val();
} | conditional_block |
previewPane.js | (function (global) {
'use strict';
$ = global.jQuery;
let branding_style = $('.govuk-radios__item input[name="branding_style"]:checked');
if (!branding_style.length) { return; }
branding_style = branding_style.val();
const $paneWrapper = $('<div class="govuk-grid-column-full"></div>');
const $form =... |
function setPreviewPane (e) {
const $target = $(e.target);
if ($target.attr('name') == 'branding_style') {
branding_style = $target.val();
}
$previewPane.attr('src', `/_${previewType}?${buildQueryString(['branding_style', branding_style])}`);
}
$paneWrapper.append($previewPane);
$form.f... | {
return $.map(arguments, (val, idx) => encodeURI(val[0]) + '=' + encodeURI(val[1])).join('&');
} | identifier_body |
Gruntfile.js | /*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
meta: {
version: '2.0.0',
banner: '/*! Ebla - v<%= meta.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> ' +
... | 'javascripts/ebla/navigation.keyboard.js',
'javascripts/ebla/placesaver.js',
'javascripts/ebla/progress.js',
'javascripts/ebla/resize.js',
'javascripts/ebla/toc.js',
'javascripts/ebla/init.js',
'javascripts/ebla/book.js'],... | 'javascripts/ebla/navigation.event.js', | random_line_split |
base.py | # -*- encoding: utf-8 -*-
"""
Django settings for login project.
"""
from django.core.urlresolvers import reverse_lazy
DEBUG = True
TESTING = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
# We use the 'SITE_NAME' for the name of the database and the name of the
# cloud files container.
SITE_NAME = '... | STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '#9x3dk(nl82sihl7c^u_#--yp((!g2ehd_1pmp)f... | # various locations. | random_line_split |
middleware.py | from django.http import HttpResponseRedirect
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMP... | path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(settings.LOGIN_URL) | conditional_block | |
middleware.py | from django.http import HttpResponseRedirect
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMP... | (MiddlewareMixin):
"""
Middleware that requires a user to be authenticated to view any page other
than LOGIN_URL. Exemptions to this requirement can optionally be specified
in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
you can copy from your urls.py).
Requires authen... | LoginRequiredMiddleware | identifier_name |
middleware.py | from django.http import HttpResponseRedirect
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMP... | assert hasattr(request, 'user'), "The Login Required middleware\
requires authentication middleware to be installed. Edit your\
MIDDLEWARE_CLASSES setting to insert\
'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
'django.co... | identifier_body | |
middleware.py | from django.http import HttpResponseRedirect
from django.conf import settings | if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware(MiddlewareMixin):
"""
Middleware that requires a user to be authenticated to view any page other
than LOGIN_URL. Exemptions to this requirement can optionally ... | from django.utils.deprecation import MiddlewareMixin
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] | random_line_split |
memoizer.js | /*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.lang.aspect.memoizer"]) | return {around:function(){
var _a=_1.getContext(),_b=_a.joinPoint,_c=_a.instance,t,u,_d,_e=_9.apply(_c,arguments);
if((t=_c.__memoizerCache)&&(t=t[_b.targetName])&&(_e in t)){
return t[_e];
}
var _d=_1.proceed.apply(null,arguments);
if(!(t=_c.__memoizerCache)){
t=_c.__memoizerCache={};
}
if(!(u=t[_b.targetName])){
u=t[... | {
dojo._hasResource["dojox.lang.aspect.memoizer"]=true;
dojo.provide("dojox.lang.aspect.memoizer");
(function(){
var _1=dojox.lang.aspect;
var _2={around:function(_3){
var _4=_1.getContext(),_5=_4.joinPoint,_6=_4.instance,t,u,_7;
if((t=_6.__memoizerCache)&&(t=t[_5.targetName])&&(_3 in t)){
return t[_3];
}
var _7=_1.pro... | conditional_block |
memoizer.js | /*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.lang.aspect.memoizer"]){
dojo._hasResource["dojox.lang.aspect.memoizer"]=true;
dojo.provide("d... | if((t=_c.__memoizerCache)&&(t=t[_b.targetName])&&(_e in t)){
return t[_e];
}
var _d=_1.proceed.apply(null,arguments);
if(!(t=_c.__memoizerCache)){
t=_c.__memoizerCache={};
}
if(!(u=t[_b.targetName])){
u=t[_b.targetName]={};
}
return u[_e]=_d;
}};
};
_1.memoizer=function(_f){
return arguments.length==0?_2:_8(_f);
};
})(... | var _a=_1.getContext(),_b=_a.joinPoint,_c=_a.instance,t,u,_d,_e=_9.apply(_c,arguments); | random_line_split |
opts.rs | initial_window_size: TypedSize2D<ScreenPx, u32>,
/// An optional string allowing the user agent to be set for testing.
pub user_agent: String,
/// Whether to run in multiprocess mode.
pub multiprocess: bool,
/// Dumps the flow tree after a layout.
pub dump_flow_tree: bool,
/// Dumps the... | {
/// List all the debug options.
pub help: bool,
/// Bubble intrinsic widths separately like other engines.
pub bubble_widths: bool,
/// Disable antialiasing of rendered text.
pub disable_text_aa: bool,
/// Disable antialiasing of rendered text on the HTML canvas element.
pub disabl... | DebugOptions | identifier_name |
opts.rs | ", "headless", "Headless mode");
opts.optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure");
opts.optflagopt("", "devtools", "Start remote devtools server on port", "6000");
opts.optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000");
opts.optopt("",... | unsafe {
assert!(DEFAULT_OPTIONS.is_null());
assert!(DEFAULT_OPTIONS != INVALID_OPTIONS);
let box_opts = box opts;
DEFAULT_OPTIONS = Box::into_raw(box_opts);
}
}
#[ | identifier_body | |
opts.rs | (Android; Mobile; rv:37.0) Servo/1.0 Firefox/37.0"
}
UserAgent::Gonk => {
"Mozilla/5.0 (Mobile; rv:37.0) Servo/1.0 Firefox/37.0"
}
}.to_owned()
}
#[cfg(target_os = "android")]
const DEFAULT_USER_AGENT: UserAgent = UserAgent::Android;
// FIXME: This requires https://github.com/... | random_line_split | ||
struct.py | else:
return '\n\n'.join([str(s) for s in self.sections])
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = promote_to_string(value)
@property
def sections(self):
return self._sections
@sections.s... |
def __eq__(self, other):
return (
isinstance(other, Paragraph) and other.category == self.category and
self.sentences == other.sentences
)
def __hash__(self):
return hash(str(self))
def __repr__(self):
sentences = '\n\t'.join(repr(s) for s in self.s... | :param sentences: document sections (`RhetRel` or `Element` type)
"""
self._sentences = [promote_to_string(s) for s in sentences] | random_line_split |
struct.py | else:
return '\n\n'.join([str(s) for s in self.sections])
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = promote_to_string(value)
@property
def sections(self):
return self._sections
@sections.s... | (self, lvl=0, indent=' '):
spaces = indent * lvl
data = spaces + '<RhetRel name="' + self.relation + '">\n'
data += indent + spaces + '<marker>' + self.marker + '</marker>\n'
data += indent + spaces + '<nuclei>\n'
data += indent * 2 + spaces + '<nucleus>\n'
for n in self... | to_xml | identifier_name |
struct.py | else:
return '\n\n'.join([str(s) for s in self.sections])
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = promote_to_string(value)
@property
def sections(self):
return self._sections
@sections.s... |
def __eq__(self, other):
return (
other.category == self.category and self.relation == other.relation and
self.nuclei == other.nuclei and self.satellite == other.satellite and
self.marker == other.marker
)
def __hash__(self):
return hash(str(self))
... | return ' '.join(str(x) for x in self.order) | identifier_body |
struct.py | else:
return '\n\n'.join([str(s) for s in self.sections])
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = promote_to_string(value)
@property
def sections(self):
return self._sections
@sections.s... |
else:
rv = ' '.join([self.order[0].to_str(), self.marker, self.order[1].to_str()])
rv = rv.replace(' , ', ', ').replace(' ', ' ')
return rv
class MsgSpec:
""" MsgSpec specifies an interface for various message specifications.
Because the specifications are domain dependen... | strings = [n.to_str() for n in self.nuclei]
rv = strings[0]
for i, s in enumerate(strings[1:]):
if i < len(strings) - 2:
rv = ' '.join([rv, self.marker, s])
else:
rv = ' '.join([rv, self.last_element_marker, s]) | conditional_block |
cellaut.py | # Based on cage v1.1.4
# http://www.alcyone.com/software/cage/
# Copyright (C) 2002-2006 Erik Max Francis <max@alcyone.com>
# GPL License
class Topology:
|
class Neighborhood:
"""Abstraction of the set of cells adjacent to any given cell"""
def neighbors(self, address):
"""Returns a list of addresses which are neighbors."""
raise NotImplementedError
def states(self, address):
"""Returns the list of cell value... | """Encaptulation of the shape and dimentionality of a cellular automata"""
def get(self, address):
raise NotImplementedError
def set(self, address, state):
raise NotImplementedError
def normalize(self, address):
raise NotImplementedError | identifier_body |
cellaut.py | # Based on cage v1.1.4
# http://www.alcyone.com/software/cage/
# Copyright (C) 2002-2006 Erik Max Francis <max@alcyone.com>
# GPL License
class Topology:
"""Encaptulation of the shape and dimentionality of a cellular automata"""
def get(self, address):
raise NotImplementedError
def se... |
else:
raise IndexError
class ExtendedNeighborhood(Neighborhood):
"""A neighborhood that retrieves a list of states on each direction"""
def states(self, address, max=1):
return [[self.get(i) for i in j] for j in self.neighbors(address, max)]
class Automaton:
"""Abstra... | x, y = addr
self.buffer[x][y] = state | conditional_block |
cellaut.py | # Based on cage v1.1.4
# http://www.alcyone.com/software/cage/
# Copyright (C) 2002-2006 Erik Max Francis <max@alcyone.com>
# GPL License
class | :
"""Encaptulation of the shape and dimentionality of a cellular automata"""
def get(self, address):
raise NotImplementedError
def set(self, address, state):
raise NotImplementedError
def normalize(self, address):
raise NotImplementedError
clas... | Topology | identifier_name |
cellaut.py | # Based on cage v1.1.4
# http://www.alcyone.com/software/cage/
# Copyright (C) 2002-2006 Erik Max Francis <max@alcyone.com>
# GPL License
class Topology:
"""Encaptulation of the shape and dimentionality of a cellular automata"""
def get(self, address):
raise NotImplementedError
def se... | self.buffer[x][y] = state
else:
raise IndexError
class ExtendedNeighborhood(Neighborhood):
"""A neighborhood that retrieves a list of states on each direction"""
def states(self, address, max=1):
return [[self.get(i) for i in j] for j in self.neighbors(address, max)... | addr = self.normalize(address)
if addr:
x, y = addr | random_line_split |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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
* | * 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 governing permissions and
* limitations under the License.
*/
import fromString = require( './index' );
// TESTS //
// The functio... | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software | random_line_split |
__init__.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# compute/__init__.py
"""
See |compute.subsystem|, |compute.network|, |compute.distance|, and
|compute.parallel| for documentation.
Attributes:
all_complexes: Alias for :func:`pyphi.compute.network.all_complexes`.
ces: Alias for :func:`pyphi.compute.subsystem.ces... | """
# pylint: disable=unused-import
from .distance import ces_distance, concept_distance
from .network import (
all_complexes,
complexes,
condensed,
major_complex,
possible_complexes,
subsystems,
)
from .subsystem import (
ConceptStyleSystem,
SystemIrreducibilityAnalysisConceptStyle,
... | subsystems: Alias for :func:`pyphi.compute.network.subsystems`. | random_line_split |
ng_switch.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { TemplateRef, ViewContainerRef } from '@angular/core';
export declare class SwitchView {
private _viewCon... | {
private _switchValue;
private _useDefault;
private _valueViews;
private _activeViews;
ngSwitch: any;
}
/**
* Insert the sub-tree when the `ngSwitchCase` expression evaluates to the same value as the
* enclosing switch expression.
*
* If multiple match expression match the switch expression va... | NgSwitch | identifier_name |
ng_switch.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { TemplateRef, ViewContainerRef } from '@angular/core';
export declare class SwitchView {
private _viewCon... | * <template [ngSwitchCase]="0">0, increment again</template>
* <template [ngSwitchCase]="1">1, increment again</template>
* <template [ngSwitchCase]="2">2, stop incrementing</template>
* <template ngSwitchDefault>> 2, STOP!</template>
* </p>
* `,
* directives: [NgSwitch, NgSwit... | * <!-- alternate syntax -->
*
* <p [ngSwitch]="value">
* <template ngSwitchCase="init">increment to start</template> | random_line_split |
symtab.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
pub struct SymTab {
parent: Option<Rc<SymTab>>,
names: RefCell<HashMap<String, usize>>,
}
impl SymTab {
pub fn new(parent: Rc<SymTab>, names: &[Rc<String>]) -> SymTab {
let mut hash_names = HashMap::new();
... | if let Some(index) = self.names.borrow().get(name) {
return *index
}
let new_index = self.names.borrow().len();
self.names.borrow_mut().insert(name.to_string(), new_index);
new_index
}
pub fn get_name(&self, name: &str) -> Option<(usize, usize)> {
s... | }
}
pub fn add_name(&self, name: &str) -> usize { | random_line_split |
symtab.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
pub struct SymTab {
parent: Option<Rc<SymTab>>,
names: RefCell<HashMap<String, usize>>,
}
impl SymTab {
pub fn new(parent: Rc<SymTab>, names: &[Rc<String>]) -> SymTab {
let mut hash_names = HashMap::new();
... |
let new_index = self.names.borrow().len();
self.names.borrow_mut().insert(name.to_string(), new_index);
new_index
}
pub fn get_name(&self, name: &str) -> Option<(usize, usize)> {
self.get_name_internal(name, 0)
}
fn get_name_internal(&self, name: &str, env_index: usi... | {
return *index
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.