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 |
|---|---|---|---|---|
urls.py | """pirate URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | #Admin Site
#url(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
url(r'^boss/', include(admin.site.urls),name='boss'),
#Home & Captain
url(r'^$', files.views.index, name='home'),
url(r'^review$', files.views.review, name ='review'),
url(r'^captain$', files.views.captain, name='c... | from django.contrib import admin
import files.views
import user.views
urlpatterns = [ | random_line_split |
all_12.js | var searchData=
[
['value',['value',['../structguac__pool__int.html#af76ff5f21c6e0f69d95cdd1385ea24a4',1,'guac_pool_int']]],
['vguac_5fclient_5fabort',['vguac_client_abort',['../client_8h.html#a4c0eccd7d0ed3dbf3e7941ce297e0224',1,'client.h']]],
['vguac_5fclient_5flog',['vguac_client_log',['../client_8h.html#a37a0... | ['vguac_5fprotocol_5fsend_5flog',['vguac_protocol_send_log',['../protocol_8h.html#a3a783d771e1727ba2a82b2298acf4ee4',1,'protocol.h']]],
['video_5fmimetypes',['video_mimetypes',['../structguac__client__info.html#aa58dc4ee1e3b8801e9b0abbf9135d8b6',1,'guac_client_info']]]
]; | random_line_split | |
oa_edit_prompts.js | import Container from './oa_container';
import { Prompt } from './oa_container_item';
/**
Editing interface for the prompts.
Args:
element (DOM element): The DOM element representing this view.
Returns:
OpenAssessment.EditPromptsView
* */
export class EditPromptsView {
constructor(element, notifier) {
t... | () {
if (this.addRemoveEnabled) {
this.promptsContainer.add();
}
}
/**
Remove a prompt.
Args:
item (OpenAssessment.RubricCriterion): The criterion item to remove.
* */
removePrompt(item) {
if (this.addRemoveEnabled) {
this.promptsContainer.remove(item);
}
}
/... | addPrompt | identifier_name |
oa_edit_prompts.js | import Container from './oa_container';
import { Prompt } from './oa_container_item';
/**
Editing interface for the prompts.
Args:
element (DOM element): The DOM element representing this view.
Returns:
OpenAssessment.EditPromptsView
* */
export class EditPromptsView {
constructor(element, notifier) {
t... |
/**
Return a list of validation errors visible in the UI.
Mainly useful for testing.
Returns:
list of string
* */
validationErrors() {
const errors = [];
return errors;
}
/**
Clear all validation errors from the UI.
* */
clearValidationErrors() {}
}
export defa... | {
return true;
} | identifier_body |
oa_edit_prompts.js | import Container from './oa_container';
import { Prompt } from './oa_container_item';
/**
Editing interface for the prompts.
Args:
element (DOM element): The DOM element representing this view.
Returns:
OpenAssessment.EditPromptsView
* */
export class EditPromptsView {
constructor(element, notifier) {
t... |
}
/**
Remove a prompt.
Args:
item (OpenAssessment.RubricCriterion): The criterion item to remove.
* */
removePrompt(item) {
if (this.addRemoveEnabled) {
this.promptsContainer.remove(item);
}
}
/**
Retrieve all prompts.
Returns:
Array of OpenAssessment.Prom... | {
this.promptsContainer.add();
} | conditional_block |
oa_edit_prompts.js | import Container from './oa_container';
import { Prompt } from './oa_container_item';
/**
Editing interface for the prompts.
Args:
element (DOM element): The DOM element representing this view.
Returns:
OpenAssessment.EditPromptsView
* */
export class EditPromptsView {
constructor(element, notifier) {
t... | clearValidationErrors() {}
}
export default EditPromptsView; | random_line_split | |
udev.rs | //! use smithay::backend::udev::{UdevBackend, UdevEvent};
//!
//! let udev = UdevBackend::new("seat0", None).expect("Failed to monitor udev.");
//!
//! for (dev_id, node_path) in udev.device_list() {
//! // process the initial list of devices
//! }
//!
//! # let event_loop = smithay::reexports::calloop::EventLoop::... | /// ## Arguments
/// `seat` - system seat which should be bound
/// `logger` - slog Logger to be used by the backend and its `DrmDevices`.
pub fn new<L, S: AsRef<str>>(seat: S, logger: L) -> IoResult<UdevBackend>
where
L: Into<Option<::slog::Logger>>,
{
let log = crate::slog_... |
impl UdevBackend {
/// Creates a new [`UdevBackend`]
/// | random_line_split |
udev.rs | //! use smithay::backend::udev::{UdevBackend, UdevEvent};
//!
//! let udev = UdevBackend::new("seat0", None).expect("Failed to monitor udev.");
//!
//! for (dev_id, node_path) in udev.device_list() {
//! // process the initial list of devices
//! }
//!
//! # let event_loop = smithay::reexports::calloop::EventLoop::... |
}
/// Events generated by the [`UdevBackend`], notifying you of changes in system devices
#[derive(Debug)]
pub enum UdevEvent {
/// A new device has been detected
Added {
/// ID of the new device
device_id: dev_t,
/// Path of the new device
path: PathBuf,
},
/// A devic... | {
self.token = Token::invalid();
poll.unregister(self.as_raw_fd())
} | identifier_body |
udev.rs | //! use smithay::backend::udev::{UdevBackend, UdevEvent};
//!
//! let udev = UdevBackend::new("seat0", None).expect("Failed to monitor udev.");
//!
//! for (dev_id, node_path) in udev.device_list() {
//! // process the initial list of devices
//! }
//!
//! # let event_loop = smithay::reexports::calloop::EventLoop::... |
}
}
// New connector
EventType::Change => {
if let Some(devnum) = event.devnum() {
info!(self.logger, "Device changed: #{}", devnum);
if self.devices.contains_key(&devnum) {
... | {
callback(UdevEvent::Removed { device_id: devnum }, &mut ());
} | conditional_block |
udev.rs | _, _dispatch_data| match event {
//! UdevEvent::Added { device_id, path } => {
//! // a new device has been added
//! },
//! UdevEvent::Changed { device_id } => {
//! // a device has been changed
//! },
//! UdevEvent::Removed { device_id } => {
//! // a device has been remov... | driver | identifier_name | |
instr_extractps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn extractps_1() {
run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Dir... | }
#[test]
fn extractps_4() {
run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Indirect(RDX, Some(OperandSize::Dword), None)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(62)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None ... | }
#[test]
fn extractps_3() {
run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Direct(EDI)), operand2: Some(Direct(XMM3)), operand3: Some(Literal8(85)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 23, 223, 85], Op... | random_line_split |
instr_extractps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn extractps_1() |
#[test]
fn extractps_2() {
run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(IndirectScaledDisplaced(EAX, Four, 630659303, Some(OperandSize::Dword), None)), operand2: Some(Direct(XMM7)), operand3: Some(Literal8(106)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: fal... | {
run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Direct(EBP)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(70)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 23, 245, 70], OperandSize::Dword)
} | identifier_body |
instr_extractps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Direct(EBP)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(70)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 23, 245, 70], OperandSize::Dword)
}
#[te... | extractps_1 | identifier_name |
context_spec.ts | /**
* @license
* Copyright Google LLC 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 {HttpContext, HttpContextToken} from '../src/context';
const IS_ENABLED = new HttpContextToken<boolean>(() =>... | });
}); | random_line_split | |
boxmodel.py | vt in self._graph.vertex_iterator():
## what if vt is simple and doesn't have operands
aggregate.setdefault( tuple( compartment_aggregation( vt.operands() ) ), [] ).append( vt.operands() )
## aggregate is { new vertex: [old vertices], ... }
print 'aggregate:', aggregate
... | return self.do_inner_product( s ) # just in case | identifier_body | |
boxmodel.py | new BoxModel. trs is a list of (source,target,rate)
# tuples suitable for adding to self._graph
#print 'add_transitions', trs
#print 'parameters before', self._parameters
nbm = deepcopy(self)
nbm._graph.add_edges( trs )
#print self._vars
for f,t,r in trs:
try:
#print r
#print r.variables()
#print Se... | terms_iterator | identifier_name | |
boxmodel.py | ita_rates to
## plot using per capita rather than absolute flow rates
if transform_graph is not None:
g = transform_graph(g)
try:
## free_product may assign this member
ellipsis_vertices = Set( self._ellipsis_vars )
def ellipsize( g ):
... | mu = MakeMicro( self, source )
ut = mu( rate )
#print str(ut); sys.stdout.flush()
lines += [ r' & ' + latex(mu.sigma_fn(SR('x'))) + r'\to' + latex(target)
+ r' \quad\text{ at rate } '
+ latex( ut )
] | conditional_block | |
boxmodel.py | in self._parameter_dependencies.items():
try: [ d[0] for d in pd ]
except: self._parameter_dependencies[p] = [ (d,deps.index) for d in pd ]
#print 'parameter dependencies:', self._parameter_dependencies
self._bindings = bindings
if self._graph.get_pos() is None:
... | sort_order_map = dict(
## parameters first, Greek letters before Roman
[ (latex(v),(T,T)) for v in self._parameters for T in [-1e+10 if latex(v)[0] == '\\' or latex(v)[0:2] == '{\\' else -0.9e+10] ] +
## then compartment names, in order of the graph layout
[... | # this function returns a sort of pseudo-expression that's only
# suitable for printing, not for doing math with
try: self._sorter
except AttributeError:
from collections import defaultdict | random_line_split |
multi_file_writer.py | #!/usr/bin/env python3
"""Defines ways to "convert" a file name to an input/output stream."""
from __future__ import absolute_import, division, print_function
from builtins import range
from io import TextIOBase
import math
import os
from emLam.utils import allname, openall
class MultiFileWriter(TextIOBase):
def... |
def __new_file(self):
"""
Opens the next file, resets the line counter and renames all previous
files if we need a new digit.
"""
self.f.close()
digits = int(math.log10(self.index)) + 1
self.index += 1
new_digits = int(math.log10(self.index)) + 1
... | self.f.write(line)
self.f.write(u'\n')
self.lines += 1
if self.lines >= self.max_lines and (
not self.wait_for_empty or line == ''):
self.__new_file() | conditional_block |
multi_file_writer.py | #!/usr/bin/env python3
"""Defines ways to "convert" a file name to an input/output stream."""
from __future__ import absolute_import, division, print_function
from builtins import range
from io import TextIOBase
import math
import os
from emLam.utils import allname, openall
class MultiFileWriter(TextIOBase):
def... | (self, index=None, digits=None):
basename, extension = allname(self.file_name)
ext = extension if extension else ''
num_format = '{{:0{}d}}'.format(digits) if digits else '{}'
index_str = num_format.format(self.index if index is None else index)
return '{}-{}{}'.format(basename, ... | __get_file_name | identifier_name |
multi_file_writer.py | #!/usr/bin/env python3
"""Defines ways to "convert" a file name to an input/output stream."""
from __future__ import absolute_import, division, print_function
from builtins import range
from io import TextIOBase
import math
import os
from emLam.utils import allname, openall
class MultiFileWriter(TextIOBase):
def... | self.wait_for_empty = wait_for_empty
self.index = 1
self.lines = 0
self.f = openall(self.__get_file_name(), 'wt')
def __get_file_name(self, index=None, digits=None):
basename, extension = allname(self.file_name)
ext = extension if extension else ''
num_format... | self.file_name = file_name
self.max_lines = max_lines | random_line_split |
multi_file_writer.py | #!/usr/bin/env python3
"""Defines ways to "convert" a file name to an input/output stream."""
from __future__ import absolute_import, division, print_function
from builtins import range
from io import TextIOBase
import math
import os
from emLam.utils import allname, openall
class MultiFileWriter(TextIOBase):
def... |
def close(self):
self.f.close()
def fileno(self):
return self.f.fileno()
def flush(self):
return self.f.flush()
def write(self, s):
for line in s.splitlines():
self.f.write(line)
self.f.write(u'\n')
self.lines += 1
if s... | basename, extension = allname(self.file_name)
ext = extension if extension else ''
num_format = '{{:0{}d}}'.format(digits) if digits else '{}'
index_str = num_format.format(self.index if index is None else index)
return '{}-{}{}'.format(basename, index_str, ext) | identifier_body |
__init__.py | """
@package medpy.features
Functionality to extract features from images and present/manipulate them.
Packages:
- histogram: Functions to create and manipulate (fuzzy) histograms.
- intensity: Functions to extracts voxel-wise intensity based features from (medical) images.
- texture: Run-time optimised fe... | gaussian_membership, sigmoidal_difference_membership
from intensity import centerdistance, centerdistance_xdminus1, guassian_gradient_magnitude, \
hemispheric_difference, indices, intensities, local_histogram, local_mean_gauss, \
median
from utilities im... | __all__ = []
# if __all__ is not set, only the following, explicit import statements are executed
from histogram import fuzzy_histogram, triangular_membership, trapezoid_membership, \ | random_line_split |
yuidoc-bootstrap.js | (function (window, undefined) {
'use strict';
function setUpActiveTab() {
if(localStorage.getItem('main-nav')){
$('a[href="'+ localStorage['main-nav'] + '"]').tab('show');
}
}
function setUpOptionsCheckboxes() |
function setOptionDisplayState(box) {
var cssName = $.trim(box.parent('label').text()).toLowerCase();
if(box.is(':checked')){
$('div.'+cssName).css('display', 'block');
$('li.'+cssName).css('display', 'block');
$('span.'+cssName).css('display', 'inline');
}else{
$('.'+cssName).css('display', 'no... | {
if(localStorage.getItem('options')){
var optionsArr = JSON.parse(localStorage.options),
optionsForm = $('#options-form');
for(var i=0;i<optionsArr.length;i++){
var box = optionsForm.find('input:checkbox').eq(i);
box.prop('checked', optionsArr[i]);
setOptionDisplayState(box);
}
... | identifier_body |
yuidoc-bootstrap.js | (function (window, undefined) {
'use strict';
function | () {
if(localStorage.getItem('main-nav')){
$('a[href="'+ localStorage['main-nav'] + '"]').tab('show');
}
}
function setUpOptionsCheckboxes() {
if(localStorage.getItem('options')){
var optionsArr = JSON.parse(localStorage.options),
optionsForm = $('#options-form');
for(var i=0;i<optionsArr.leng... | setUpActiveTab | identifier_name |
yuidoc-bootstrap.js | (function (window, undefined) {
'use strict';
function setUpActiveTab() {
if(localStorage.getItem('main-nav')){
$('a[href="'+ localStorage['main-nav'] + '"]').tab('show');
}
}
function setUpOptionsCheckboxes() {
if(localStorage.getItem('options')){
var optionsArr = JSON.parse(localStorage.options),
... | setOptionDisplayState(box);
}
}
}
function setOptionDisplayState(box) {
var cssName = $.trim(box.parent('label').text()).toLowerCase();
if(box.is(':checked')){
$('div.'+cssName).css('display', 'block');
$('li.'+cssName).css('display', 'block');
$('span.'+cssName).css('display', 'inline');
... | box.prop('checked', optionsArr[i]); | random_line_split |
deriving-cmp-generic-enum.rs | // Copyright 2013 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 ... | #[derive(PartialEq, Eq, PartialOrd, Ord)]
enum E<T> {
E0,
E1(T),
E2(T,T)
}
pub fn main() {
let e0 = E::E0;
let e11 = E::E1(1i);
let e12 = E::E1(2i);
let e21 = E::E2(1i, 1i);
let e22 = E::E2(1i, 2i);
// in order for both PartialOrd and Ord
let es = [e0, e11, e12, e21, e22];
... |
// no-pretty-expanded FIXME #15189
| random_line_split |
deriving-cmp-generic-enum.rs | // Copyright 2013 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 ... | // PartialEq
assert_eq!(*e1 == *e2, eq);
assert_eq!(*e1 != *e2, !eq);
// PartialOrd
assert_eq!(*e1 < *e2, lt);
assert_eq!(*e1 > *e2, gt);
assert_eq!(*e1 <= *e2, le);
assert_eq!(*e1 >= *e2, ge);
// Ord
... | {
let e0 = E::E0;
let e11 = E::E1(1i);
let e12 = E::E1(2i);
let e21 = E::E2(1i, 1i);
let e22 = E::E2(1i, 2i);
// in order for both PartialOrd and Ord
let es = [e0, e11, e12, e21, e22];
for (i, e1) in es.iter().enumerate() {
for (j, e2) in es.iter().enumerate() {
let... | identifier_body |
deriving-cmp-generic-enum.rs | // Copyright 2013 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 ... | <T> {
E0,
E1(T),
E2(T,T)
}
pub fn main() {
let e0 = E::E0;
let e11 = E::E1(1i);
let e12 = E::E1(2i);
let e21 = E::E2(1i, 1i);
let e22 = E::E2(1i, 2i);
// in order for both PartialOrd and Ord
let es = [e0, e11, e12, e21, e22];
for (i, e1) in es.iter().enumerate() {
... | E | identifier_name |
offset.test.ts | /* global describe,test,expect */
/* eslint-env jest */
import offset from '../src/offset'
describe('Testing offset', () => {
test('offset element', () => {
// create mock elements
const elementMock: any = {
getClientRects: () => [
{
left: 10,
right: 20,
top: 5,
... | expect(() => { offset(div) }).toThrow('target element must be part of the dom')
})
}) |
test('offset of element that is not in the dom', () => {
const div = window.document.createElement('div') | random_line_split |
stream-client.js | var rpc = require('../src/jsonrpc');
/*
Each uses a different syntax
Responses can not be assigned to a source request if the socket version
... it sucks
Moreover jsonrpc2 knows no stream ... it may be helpful, but it is not JSON-RPC2
Michal <misablaha@gmail.com>
*/
/*
Connect to HTTP server
*/
var client = ... | (err){
console.error('RPC Error: ' + err.toString());
}
| printError | identifier_name |
stream-client.js | var rpc = require('../src/jsonrpc');
/*
Each uses a different syntax
Responses can not be assigned to a source request if the socket version
... it sucks
Moreover jsonrpc2 knows no stream ... it may be helpful, but it is not JSON-RPC2
Michal <misablaha@gmail.com>
*/
/*
Connect to HTTP server
*/
var client = ... | {
console.error('RPC Error: ' + err.toString());
} | identifier_body | |
stream-client.js | var rpc = require('../src/jsonrpc');
| Moreover jsonrpc2 knows no stream ... it may be helpful, but it is not JSON-RPC2
Michal <misablaha@gmail.com>
*/
/*
Connect to HTTP server
*/
var client = rpc.Client.create(8088, 'localhost');
client.stream('listen', [], function (err, connection){
if (err) {
return printError(err);
}
var counter = 0;... | /*
Each uses a different syntax
Responses can not be assigned to a source request if the socket version
... it sucks | random_line_split |
stream-client.js | var rpc = require('../src/jsonrpc');
/*
Each uses a different syntax
Responses can not be assigned to a source request if the socket version
... it sucks
Moreover jsonrpc2 knows no stream ... it may be helpful, but it is not JSON-RPC2
Michal <misablaha@gmail.com>
*/
/*
Connect to HTTP server
*/
var client = ... |
});
conn.call('listen', [], function (err){
if (err) {
return printError(err);
}
});
});
function printError(err){
console.error('RPC Error: ' + err.toString());
}
| {
conn.end();
} | conditional_block |
dtmdata.py | eastLine = round((east-dtminfo[1])//10)
northLine = round((north-dtminfo[2])//10)
east_delta = (east-dtminfo[1])%10
north_delta = (north-dtminfo[1])%10
return [eastLine,northLine,dtminfo[0],east_delta,north_delta,dtminfo[1],dtminfo[2]]
except:
raise Excep... |
rect.append(line)
return rect
def calculateEle(x,y,coordsys='utm'):
if coordsys == 'latlon':
east, north, zone_number, zone_letter = utm.from_latlon(x, y)
else:
east,north = x,y
try:
p = findClosestPoint(east, north)
dpx ... | if northLine < 146:
s = 144+northLine*6
else:
c = (northLine-146) // 170 +1
d = (northLine-146) % 170
s = 1024*(c)+d*6
line.append(int(d... | conditional_block |
dtmdata.py | eastLine = round((east-dtminfo[1])//10)
northLine = round((north-dtminfo[2])//10)
east_delta = (east-dtminfo[1])%10
north_delta = (north-dtminfo[1])%10
return [eastLine,northLine,dtminfo[0],east_delta,north_delta,dtminfo[1],dtminfo[2]]
except:
raise Excep... |
def getDTMFile(east,north):
try:
dtmfile = getDTMdict()
for key in dtmfile:
if north>=dtmfile[key][1] and north<=dtmfile[key][1]+50000:
if east>=dtmfile[key][0] and east<=dtmfile[key][0]+50000:
return [key,int(dtmfile[key][0]),int(d... | p1=pxc[0]
p2=pxc[1]
f = intp.RectBivariateSpline(x,y,z,kx=1, ky=1, s=0)
return f(p1,p2)[0][0]
| random_line_split |
dtmdata.py | eastLine = round((east-dtminfo[1])//10)
northLine = round((north-dtminfo[2])//10)
east_delta = (east-dtminfo[1])%10
north_delta = (north-dtminfo[1])%10
return [eastLine,northLine,dtminfo[0],east_delta,north_delta,dtminfo[1],dtminfo[2]]
except:
raise Exception("C... | (east,north):
try:
dtmfile = getDTMdict()
for key in dtmfile:
if north>=dtmfile[key][1] and north<=dtmfile[key][1]+50000:
if east>=dtmfile[key][0] and east<=dtmfile[key][0]+50000:
return [key,int(dtmfile[key][0]),int(dtmfile[key][1])]
... | getDTMFile | identifier_name |
dtmdata.py | eastLine = round((east-dtminfo[1])//10)
northLine = round((north-dtminfo[2])//10)
east_delta = (east-dtminfo[1])%10
north_delta = (north-dtminfo[1])%10
return [eastLine,northLine,dtminfo[0],east_delta,north_delta,dtminfo[1],dtminfo[2]]
except:
raise Exception("C... |
return float(data[s:s+6])/10
def getElevationArea(eastLmin,northLmin,eastLmax,northLmax,dtmfile):
rows = 5041
head = 1024
lhead = 144
blockSize = 30720
rect = []
with open("C:\\python\\dtms\\{}".format(dtmfile), 'r') as fin:
for eastLine in ra... | rows = 5041
head = 1024
lhead = 144
blockSize = 30720
eastLine = eastL
northLine = northL
with open("C:\\python\\dtms\\{}".format(dtmfile), 'r') as fin:
fin.seek(head+blockSize*eastLine)
data = fin.read(blockSize)
if northLine < 146:
... | identifier_body |
receipt.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | () {
let expected = ::rustc_serialize::hex::FromHex::from_hex("f90162a02f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee83040caeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000... | test_basic | identifier_name |
receipt.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
impl Decodable for Receipt {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
let receipt = Receipt {
state_root: try!(d.val_at(0)),
gas_used: try!(d.val_at(1)),
log_bloom: try!(d.val_at(2)),
logs: try!(d.val_at(3)),
};
Ok(receipt)
}
}
impl ... | {
s.begin_list(4);
s.append(&self.state_root);
s.append(&self.gas_used);
s.append(&self.log_bloom);
s.append(&self.logs);
} | identifier_body |
receipt.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | state_root: try!(d.val_at(0)),
gas_used: try!(d.val_at(1)),
log_bloom: try!(d.val_at(2)),
logs: try!(d.val_at(3)),
};
Ok(receipt)
}
}
impl HeapSizeOf for Receipt {
fn heap_size_of_children(&self) -> usize {
self.logs.heap_size_of_children()
}
}
/// Receipt with additional info.
#[derive(Debug, Cl... | fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
let receipt = Receipt { | random_line_split |
views.py | # Patchless XMLRPC Service for Django
# Kind of hacky, and stolen from Crast on irc.freenode.net:#django
# Self documents as well, so if you call it from outside of an XML-RPC Client
# it tells you about itself and its methods
#
# Brendan W. McAdams <brendan.mcadams@thewintergrp.com>
# SimpleXMLRPCDispatcher lets us r... |
@staff_member_required
def delete_from_queue (request, package_id):
pkg = get_object_or_404 (Package, id=package_id)
q_id = pkg.queue.id
pkg.delete ()
return redirect ('/buildfarm/queue/%d/' % q_id)
@staff_member_required
def delete_queue (request, queue_id):
queue = get_object_or_404 (Queu... | rdict = {}
q = Queue.objects.get(id=queue_id)
packages = Package.objects.filter(queue=q)
pct =float ( float(q.current) / q.length ) * 100
rdict = { 'percent' : pct, 'total': q.length, 'current': q.current, 'name_current': q.current_package_name }
json = simplejson.dumps(rdict, ensure_ascii=False)
return Http... | identifier_body |
views.py | # Patchless XMLRPC Service for Django
# Kind of hacky, and stolen from Crast on irc.freenode.net:#django
# Self documents as well, so if you call it from outside of an XML-RPC Client
# it tells you about itself and its methods
#
# Brendan W. McAdams <brendan.mcadams@thewintergrp.com>
# SimpleXMLRPCDispatcher lets us r... |
json = simplejson.dumps(rdict, ensure_ascii=False)
print json
# And send it off.
return HttpResponse( json, content_type='application/json')
else:
form = NewQueueForm ()
context = {'form': form }
return render (request, 'buildfarm/new_queue.html', context)
def queue_index(request, queue_id=No... | html = render_to_string ('buildfarm/new_queue.html', {'form_queue': form})
rdict = { 'html': html, 'tags': 'fail' } | conditional_block |
views.py | # Patchless XMLRPC Service for Django
# Kind of hacky, and stolen from Crast on irc.freenode.net:#django
# Self documents as well, so if you call it from outside of an XML-RPC Client
# it tells you about itself and its methods
#
# Brendan W. McAdams <brendan.mcadams@thewintergrp.com>
# SimpleXMLRPCDispatcher lets us r... | (request):
queues = Queue.objects.all ()
context = { 'queues': queues, 'navhint': 'queue', 'not_reload': 'true', 'form' : NewQueueForm() }
return render (request, "buildfarm/site_index.html", context)
def package_progress_json (request, queue_id):
rdict = {}
q = Queue.objects.get(id=queue_id)
packages = P... | site_index | identifier_name |
views.py | # Patchless XMLRPC Service for Django
# Kind of hacky, and stolen from Crast on irc.freenode.net:#django
# Self documents as well, so if you call it from outside of an XML-RPC Client
# it tells you about itself and its methods
#
# Brendan W. McAdams <brendan.mcadams@thewintergrp.com>
# SimpleXMLRPCDispatcher lets us r... | print json
# And send it off.
return HttpResponse( json, content_type='application/json')
else:
form = NewQueueForm ()
context = {'form': form }
return render (request, 'buildfarm/new_queue.html', context)
def queue_index(request, queue_id=None):
q = get_object_or_404 (Queue, id=queue_id)
pack... | else:
html = render_to_string ('buildfarm/new_queue.html', {'form_queue': form})
rdict = { 'html': html, 'tags': 'fail' }
json = simplejson.dumps(rdict, ensure_ascii=False)
| random_line_split |
blogs.js | $(document).ready(function () {
$('body').on('click', '.popular-next', function (e) {
e.preventDefault();
var caller = $(this),
container = $('.popular-container'),
page = caller.data('page') + 1,
url = caller.attr('href'),
request = {
... |
if (response.finish) {
container.find('.popular-next').remove();
}
}, false, true);
});
$('body').on('click', '.load-more-links', function (e) {
e.preventDefault();
var caller = $(this),
container = $('.b-post-list'),
p... | {
container.html(response.html);
} | conditional_block |
blogs.js | $(document).ready(function () {
$('body').on('click', '.popular-next', function (e) {
e.preventDefault();
var caller = $(this),
container = $('.popular-container'),
page = caller.data('page') + 1,
url = caller.attr('href'),
request = {
... | if (user !== '') {
url += '/' + user;
}
$.commonAJAX.processData(url, request, function (response) {
if (response.isSuccessful) {
container.append(response.html);
caller.data('page', page);
}
if (response.finish) {... | request = {
'page': page
};
| random_line_split |
scatter_lines_markers.py | #Autogenerated by ReportLab guiedit do not edit
from reportlab.graphics.charts.legends import Legend
from reportlab.graphics.charts.lineplots import ScatterPlot
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String
from reportlab.graphics.charts.textlabels import Label
from excelcolors import ... | self.chart.xValueAxis.labels.fontSize = 7
self.chart.xValueAxis.forceZero = 0
self.chart.data = [((100,100), (200,200), (250,210), (300,300), (400,500)), ((100,200), (200,300), (250,200), (300,400), (400, 600))]
self.chart.xValueAxis.avoidBoundFrac ... | def __init__(self,width=200,height=150,*args,**kw):
apply(Drawing.__init__,(self,width,height)+args,kw)
self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart")
self.chart.width = 115
self.chart.height = 80
self.chart.x = 30
s... | identifier_body |
scatter_lines_markers.py | #Autogenerated by ReportLab guiedit do not edit
from reportlab.graphics.charts.legends import Legend
from reportlab.graphics.charts.lineplots import ScatterPlot
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String
from reportlab.graphics.charts.textlabels import Label
from excelcolors import ... | self.chart.lineLabels.fontName = 'Helvetica'
self.chart.xValueAxis.labels.fontName = 'Helvetica'
self.chart.xValueAxis.labels.fontSize = 7
self.chart.xValueAxis.forceZero = 0
self.chart.data = [((100,100), (200,200), (250,210),... | self.chart.lines[7].strokeColor = color08
self.chart.lines[8].strokeColor = color09
self.chart.lines[9].strokeColor = color10
self.chart.fillColor = backgroundGrey
| random_line_split |
scatter_lines_markers.py | #Autogenerated by ReportLab guiedit do not edit
from reportlab.graphics.charts.legends import Legend
from reportlab.graphics.charts.lineplots import ScatterPlot
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String
from reportlab.graphics.charts.textlabels import Label
from excelcolors import ... | (self,width=200,height=150,*args,**kw):
apply(Drawing.__init__,(self,width,height)+args,kw)
self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart")
self.chart.width = 115
self.chart.height = 80
self.chart.x = 30
self.chart.y ... | __init__ | identifier_name |
scatter_lines_markers.py | #Autogenerated by ReportLab guiedit do not edit
from reportlab.graphics.charts.legends import Legend
from reportlab.graphics.charts.lineplots import ScatterPlot
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String
from reportlab.graphics.charts.textlabels import Label
from excelcolors import ... | ScatterLinesMarkers().save(formats=['pdf'],outDir=None,fnRoot='scatter_lines_markers') | conditional_block | |
help-content-module.js | /* | *
* Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Pu... | * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. | random_line_split |
plot.input.image.py | import numpy as np
from matplotlib import pyplot as plt
from random import *
def transpose_shape(x):
n = []
for i in x: n.append(i.T)
return np.array(n)
def flip_bits(x):
n = []
for idx, i in enumerate(x):
m = []
for j in i:
ch = choice([0,1])
if ch and j.s... |
idx+=1
print y[s[0]]
plt.imshow(x[s[0]], aspect=.10, cmap='gray')
plt.show()
idx = 0
s = [0, 0]
for i in x:
g = i.sum()
if y[idx] == 2:
if g > s[1]: s = [idx, g]
idx+=1
print y[s[0]]
plt.imshow(x[s[0]], aspect=.10, cmap='gray')
plt.show()
| s = [idx, g] | conditional_block |
plot.input.image.py | import numpy as np
from matplotlib import pyplot as plt
from random import *
def transpose_shape(x):
n = []
for i in x: n.append(i.T)
return np.array(n)
def flip_bits(x):
n = []
for idx, i in enumerate(x):
m = []
for j in i:
ch = choice([0,1])
if ch and j.s... | if y[idx] == 0:
if g > s[1]: s = [idx, g]
idx+=1
print y[s[0]]
plt.imshow(x[s[0]], aspect=.10, cmap='gray')
plt.show()
idx = 0
s = [0, 0]
for i in x:
g = i.sum()
if y[idx] == 2:
if g > s[1]: s = [idx, g]
idx+=1
print y[s[0]]
plt.imshow(x[s[0]], aspect=.10, cmap='gray')
plt.sho... | s = [0, 0]
for i in x:
g = i.sum() | random_line_split |
plot.input.image.py | import numpy as np
from matplotlib import pyplot as plt
from random import *
def transpose_shape(x):
n = []
for i in x: n.append(i.T)
return np.array(n)
def flip_bits(x):
|
def shuffle_rows(x):
n = []
s = set(range(x.shape[1]))
for kdx, i in enumerate(x):
out = set([idx for idx, j in enumerate(i) if not j.sum()])
shuffleable = list(s-out)
#print sorted(out)
#print i.shape
shuffle(shuffleable)
shuffleable.extend(sorted(out))
... | n = []
for idx, i in enumerate(x):
m = []
for j in i:
ch = choice([0,1])
if ch and j.sum(): #avoid flipping bits on the all zeros padded section (which has sum = 0)
#print j
j = j*-1+1
#print j, '\n'#works
m.append(j... | identifier_body |
plot.input.image.py | import numpy as np
from matplotlib import pyplot as plt
from random import *
def transpose_shape(x):
n = []
for i in x: n.append(i.T)
return np.array(n)
def | (x):
n = []
for idx, i in enumerate(x):
m = []
for j in i:
ch = choice([0,1])
if ch and j.sum(): #avoid flipping bits on the all zeros padded section (which has sum = 0)
#print j
j = j*-1+1
#print j, '\n'#works
... | flip_bits | identifier_name |
controllers.js | ]
});
}
return kendoCols;
}
function prepareWebScroller(dsType, esWebApiService, $log, GroupID, FilterID, params, esOptions) {
var xParam = {
transport: {
read: function(options) {
$log.info("*** SERVER EXECUTION *** ", JSON.stringify(options));
... |
options.success(pq);
$log.info("Executed");
});
}
},
schema: {
data: "Rows",
total: "Count"
}
};
if (esOptions) {
angular.extend(xParam, esOptions);
}
if (dsType && ... | {
$log.info(i, " ==> ", pq.Rows[i]["Code"]);
} | conditional_block |
controllers.js | [index]
});
}
return kendoCols;
}
function prepareWebScroller(dsType, esWebApiService, $log, GroupID, FilterID, params, esOptions) {
var xParam = {
transport: {
read: function(options) {
$log.info("*** SERVER EXECUTION *** ", JSON.stringify(options));
... | options.error("Now records found");
return;
}
pq.Rows = _.sortBy(pq.Rows, 'Code');
if (options.data && options.data.pageSize) {
$log.info("Page ", options.data.p... | }
if (pq.Rows.length == 0) { | random_line_split |
controllers.js | }
function prepareWebScroller(dsType, esWebApiService, $log, GroupID, FilterID, params, esOptions) {
var xParam = {
transport: {
read: function(options) {
$log.info("*** SERVER EXECUTION *** ", JSON.stringify(options));
esWebApiService.fetchPublicQuery(GroupID... | {
if ((cols && cols.length > 0) || !data) {
return cols;
}
var NumCols = Math.floor((Math.random() * 10) + 1);
var kendoCols = [];
var dtCols = Object.keys(data[0]);
var mx = Math.min(NumCols, dtCols.length);
var index;
for (index = 0; index < mx; index++) {
kendoCols... | identifier_body | |
controllers.js | ]
});
}
return kendoCols;
}
function | (dsType, esWebApiService, $log, GroupID, FilterID, params, esOptions) {
var xParam = {
transport: {
read: function(options) {
$log.info("*** SERVER EXECUTION *** ", JSON.stringify(options));
esWebApiService.fetchPublicQuery(GroupID, FilterID, params)
... | prepareWebScroller | identifier_name |
passport-init.js | var mongoose = require('mongoose')
var User = mongoose.model('User')
var LocalStrategy = require('passport-local').Strategy
var bCrypt = require('bcrypt-nodejs')
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.seriali... | };
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
}; | );
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password); | random_line_split |
passport-init.js | var mongoose = require('mongoose')
var User = mongoose.model('User')
var LocalStrategy = require('passport-local').Strategy
var bCrypt = require('bcrypt-nodejs')
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.seriali... | else {
// if there is no user, create the user
var newUser = new User();
// set the user's local credentials
newUser.username = username;
newUser.password = createHash(password);
// save the user
newUser.save(function(err) {
if (err){
console.log('Error in Saving user:... | {
console.log('User already exists with username: '+username);
return done(null, false);
} | conditional_block |
ragna.py | import re
def read_lua():
PATTERN = r'\s*\[(?P<id>\d+)\] = {\s*unidentifiedDisplayName = ' \
r'"(?P<unidentifiedDisplayName>[^"]+)",\s*unidentifie' \
r'dResourceName = "(?P<unidentifiedResourceName>[^"]+' \
r')",\s*unidentifiedDescriptionName = {\s*"(?P<uniden' \
... | return 0
"""
for group in test.groupdict():
for k, v in group.items():
print(k + ' : ' + v)
print()
"""
read_lua() | for item in test:
if item[0] == '502':
print(item)
print(len(test))
| random_line_split |
ragna.py | import re
def read_lua():
PATTERN = r'\s*\[(?P<id>\d+)\] = {\s*unidentifiedDisplayName = ' \
r'"(?P<unidentifiedDisplayName>[^"]+)",\s*unidentifie' \
r'dResourceName = "(?P<unidentifiedResourceName>[^"]+' \
r')",\s*unidentifiedDescriptionName = {\s*"(?P<uniden' \
... |
print(len(test))
return 0
"""
for group in test.groupdict():
for k, v in group.items():
print(k + ' : ' + v)
print()
"""
read_lua() | if item[0] == '502':
print(item) | conditional_block |
ragna.py | import re
def | ():
PATTERN = r'\s*\[(?P<id>\d+)\] = {\s*unidentifiedDisplayName = ' \
r'"(?P<unidentifiedDisplayName>[^"]+)",\s*unidentifie' \
r'dResourceName = "(?P<unidentifiedResourceName>[^"]+' \
r')",\s*unidentifiedDescriptionName = {\s*"(?P<uniden' \
r'tifiedDescr... | read_lua | identifier_name |
ragna.py | import re
def read_lua():
|
"""
for group in test.groupdict():
for k, v in group.items():
print(k + ' : ' + v)
print()
"""
read_lua() | PATTERN = r'\s*\[(?P<id>\d+)\] = {\s*unidentifiedDisplayName = ' \
r'"(?P<unidentifiedDisplayName>[^"]+)",\s*unidentifie' \
r'dResourceName = "(?P<unidentifiedResourceName>[^"]+' \
r')",\s*unidentifiedDescriptionName = {\s*"(?P<uniden' \
r'tifiedDescriptionNam... | identifier_body |
quickFixModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
if (this._editor.getModel()
&& CodeActionProviderRegistry.has(this._editor.getModel())
&& !this._editor.getConfiguration().readOnly) {
this._quickFixOracle = new QuickFixOracle(this._editor, this._markerService, p => this._onDidChangeFixes.fire(p));
this._quickFixOracle.trigger('auto');
}
}
trigger... | } | random_line_split |
quickFixModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
export interface QuickFixComputeEvent {
type: 'auto' | 'manual';
range: IRange;
position: IPosition;
fixes: TPromise<CodeAction[]>;
}
export class QuickFixModel {
private _editor: ICommonCodeEditor;
private _markerService: IMarkerService;
private _quickFixOracle: QuickFixOracle;
private _onDidChangeFixes ... | {
const pos = this._editor.getPosition();
const model = this._editor.getModel();
const info = model.getWordAtPosition(pos);
if (info) {
return {
startLineNumber: pos.lineNumber,
startColumn: info.startColumn,
endLineNumber: pos.lineNumber,
endColumn: info.endColumn
};
}
return undefine... | identifier_body |
quickFixModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
private _rangeAtPosition(): IRange {
// (1) check with non empty selection
const selection = this._editor.getSelection();
if (!selection.isEmpty()) {
return selection;
}
// (2) check with diagnostics markers
const marker = this._markerAtPosition();
if (marker) {
return Range.lift(marker);
... | {
this._currentRange = range;
this._signalChange({
type: 'auto',
range,
position: this._editor.getPosition(),
fixes: range && getCodeActions(this._editor.getModel(), this._editor.getModel().validateRange(range))
});
} | conditional_block |
quickFixModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): Event<QuickFixComputeEvent> {
return this._onDidChangeFixes.event;
}
private _update(): void {
if (this._quickFixOracle) {
this._quickFixOracle.dispose();
this._quickFixOracle = undefined;
this._onDidChangeFixes.fire(undefined);
}
if (this._editor.getModel()
&& CodeActionProviderRegistry.ha... | onDidChangeFixes | identifier_name |
_adapters.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2007 - 2015
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | (self, name, default=None):
""" :See: ``tdi.tools.htmlform.ParameterAdapterInterface`` """
return self.param.get(name, default)
def getlist(self, name):
""" :See: ``tdi.tools.htmlform.ParameterAdapterInterface`` """
if name in self.param:
return [self.param[name]]
... | getfirst | identifier_name |
_adapters.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2007 - 2015
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... |
__author__ = r"Andr\xe9 Malo".encode('ascii').decode('unicode_escape')
__docformat__ = "restructuredtext en"
__all__ = [
'DictParameterAdapter', 'ListDictParameterAdapter',
'MultiDictParameterAdapter', 'NullParameterAdapter',
]
from ._interfaces import ParameterAdapterInterface
class DictParameterAdapter(ob... | __doc__ = __doc__.encode('ascii').decode('unicode_escape') | conditional_block |
_adapters.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2007 - 2015
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | Otherwise ``getfirst`` will return the first element and
``getlist`` will return a shallow copy of the sequence as a
``list``.
"""
self.param = param
def getfirst(self, name, default=None):
""" :See: ``tdi.tools.htmlform.ParameterAdapterInterface`` """
... | Parameters. Empty sequences act as if the key was not present. | random_line_split |
_adapters.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2007 - 2015
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | self.param = param
def getfirst(self, name, default=None):
""" :See: ``tdi.tools.htmlform.ParameterAdapterInterface`` """
try:
result = self.param[name]
except KeyError:
pass
else:
if result:
return result[0]
return... | """
HTMLForm parameter adapter from a dict of sequences
:IVariables:
`param` : dict of sequences
Parameters
"""
__implements__ = [ParameterAdapterInterface]
def __init__(self, param):
"""
Initialization
:Parameters:
`param` : dict of sequences
... | identifier_body |
reset.js | 'use strict'
/* global describe it beforeEach afterEach */
const cli = require('heroku-cli-util')
const { expect } = require('chai') | name: 'postgres-1',
plan: { name: 'heroku-postgresql:standard-0' }
}
const fetcher = () => {
return {
addon: () => addon
}
}
const cmd = proxyquire('../../commands/reset', {
'../lib/fetcher': fetcher
})
describe('pg:reset', () => {
let api, pg
beforeEach(() => {
api = nock('https://api.heroku.c... | const nock = require('nock')
const proxyquire = require('proxyquire')
const addon = {
id: 1, | random_line_split |
code.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Http } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable, Subject, Subscription } from 'rxjs';
import { CodeLayer } from '../core/model/code-layer.model';
import { CodeService } from '../core/service... |
}
focusElement(e: Event) {
console.log(e);
this.focusOn = e.srcElement.getAttribute('data-layer');
this.focusDiv = true;
}
ngOnInit() {
}
ngOnDestroy() {
if(this.urlSubscription) this.urlSubscription.unsubscribe();
if(this.codeSubscription) this.codeSubscription.unsubscribe();
}
r... | {
this.showCode = true;
} | conditional_block |
code.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Http } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable, Subject, Subscription } from 'rxjs';
import { CodeLayer } from '../core/model/code-layer.model';
import { CodeService } from '../core/service... | }
removeFocus() {
this.focusOn = null;
this.focusDiv = false;
}
} | random_line_split | |
code.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Http } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable, Subject, Subscription } from 'rxjs';
import { CodeLayer } from '../core/model/code-layer.model';
import { CodeService } from '../core/service... | () {
if(this.urlSubscription) this.urlSubscription.unsubscribe();
if(this.codeSubscription) this.codeSubscription.unsubscribe();
}
removeFocus() {
this.focusOn = null;
this.focusDiv = false;
}
}
| ngOnDestroy | identifier_name |
ContainerComponent.js | 'use strict';
exports.__esModule = true;
var _slice = Array.prototype.slice;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a func... | exports['default'] = ContainerComponent;
module.exports = exports['default']; | container: _react2['default'].PropTypes.object.isRequired
};
| random_line_split |
ContainerComponent.js | 'use strict';
exports.__esModule = true;
var _slice = Array.prototype.slice;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a func... | () {
_classCallCheck(this, ContainerComponent);
_Container.apply(this, arguments);
}
ContainerComponent.prototype.componentDidMount = function componentDidMount() {
var _Container$prototype$componentDidMount;
(_Container$prototype$componentDidMount = _Container.prototype.componentDidMount).call.a... | ContainerComponent | identifier_name |
ContainerComponent.js | 'use strict';
exports.__esModule = true;
var _slice = Array.prototype.slice;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) |
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enum... | { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } | identifier_body |
2PopDNAnorec_1_76.js | USETEXTLINKS = 1
STARTALLOPEN = 0
WRAPTEXT = 1
PRESERVESTATE = 0
HIGHLIGHT = 1
ICONPATH = 'file:////Users/eric/github/popgenDB/sims_for_structure_paper/2PopDNAnorec_0.5_1000/' //change if the gif's folder is a subfolder, for example: 'images/'
foldersTree = gFld("<i>ARLEQUIN RESULTS (2PopDNAnorec_1_76.arp)</i>", ""... | aux2 = insFld(aux1, gFld("Genetic structure (samp=pop)", "2PopDNAnorec_1_76.xml#31_07_18at17_02_31_pop_gen_struct"))
insDoc(aux2, gLnk("R", "AMOVA", "2PopDNAnorec_1_76.xml#31_07_18at17_02_31_pop_amova"))
insDoc(aux2, gLnk("R", "Pairwise distances", "2PopDNAnorec_1_76.xml#31_07_18at17_02_31_pop_pairw_diff")) | random_line_split | |
mod.rs | //! =====================================================================================
//!
//! Filename: movement/mod.rs
//!
//! Description: Components to update actor's movement.
//!
//! Version: 1.0
//! Created: 13/06/16 22:43:05 | //!
//! Author: Anicka Burova
//!
//! =====================================================================================
extern crate rand;
use rand::Rng;
use collision::{Aabb};
use tcod::input::KeyCode;
use component::Component;
use util::{Offset};
use actor::Actor;
use game::Game;
use world::World;
pu... | //! Revision: none
//! Compiler: rust | random_line_split |
mod.rs | //! =====================================================================================
//!
//! Filename: movement/mod.rs
//!
//! Description: Components to update actor's movement.
//!
//! Version: 1.0
//! Created: 13/06/16 22:43:05
//! Revision: none
//! Compiler: rust
//!
/... |
}
pub struct InputMovement;
impl Component for InputMovement {
fn update(&mut self, actor: &mut Actor, game: &Game, _: &mut World) {
let mut offset = Offset::new(0,0);
let key = game.last_key;
match key {
KeyCode::Up => offset.y = -1,
KeyCode::Down =>... | {
let offset_x = rand::thread_rng().gen_range(-1,2);
let new_pos = actor.position + Offset::new(offset_x, 0);
let mut res = actor.position;
if game.window_bounds.contains(new_pos) {
res = new_pos;
}
let offset_y = rand::thread_rng().gen_range(-1,2);
le... | identifier_body |
mod.rs | //! =====================================================================================
//!
//! Filename: movement/mod.rs
//!
//! Description: Components to update actor's movement.
//!
//! Version: 1.0
//! Created: 13/06/16 22:43:05
//! Revision: none
//! Compiler: rust
//!
/... | ;
impl Component for InputMovement {
fn update(&mut self, actor: &mut Actor, game: &Game, _: &mut World) {
let mut offset = Offset::new(0,0);
let key = game.last_key;
match key {
KeyCode::Up => offset.y = -1,
KeyCode::Down => offset.y = 1,
K... | InputMovement | identifier_name |
mod.rs | //! =====================================================================================
//!
//! Filename: movement/mod.rs
//!
//! Description: Components to update actor's movement.
//!
//! Version: 1.0
//! Created: 13/06/16 22:43:05
//! Revision: none
//! Compiler: rust
//!
/... |
actor.position = res;
}
}
pub struct InputMovement;
impl Component for InputMovement {
fn update(&mut self, actor: &mut Actor, game: &Game, _: &mut World) {
let mut offset = Offset::new(0,0);
let key = game.last_key;
match key {
KeyCode::Up => offset.y = -1... | {
res = new_pos;
} | conditional_block |
case-blocks.js | function pug_escape(e) {
var a = "" + e, t = pug_match_html.exec(a);
if (!t) return e;
var r, c, n, s = "";
for (r = t.index, c = 0; r < a.length; r++) {
switch (a.charCodeAt(r)) {
case 34: | n = "&";
break;
case 60:
n = "<";
break;
case 62:
n = ">";
break;
default:
continue;
}
c !== r && (s += a.substring(c, r)), c = r + 1, s += n;
}
return c !== r ? s + a.s... | n = """;
break;
case 38: | random_line_split |
case-blocks.js | function pug_escape(e) | break;
default:
continue;
}
c !== r && (s += a.substring(c, r)), c = r + 1, s += n;
}
return c !== r ? s + a.substring(c, r) : s;
}
var pug_match_html = /["&<>]/;
function template(locals) {
var pug_html = "", pug_mixins = {}, pug_interp;
pug_html = ... | {
var a = "" + e, t = pug_match_html.exec(a);
if (!t) return e;
var r, c, n, s = "";
for (r = t.index, c = 0; r < a.length; r++) {
switch (a.charCodeAt(r)) {
case 34:
n = """;
break;
case 38:
n = "&";
break;
... | identifier_body |
case-blocks.js | function pug_escape(e) {
var a = "" + e, t = pug_match_html.exec(a);
if (!t) return e;
var r, c, n, s = "";
for (r = t.index, c = 0; r < a.length; r++) | }
c !== r && (s += a.substring(c, r)), c = r + 1, s += n;
}
return c !== r ? s + a.substring(c, r) : s;
}
var pug_match_html = /["&<>]/;
function template(locals) {
var pug_html = "", pug_mixins = {}, pug_interp;
pug_html = pug_html + "<html><body>";
var friends = 1;
switch (f... | {
switch (a.charCodeAt(r)) {
case 34:
n = """;
break;
case 38:
n = "&";
break;
case 60:
n = "<";
break;
case 62:
n = ">";
break;
default:
... | conditional_block |
case-blocks.js | function pug_escape(e) {
var a = "" + e, t = pug_match_html.exec(a);
if (!t) return e;
var r, c, n, s = "";
for (r = t.index, c = 0; r < a.length; r++) {
switch (a.charCodeAt(r)) {
case 34:
n = """;
break;
case 38:
n = "&";
... | (locals) {
var pug_html = "", pug_mixins = {}, pug_interp;
pug_html = pug_html + "<html><body>";
var friends = 1;
switch (friends) {
case 0:
pug_html = pug_html + "<p>you have no friends</p>";
break;
case 1:
pug_html = pug_html + "<p>you have a friend</p>";
b... | template | identifier_name |
chain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gdb
import pwndbg.abi
import pwndbg.color.chain as C
import pwndbg.color.memory as M
import pwndbg.color.theme as theme
import pwndbg.enhance
import pwndbg.memory
import pwndbg.symbol
import pwndbg.typeinfo
import pwndbg.vmmap
LIMIT = pwndbg.config.Parameter('dere... | (address, limit=LIMIT, offset=0, hard_stop=None, hard_end=0, include_start=True):
"""
Recursively dereferences an address. For bare metal, it will stop when the address is not in any of vmmap pages to avoid redundant dereference.
Arguments:
address(int): the first address to begin dereferencing
... | get | identifier_name |
chain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gdb
import pwndbg.abi
import pwndbg.color.chain as C
import pwndbg.color.memory as M
import pwndbg.color.theme as theme
import pwndbg.enhance
import pwndbg.memory
import pwndbg.symbol
import pwndbg.typeinfo
import pwndbg.vmmap
LIMIT = pwndbg.config.Parameter('dere... |
if hard_stop is not None and address == hard_stop:
result.append(hard_end)
break
try:
address = address + offset
# Avoid redundant dereferences in bare metal mode by checking
# if address is in any of vmmap pages
if not pwndbg.a... | break | conditional_block |
chain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gdb
import pwndbg.abi
import pwndbg.color.chain as C
import pwndbg.color.memory as M
import pwndbg.color.theme as theme
import pwndbg.enhance
import pwndbg.memory
import pwndbg.symbol
import pwndbg.typeinfo
import pwndbg.vmmap
LIMIT = pwndbg.config.Parameter('dere... | offset(int): Offset into the address to get the next pointer
hard_stop(int): Value to stop on
hard_end: Value to append when hard_stop is reached: null, value of hard stop, a string.
Returns:
A string representing pointers of each address and reference
Strings format: 0x0804... | limit(int): Number of valid pointers
code(bool): Hint that indicates the value may be an instruction | random_line_split |
chain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gdb
import pwndbg.abi
import pwndbg.color.chain as C
import pwndbg.color.memory as M
import pwndbg.color.theme as theme
import pwndbg.enhance
import pwndbg.memory
import pwndbg.symbol
import pwndbg.typeinfo
import pwndbg.vmmap
LIMIT = pwndbg.config.Parameter('dere... | break
if hard_stop is not None and address == hard_stop:
result.append(hard_end)
break
try:
address = address + offset
# Avoid redundant dereferences in bare metal mode by checking
# if address is in any of vmmap pages
... | """
Recursively dereferences an address. For bare metal, it will stop when the address is not in any of vmmap pages to avoid redundant dereference.
Arguments:
address(int): the first address to begin dereferencing
limit(int): number of valid pointers
offset(int): offset into the address... | identifier_body |
Xml2DCaseTree.ts | ///<reference path='../../DefinitelyTyped/jquery/jquery.d.ts'/>
///<reference path='./DCaseTree.ts'/>
function outputError(o : any) : void {
console.log("error: " + o);
}
module Xml2DCaseTree {
export class DCaseLink {
source : string;
target : string;
constructor(source : string, target : string) {
thi... | self.addNodeIdToMap(IdText);
var node : DCaseTree.DCaseNode = new DCaseTree[NodeType + "Node"](Description, null, self.nodeIdMap[IdText]);
node.NodeName = NodeName;
self.nodes[IdText] = node;
return null;
});
$(xmlText).find("rootBasicLink").each(function(index : any, elem : Element) : JQue... | var Description : string = $(this).attr("desc");
var NodeName : string = $(this).attr("name");
| random_line_split |
Xml2DCaseTree.ts | ///<reference path='../../DefinitelyTyped/jquery/jquery.d.ts'/>
///<reference path='./DCaseTree.ts'/>
function outputError(o : any) : void {
console.log("error: " + o);
}
module Xml2DCaseTree {
export class DCaseLink {
source : string;
target : string;
constructor(source : string, target : string) {
thi... | () {
}
addNodeIdToMap(IdText : string) : void {
if(!(IdText in this.nodeIdMap)) {
if(this.NodeCount == 0) {
this.rootNodeIdText = IdText;
}
this.nodeIdMap[IdText] = this.NodeCount;
this.NodeCount += 1;
}
}
makeTree(nodeIdText : string) : DCaseTree.DCaseNode {
var thisNode : DCas... | constructor | identifier_name |
Xml2DCaseTree.ts | ///<reference path='../../DefinitelyTyped/jquery/jquery.d.ts'/>
///<reference path='./DCaseTree.ts'/>
function outputError(o : any) : void {
console.log("error: " + o);
}
module Xml2DCaseTree {
export class DCaseLink {
source : string;
target : string;
constructor(source : string, target : string) {
thi... | }
}
}
return thisNode;
}
parseXmlWeaver(xmlText: string): DCaseTree.TopGoalNode {
var self : Converter = this;
$($.parseXML(xmlText).getElementsByTagName("node")).each(function(index : any, elem : Element) : JQuery {
var NodeType : string = $(this).attr("type");
var IdText : string ... | {
var childNodeIdText : string;
if(link.source == nodeIdText) {
childNodeIdText = link.target;
}
else {
childNodeIdText = link.source;
}
delete this.links[linkIdText];
var childNode : DCaseTree.DCaseNode = this.nodes[childNodeIdText];
if(childNode.NodeType == "Cont... | conditional_block |
test_statistics.py | import numpy as np
import pytest
from numpy.testing import assert_allclose
try:
import scipy
except ImportError:
HAS_SCIPY = False
else:
HAS_SCIPY = True
import astropy.units as u
from astropy.timeseries.periodograms.lombscargle import LombScargle
from astropy.timeseries.periodograms.lombscargle._statisti... | (normalization, use_errs, units):
t, y, dy, fmax = null_data(units=units)
if not use_errs:
dy = None
fap = np.linspace(0, 1, 11)
method = 'bootstrap'
method_kwds = METHOD_KWDS['bootstrap']
ls = LombScargle(t, y, dy, normalization=normalization)
z = ls.false_alarm_level(fap, maximu... | test_inverse_bootstrap | identifier_name |
test_statistics.py | import numpy as np
import pytest
from numpy.testing import assert_allclose
try:
import scipy
except ImportError:
HAS_SCIPY = False
else:
|
import astropy.units as u
from astropy.timeseries.periodograms.lombscargle import LombScargle
from astropy.timeseries.periodograms.lombscargle._statistics import (fap_single, inv_fap_single,
METHODS)
from astropy.timeseries.periodograms.lombscargle.... | HAS_SCIPY = True | conditional_block |
test_statistics.py | import numpy as np
import pytest
from numpy.testing import assert_allclose
try:
import scipy
except ImportError:
HAS_SCIPY = False
else:
HAS_SCIPY = True
import astropy.units as u
from astropy.timeseries.periodograms.lombscargle import LombScargle
from astropy.timeseries.periodograms.lombscargle._statisti... | # Test that observed power is distributed according to the theoretical pdf
hist, bins = np.histogram(power, 30, density=True)
midpoints = 0.5 * (bins[1:] + bins[:-1])
pdf = ls.distribution(midpoints)
assert_allclose(hist, pdf, rtol=0.05, atol=0.05 * pdf[0])
@pytest.mark.parame... | t, y, dy, fmax = null_data(units=units)
if not with_errors:
dy = None
ls = LombScargle(t, y, dy, normalization=normalization)
freq, power = ls.autopower(maximum_frequency=fmax)
z = np.linspace(0, power.max(), 1000)
# Test that pdf and cdf are consistent
dz = z[1] - z[0]
z_mid = z[... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.