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 |
|---|---|---|---|---|
explicit-self.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(), 10);
assert_eq!(x.quux(), 10);
l... | pub fn foo(@self) -> int { *self.x.a }
pub fn bar(~self) -> int { *self.x.a } | random_line_split |
explicit-self.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (shape: &shape) -> f64 {
match *shape {
circle(_, radius) => 0.5 * tau * radius * radius,
rectangle(_, ref size) => size.w * size.h
}
}
impl shape {
// self is in the implicit self region
pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T)
-> &'r T {... | compute_area | identifier_name |
explicit-self.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn bar(~self) -> int { *self.x.a }
pub fn quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(... | { *self.x.a } | identifier_body |
credit_seat_spec.js | define([
'collections/credit_provider_collection',
'ecommerce',
'models/course_seats/credit_seat'
],
function (CreditProviderCollection,
ecommerce,
CreditSeat) {
'use strict';
var model,
data = {
id: 9,
... | (credit_provider, expected_msg) {
model.set('credit_provider', credit_provider);
expect(model.validate().credit_provider).toEqual(expected_msg);
expect(model.isValid(true)).toBeFalsy();
}
it('should do nothing if the credit pro... | assertCreditProviderInvalid | identifier_name |
credit_seat_spec.js | define([
'collections/credit_provider_collection',
'ecommerce',
'models/course_seats/credit_seat'
],
function (CreditProviderCollection,
ecommerce,
CreditSeat) {
'use strict';
var model,
data = {
id: 9,
... |
it('should do nothing if the credit provider is valid', function () {
model.set('credit_provider', ecommerce.credit.providers.at(0).get('id'));
expect(model.validate().credit_provider).toBeUndefined();
});
it('should return a mes... | {
model.set('credit_provider', credit_provider);
expect(model.validate().credit_provider).toEqual(expected_msg);
expect(model.isValid(true)).toBeFalsy();
} | identifier_body |
credit_seat_spec.js | define([
'collections/credit_provider_collection',
'ecommerce',
'models/course_seats/credit_seat'
],
function (CreditProviderCollection,
ecommerce,
CreditSeat) {
'use strict';
var model,
data = {
id: 9,
... | });
it('should return a message if the credit provider is not set', function () {
var msg = 'All credit seats must have a credit provider.',
values = [null, undefined, ''];
values.forEach(function (value) {
... | }
it('should do nothing if the credit provider is valid', function () {
model.set('credit_provider', ecommerce.credit.providers.at(0).get('id'));
expect(model.validate().credit_provider).toBeUndefined(); | random_line_split |
manageuserdirectories.py | # This file is part of the mantidqt package
#
# Copyright (C) 2017 mantidproject
#
# 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) an... | ManageUserDirectories = import_qtlib('_widgetscore', 'mantidqt.widgets', 'ManageUserDirectories') | random_line_split | |
chooser_exception_list.ts | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* 'chooser-exception-list' shows a list of chooser exceptions for a given
* chooser type.
*/
import 'chrome://resources/cr_element... | ,
},
/**
* The string ID of the chooser type that this element is displaying data
* for.
* See site_settings/constants.js for possible values.
*/
chooserType: {
observer: 'chooserTypeChanged_',
type: String,
value: ChooserType.NONE,
},
... | {
return [];
} | identifier_body |
chooser_exception_list.ts | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* 'chooser-exception-list' shows a list of chooser exceptions for a given
* chooser type.
*/
import 'chrome://resources/cr_element... | () {
return [];
},
},
/**
* The string ID of the chooser type that this element is displaying data
* for.
* See site_settings/constants.js for possible values.
*/
chooserType: {
observer: 'chooserTypeChanged_',
type: String,
value:... | value | identifier_name |
chooser_exception_list.ts | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* 'chooser-exception-list' shows a list of chooser exceptions for a given
* chooser type.
*/
import 'chrome://resources/cr_element... |
}
}
declare global {
interface HTMLElementTagNameMap {
'chooser-exception-list': ChooserExceptionListElement;
}
}
customElements.define(
ChooserExceptionListElement.is, ChooserExceptionListElement);
| {
// The chooser objects have not been changed, so check if their site
// permissions have changed. The |exceptions| and |this.chooserExceptions|
// arrays should be the same length.
const siteUidGetter = (x: SiteException) =>
x.origin + x.embeddingOrigin + x.incognito;
exception... | conditional_block |
chooser_exception_list.ts | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* 'chooser-exception-list' shows a list of chooser exceptions for a given
* chooser type.
*/
import 'chrome://resources/cr_element... | this.emptyListMessage_ = this.i18n('noHidDevicesFound');
break;
case ChooserType.BLUETOOTH_DEVICES:
this.emptyListMessage_ = this.i18n('noBluetoothDevicesFound');
break;
default:
this.emptyListMessage_ = '';
}
this.populateList_();
}
/**
* @return tru... | case ChooserType.HID_DEVICES: | random_line_split |
restaurant.js | 1) {
return dishes[xx];
}
}
}
}
self.deliveryDiff = function(total) {
var diff = parseFloat(self.delivery_min - total).toFixed(2);
return diff;
}
self.meetDeliveryMin = function(total) {
return total < parseFloat(self.delivery_min) ? true : false;
}
self.dateFromItem = function(item, offset... |
}
}
// it means the restaurant will not be opened for the next 24 hours
if( self.next_open_time ){
self._opensIn = timestampDiff( Date.parse( self.next_open_time ), now_time );
if( self._opensIn <= 60 * 60 ){
self._opensIn_formatted = formatTime( self._opensIn, self.next_open_time_message );
}
... | {
self._opensIn = timestampDiff( self.hours[ x ]._from_time, now_time );
if( self._opensIn <= 60 * 60 ){
self._opensIn_formatted = formatTime( self._opensIn );
return;
}
} | conditional_block |
restaurant.js | 1) {
return dishes[xx];
}
}
}
}
self.deliveryDiff = function(total) {
var diff = parseFloat(self.delivery_min - total).toFixed(2);
return diff;
}
self.meetDeliveryMin = function(total) {
return total < parseFloat(self.delivery_min) ? true : false;
}
self.dateFromItem = function(item, offset... | return true;
}
self.opensIn( now );
if( self._opensIn && self._opensIn < ( 3600 ) ){
return true;
}
return false;
}
/*
** Open/Close check methods
*/
// return true if the restaurant is open
self.open = function( now, ignoreOpensClosesInCalc ) {
if( !ignoreOpensClosesInCalc ){
self.tagfy( '... | self.openRestaurantPage = function( now ){
// See 2662
now = self.getNow( now );
if( self.open( now, true ) ){ | random_line_split |
backbone.states.js | var State = Backbone.State = function(options) {
options || (options = {});
};
_.extend(State.prototype, Backbone.Events, {
classes: [],
before: null,
on: null,
after: null,
events: {},
triggers: [],
multistate: [],
_isStateDescribedInSet: function( set, state ) {
var ... | isStateDescribedInAllowed: function( state ) {
return _isStateDescribedInSet( this.multistate.allow, state );
},
isStateDescribedInDisallowed: function( state ) {
return _isStateDescribedInSet( this.multistate.disallow, state );
},
isStatePermitted: function( state ) {
var allowed = false;
... | random_line_split | |
backbone.states.js | var State = Backbone.State = function(options) {
options || (options = {});
};
_.extend(State.prototype, Backbone.Events, {
classes: [],
before: null,
on: null,
after: null,
events: {},
triggers: [],
multistate: [],
_isStateDescribedInSet: function( set, state ) {
var ... |
else { return null; }
},
set classes( newClasses ) {
if( !$this.el)
if( typeof newClasses === 'string' ) {
this.$el.attr('class', newClasses);
} else {
this.$el.attr('class', newClasses.join(' '));
}
},
createState: function( name, state ) {
state = (typeof state === ... | { return _.toArray( this.$el.attr('class').split(/\s+/) ); } | conditional_block |
backbone.states.js | var State = Backbone.State = function(options) {
options || (options = {});
};
_.extend(State.prototype, Backbone.Events, {
classes: [],
before: null,
on: null,
after: null,
events: {},
triggers: [],
multistate: [],
_isStateDescribedInSet: function( set, state ) {
var ... | ( ) {
if(this.$el) { return _.toArray( this.$el.attr('class').split(/\s+/) ); }
else { return null; }
},
set classes( newClasses ) {
if( !$this.el)
if( typeof newClasses === 'string' ) {
this.$el.attr('class', newClasses);
} else {
this.$el.attr('class', newClasses.join(' '));... | classes | identifier_name |
backbone.states.js | var State = Backbone.State = function(options) {
options || (options = {});
};
_.extend(State.prototype, Backbone.Events, {
classes: [],
before: null,
on: null,
after: null,
events: {},
triggers: [],
multistate: [],
_isStateDescribedInSet: function( set, state ) {
var ... | ,
set classes( newClasses ) {
if( !$this.el)
if( typeof newClasses === 'string' ) {
this.$el.attr('class', newClasses);
} else {
this.$el.attr('class', newClasses.join(' '));
}
},
createState: function( name, state ) {
state = (typeof state === State) ? state : new State( state )... | {
if(this.$el) { return _.toArray( this.$el.attr('class').split(/\s+/) ); }
else { return null; }
} | identifier_body |
sweep.py | # coding=utf-8
# Copyright 2018 The DisentanglementLib 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
#
# Un... |
class AbstractReasoningStudyV1(study.Study):
"""Defines the study for the paper."""
def get_model_config(self, model_num=0):
"""Returns model bindings and config file."""
config = get_config()[model_num]
model_bindings = h.to_bindings(config)
model_config_file = resources.get_file(
"conf... | """Returns the hyperparameter configs for different experiments."""
arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1)
arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1)
architecture = h.zipit([arch_enc, arch_dec])
return h.product([
get_datasets(),
architecture,
... | identifier_body |
sweep.py | # coding=utf-8
# Copyright 2018 The DisentanglementLib 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
#
# Un... |
gammas = h.sweep("factor_vae.gamma",
h.discrete([10., 20., 30., 40., 50., 100.]))
config_factor_vae = h.zipit([model_name, gammas, model_fn, discr_fn])
# DIP-VAE-I config.
model_name = h.fixed("model.name", "dip_vae_i")
model_fn = h.fixed("model.model", "@dip_vae()")
lambda_od = h.sweep... | # FactorVAE config.
model_name = h.fixed("model.name", "factor_vae")
model_fn = h.fixed("model.model", "@factor_vae()")
discr_fn = h.fixed("discriminator.discriminator_fn", "@fc_discriminator") | random_line_split |
sweep.py | # coding=utf-8
# Copyright 2018 The DisentanglementLib 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
#
# Un... | (num):
"""Returns random seeds."""
return h.sweep("model.random_seed", h.categorical(list(range(num))))
def get_default_models():
"""Our default set of models (6 model * 6 hyperparameters=36 models)."""
# BetaVAE config.
model_name = h.fixed("model.name", "beta_vae")
model_fn = h.fixed("model.model", "@va... | get_seeds | identifier_name |
main.py | ''' Controller for the application '''
import logging
import sys
import traceback
import forms
from models import Settings
from flask import Flask, render_template
from google.appengine.api import app_identity # pylint: disable=E0401
from google.appengine.api import mail # pylint: disable=E0401
from google.appengine.ap... |
return render_template('form.html', title="Message", form=message_form)
def send_mail(their_email, their_message):
''' Send an email message to me '''
message = mail.EmailMessage(sender=app_identity.get_application_id() +
'@appspot.gserviceaccount.com>')
message.subject... | send_mail(message_form.email.data, message_form.message.data)
return render_template('submitted_form.html', title="Thanks", form=message_form) | conditional_block |
main.py | ''' Controller for the application '''
import logging
import sys
import traceback
import forms
from models import Settings
from flask import Flask, render_template
from google.appengine.api import app_identity # pylint: disable=E0401
from google.appengine.api import mail # pylint: disable=E0401
from google.appengine.ap... |
def send_mail(their_email, their_message):
''' Send an email message to me '''
message = mail.EmailMessage(sender=app_identity.get_application_id() +
'@appspot.gserviceaccount.com>')
message.subject = 'Message from Bagbatch Website'
message.to = Settings.get('EMAIL')
... | ''' Show the message form for the user to fill in '''
message_form = forms.MessageForm()
if message_form.validate_on_submit():
send_mail(message_form.email.data, message_form.message.data)
return render_template('submitted_form.html', title="Thanks", form=message_form)
return render_template... | identifier_body |
main.py | ''' Controller for the application '''
import logging
import sys
import traceback
import forms
from models import Settings
from flask import Flask, render_template
from google.appengine.api import app_identity # pylint: disable=E0401
from google.appengine.api import mail # pylint: disable=E0401
from google.appengine.ap... | ''' Show the message form for the user to fill in '''
message_form = forms.MessageForm()
if message_form.validate_on_submit():
send_mail(message_form.email.data, message_form.message.data)
return render_template('submitted_form.html', title="Thanks", form=message_form)
return render_temp... | app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.route('/', methods=['GET', 'POST'])
def form(): | random_line_split |
main.py | ''' Controller for the application '''
import logging
import sys
import traceback
import forms
from models import Settings
from flask import Flask, render_template
from google.appengine.api import app_identity # pylint: disable=E0401
from google.appengine.api import mail # pylint: disable=E0401
from google.appengine.ap... | (their_email, their_message):
''' Send an email message to me '''
message = mail.EmailMessage(sender=app_identity.get_application_id() +
'@appspot.gserviceaccount.com>')
message.subject = 'Message from Bagbatch Website'
message.to = Settings.get('EMAIL')
message.body ... | send_mail | identifier_name |
server.js | var eio = require('engine.io'),
HashMap = require('hashmap').HashMap;
function | () {
var self = this;
self.endpoint = {
port: 44444,
host: 'localhost'
};
self.server = eio.listen(self.endpoint.port, self.endpoint.host);
self.server.on('connection', function(socket){
console.log('Server :: Connection from socket: ' + socket.id);
socket.on('message', function(msg){
... | Server | identifier_name |
server.js | var eio = require('engine.io'),
HashMap = require('hashmap').HashMap;
function Server() | });
socket.on('disconnect', function(){
console.log('Server :: Disconnect event from socket: ' + socket.id);
});
});
}
var server = new Server();
| {
var self = this;
self.endpoint = {
port: 44444,
host: 'localhost'
};
self.server = eio.listen(self.endpoint.port, self.endpoint.host);
self.server.on('connection', function(socket){
console.log('Server :: Connection from socket: ' + socket.id);
socket.on('message', function(msg){
c... | identifier_body |
server.js | var eio = require('engine.io'),
HashMap = require('hashmap').HashMap;
function Server() {
var self = this;
self.endpoint = {
port: 44444, | host: 'localhost'
};
self.server = eio.listen(self.endpoint.port, self.endpoint.host);
self.server.on('connection', function(socket){
console.log('Server :: Connection from socket: ' + socket.id);
socket.on('message', function(msg){
console.log('Server :: Message event from socket: ' + socket.... | random_line_split | |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... | () {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "Password (... | main | identifier_name |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... |
};
let mut appkey_file = File::open(
Path::new(&*matches.opt_str("a").unwrap())
).expect("Could not open app key.");
let username = matches.opt_str("u").unwrap();
let cache_location = matches.opt_str("c").unwrap();
let name = mat... | {
print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts));
return;
} | conditional_block |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... |
let mut spirc_manager = SpircManager::new(&session, player, name);
spirc_manager.run();
} | });
let player = Player::new(&session); | random_line_split |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... |
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "P... | {
let brief = format!("Usage: {} [options]", program);
format!("{}", opts.usage(&brief))
} | identifier_body |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... |
}
impl<'a> AsRef<libc::iovec> for IoBufMut<'a> {
fn as_ref(&self) -> &libc::iovec {
&self.iov
}
}
impl<'a> AsMut<libc::iovec> for IoBufMut<'a> {
fn as_mut(&mut self) -> &mut libc::iovec {
&mut self.iov
}
}
// It's safe to implement Send + Sync for this type for the same reason that `... | {
// Safe because `IoBufMut` is ABI-compatible with `iovec`.
unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) }
} | identifier_body |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... |
}
#[inline]
pub fn len(&self) -> usize {
self.iov.iov_len as usize
}
#[inline]
pub fn is_empty(&self) -> bool {
self.iov.iov_len == 0
}
/// Gets a const pointer to this slice's memory.
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.iov.iov_base as ... | {
self.iov.iov_len = len;
} | conditional_block |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... | }
/// Advance the internal position of the buffer.
///
/// Panics if `count > self.len()`.
pub fn advance(&mut self, count: usize) {
assert!(count <= self.len());
self.iov.iov_len -= count;
// Safe because we've checked that `count <= self.len()` so both the starting and re... | phantom: PhantomData,
} | random_line_split |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... | <'a> {
iov: iovec,
phantom: PhantomData<&'a mut [u8]>,
}
impl<'a> IoBufMut<'a> {
pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {
// Safe because buf's memory is of the supplied length, and
// guaranteed to exist for the lifetime of the returned value.
unsafe { Self::from_raw_parts(buf.... | IoBufMut | identifier_name |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... | else {
terrain.move_src_to_dst(&self.position, new_point);
self.position.x = new_point.x; // change internal position (copy of x and y)
self.position.y = new_point.y;
}
}
/// This function encapulates a complete move for a person :
/// from looking around to actually movin... | {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_terrain(terrain);
} | conditional_block |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... |
/// This function encapulates a complete move for a person :
/// from looking around to actually moving to another place
/// (and mutating the Person and the Terrain).
pub fn look_and_move(&mut self, terrain : &mut Terrain) {
//println!("Dealing with : {}", self);
// look around
... | {
if self.has_escaped == true {
} else if terrain.get_exit_points().contains(new_point) {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_t... | identifier_body |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... |
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
} | random_line_split | |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
}
| fmt | identifier_name |
rich-textarea-field-response.js | import React from "react";
import PropTypes from "prop-types";
import styled from "@emotion/styled";
import { insertEmbeddedImages } from "../../../utils/embedded-images";
const RichTextareaFieldResponseWrapper = styled("div")(props => ({
// TODO: fluid video
lineHeight: "1.3rem",
"& img": {
maxWidth: "100%... |
RichTextareaFieldResponse.propTypes = {
attachments: PropTypes.array,
value: PropTypes.string.isRequired,
};
export default RichTextareaFieldResponse; | }; | random_line_split |
backtrace.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 https://mozilla.org/MPL/2.0/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: h... | loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
}
Err(err) => {
fmt.write_char(std::char::REPLACEMENT_CHARACTER)?;
... | fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
match path {
BytesOrWideString::Bytes(mut bytes) => { | random_line_split |
backtrace.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 https://mozilla.org/MPL/2.0/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: h... | fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))?
}
}
}
Ok(())
}
| match path {
BytesOrWideString::Bytes(mut bytes) => {
loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
}
Err(err) => {
f... | identifier_body |
backtrace.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 https://mozilla.org/MPL/2.0/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: h... | : &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
match path {
BytesOrWideString::Bytes(mut bytes) => {
loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
... | t_path(fmt | identifier_name |
calc.js | /**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var isNumeric = require('fast-isnumeric');
var calcColorscale = require('../scatter/colorscale_calc');
var arr... |
trace._needsCull = needsCull;
cd[0].carpet = carpet;
cd[0].trace = trace;
calcMarkerSize(trace, serieslen);
calcColorscale(gd, trace);
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
};
| {
a = trace.a[i];
b = trace.b[i];
if(isNumeric(a) && isNumeric(b)) {
var xy = carpet.ab2xy(+a, +b, true);
var visible = carpet.isVisible(+a, +b);
if(!visible) needsCull = true;
cd[i] = {x: xy[0], y: xy[1], a: a, b: b, vis: visible};
} else ... | conditional_block |
calc.js | /**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var isNumeric = require('fast-isnumeric');
var calcColorscale = require('../scatter/colorscale_calc');
var arr... | } else cd[i] = {x: false, y: false};
}
trace._needsCull = needsCull;
cd[0].carpet = carpet;
cd[0].trace = trace;
calcMarkerSize(trace, serieslen);
calcColorscale(gd, trace);
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
}; | var visible = carpet.isVisible(+a, +b);
if(!visible) needsCull = true;
cd[i] = {x: xy[0], y: xy[1], a: a, b: b, vis: visible}; | random_line_split |
linkedList.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v18.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LinkedList = (function () {
function LinkedList() {
... |
else {
this.first = entry;
}
this.last = entry;
};
LinkedList.prototype.remove = function () {
var result = this.first;
if (result) {
this.first = result.next;
if (!this.first) {
this.last = null;
}
... | {
this.last.next = entry;
} | conditional_block |
linkedList.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v18.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LinkedList = (function () {
function LinkedList() {
... | LinkedList.prototype.isEmpty = function () {
return !this.first;
};
return LinkedList;
}());
exports.LinkedList = LinkedList;
var LinkedListItem = (function () {
function LinkedListItem() {
}
return LinkedListItem;
}()); | this.last = null;
}
}
return result.item;
}; | random_line_split |
linkedList.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v18.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LinkedList = (function () {
function LinkedList() {
... | () {
}
return LinkedListItem;
}());
| LinkedListItem | identifier_name |
linkedList.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v18.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LinkedList = (function () {
function LinkedList() {
... |
return LinkedListItem;
}());
| {
} | identifier_body |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... |
//TODO: FIXME
// version: perfect hash. Not working currently
let lookup = find_fast(
((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize
);
HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank)
}
// don't use this.
pub fn eval_7cards(cards: [&Card; 7... | {
return s;
} | conditional_block |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... | (cards: [&Card; 5]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16;
... | eval_5cards | identifier_name |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... |
// these two guys only work by accident
/*
#[test]
fn get_rank_of_5_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c... | {
let mut tmp;
let mut best = 0;
for ids in lookups::PERM_7.iter() {
let subhand : [&Card; 5] = [
cards[ids[0] as usize],
cards[ids[1] as usize],
cards[ids[2] as usize],
cards[ids[3] as usize],
cards[ids[4] as usize]
... | identifier_body |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... | let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c6 = Card(Value::Three, Suit::Diamonds);
let c7 = Card(Value::Three, Suit::Clubs... | #[test]
fn get_rank_of_7_perfect() { | random_line_split |
test_base.py | #!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import numpy as np # noqa
import pandas as pd # noqa
import pandas_ml as pdml # noqa
import pandas_ml.util.testing as tm # noqa
import sklearn.datasets as data... |
def test_XGBClassifier(self):
iris = datasets.load_iris()
df = pdml.ModelFrame(iris)
models = ['XGBClassifier']
for model in models:
mod1 = getattr(df.xgboost, model)()
mod2 = getattr(xgb, model)()
df.fit(mod1)
mod2.fi... | df = pdml.ModelFrame([])
self.assertIs(df.xgboost.XGBRegressor, xgb.XGBRegressor)
self.assertIs(df.xgboost.XGBClassifier, xgb.XGBClassifier) | identifier_body |
test_base.py | #!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import numpy as np # noqa
import pandas as pd # noqa
import pandas_ml as pdml # noqa
import pandas_ml.util.testing as tm # noqa
import sklearn.datasets as data... | (self):
iris = datasets.load_iris()
df = pdml.ModelFrame(iris)
df.fit(df.svm.SVC())
# raises if df.estimator is not XGBModel
with self.assertRaises(ValueError):
df.xgb.plot_importance()
with self.assertRaises(ValueError):
df.xgb.to_... | test_plotting | identifier_name |
test_base.py | #!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import numpy as np # noqa
import pandas as pd # noqa
import pandas_ml as pdml # noqa
import pandas_ml.util.testing as tm # noqa
import sklearn.datasets as data... |
def test_grid_search(self):
tuned_parameters = [{'max_depth': [3, 4],
'n_estimators': [50, 100]}]
df = pdml.ModelFrame(datasets.load_digits())
cv = df.grid_search.GridSearchCV(df.xgb.XGBClassifier(), tuned_parameters, cv=5)
with tm.RNGContext... | mod1 = getattr(df.xgboost, model)()
mod2 = getattr(xgb, model)()
df.fit(mod1)
mod2.fit(X, y)
result = df.predict(mod1)
expected = mod2.predict(X)
self.assertIsInstance(result, pdml.ModelSeries)
self.assert_numpy_array_almos... | conditional_block |
test_base.py | #!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import numpy as np # noqa
import pandas as pd # noqa
import pandas_ml as pdml # noqa
import pandas_ml.util.testing as tm # noqa
import sklearn.datasets as data... | # PYTHON=3.4 PANDAS=0.17.1 SKLEARN=0.16.1
raise nose.SkipTest()
self.assertIsInstance(ax, Axes)
assert ax.get_title() == 'Feature importance'
assert ax.get_xlabel() == 'F score'
assert ax.get_ylabel() == 'Features'
assert len(ax.patches) == 4
... | random_line_split | |
backtrace.rs | 1::*;
use io::prelude::*;
use ffi::CStr;
use io;
use libc;
use str;
use sync::StaticMutex;
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is ... | &mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Co... | {
struct Context<'a> {
idx: isize,
writer: &'a mut (Write+'a),
last_error: Option<io::Error>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of prin... | identifier_body |
backtrace.rs | 1::*;
use io::prelude::*;
use ffi::CStr;
use io;
use libc;
use str;
use sync::StaticMutex;
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is ... | (w: &mut Write, idx: isize, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> io::Result<()> {
use env;
use os::unix::prelude::*;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
//////////////////////////////////////////////... | print | identifier_name |
backtrace.rs | ip_before_insn) as *mut libc::c_void
};
if !ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on o... | ////////////////////////////////////////////////////////////////////////
// translation | random_line_split | |
backtrace.rs | ::*;
use io::prelude::*;
use ffi::CStr;
use io;
use libc;
use str;
use sync::StaticMutex;
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is p... |
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often beca... | {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
} | conditional_block |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1,
n2,
confidence);
}
/// Calculate the Kolmogorov-Smirnov probability function.
fn proba... | {
// Maintain invariant that reject_probability(high) > confidence.
high = mid;
} | conditional_block |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | // Maintain invariant that reject_probability(high) > confidence.
high = mid;
} else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1... | {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if l... | identifier_body |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | (statistic: f64, n1: usize, n2: usize) -> f64 {
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
let n1 = n1 as f64;
let n2 = n2 as f64;
let factor = ((n1 * n2) / (n1 + n2)).sqrt();
let term = (factor + 0.12 + 0.11 / factor) * statistic;
let reject_probability = 1.0 - prob... | calculate_reject_probability | identifier_name |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if low + 1e-8 >= high {
return high;
}
let mid = low + (high - low) / 2... | /// ```
pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7. | random_line_split |
GenomeAFS.py | '''
Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: airanmehr@gmail.com
'''
import numpy as np;
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
import pylab as plt;
imp... | (chrom=None):
f=est.Estimate.getSAFS
a=pd.read_pickle(kutl.path+'/data/freq.df')
if chrom is not None:
suff='.chr{}'.format(chrom)
a=a.loc[[chrom]]
kplt.plotSFSold2(a, fold=False, fname='AFS' + suff);
kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f)
kplt.plotSFSold... | plotSFSall | identifier_name |
GenomeAFS.py | '''
Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: airanmehr@gmail.com
'''
import numpy as np;
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False | home = os.path.expanduser('~') + '/'
import Utils.Estimate as est
import Utils.Plots as pplt
import Scripts.KyrgysHAPH.Utils as kutl
import Scripts.KyrgysHAPH.Plot as kplt
kplt.savefig()
reload(est)
a=pd.read_pickle(kutl.path+'/data/freq.df')
def plotSFSall(chrom=None):
f=est.Estimate.getSAFS
a=pd.read_pickle(... | import pylab as plt;
import os;
| random_line_split |
GenomeAFS.py | '''
Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: airanmehr@gmail.com
'''
import numpy as np;
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
import pylab as plt;
imp... |
def plotChromAll():
a.apply(lambda x: kplt.SFSChromosomwise(x, False, False))
a.apply(lambda x: kplt.SFSChromosomwise(x, False, True))
a.apply(lambda x: kplt.SFSChromosomwise(x, True, False))
a.apply(lambda x: kplt.SFSChromosomwise(x, True, True))
def SFS():
plotSFSall()
plotSFSall('X')
p... | f=est.Estimate.getSAFS
a=pd.read_pickle(kutl.path+'/data/freq.df')
if chrom is not None:
suff='.chr{}'.format(chrom)
a=a.loc[[chrom]]
kplt.plotSFSold2(a, fold=False, fname='AFS' + suff);
kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f)
kplt.plotSFSold2(a, fold=True, fn... | identifier_body |
GenomeAFS.py | '''
Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: airanmehr@gmail.com
'''
import numpy as np;
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
import pylab as plt;
imp... |
kplt.plotSFSold2(a, fold=False, fname='AFS' + suff);
kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f)
kplt.plotSFSold2(a, fold=True, fname='AFS' + suff, );
kplt.plotSFSold2(a, fold=True, fname='Scaled-AFS' + suff, f=f)
def plotChromAll():
a.apply(lambda x: kplt.SFSChromosomwise(x, F... | suff='.chr{}'.format(chrom)
a=a.loc[[chrom]] | conditional_block |
Cert_5_1_06_RemoveRouterId.py | #!/usr/bin/env python3
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | (thread_cert.TestCase):
TOPOLOGY = {
LEADER: {
'mode': 'rsdn',
'panid': 0xface,
'whitelist': [ROUTER1]
},
ROUTER1: {
'mode': 'rsdn',
'panid': 0xface,
'router_selection_jitter': 1,
'whitelist': [LEADER]
... | Cert_5_1_06_RemoveRouterId | identifier_name |
Cert_5_1_06_RemoveRouterId.py | #!/usr/bin/env python3
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
msg = router1_messages.next_coap_message(code="0.02")
command.check_address_solicit(msg, was_router=True)
# 4 - Router1
for addr in self.nodes[ROUTER1].get_addrs():
self.assertTrue(self.nodes[LEADER].ping(addr))
if __name__ == '__main__':
unittest.main() | random_line_split | |
Cert_5_1_06_RemoveRouterId.py | #!/usr/bin/env python3
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
if __name__ == '__main__':
unittest.main()
| self.assertTrue(self.nodes[LEADER].ping(addr)) | conditional_block |
Cert_5_1_06_RemoveRouterId.py | #!/usr/bin/env python3
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | leader_messages.next_mle_message(mle.CommandType.ADVERTISEMENT)
router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST)
leader_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE)
router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST)
leader_message... | self.nodes[LEADER].start()
self.simulator.go(5)
self.assertEqual(self.nodes[LEADER].get_state(), 'leader')
self.nodes[ROUTER1].start()
self.simulator.go(5)
self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')
rloc16 = self.nodes[ROUTER1].get_addr16()
for ... | identifier_body |
types.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use ca... | (&self) -> bool {
match *self {
TexImageTarget::Texture2D => false,
_ => true,
}
}
}
| is_cubic | identifier_name |
types.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use ca... |
}
| {
match *self {
TexImageTarget::Texture2D => false,
_ => true,
}
} | identifier_body |
types.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use ca... | TexImageTarget::Texture2D => false,
_ => true,
}
}
} | pub fn is_cubic(&self) -> bool {
match *self { | random_line_split |
hdfs_command.py | pyox hdfs ls',description="ls")
lsparser.add_argument(
'-b',
action='store_true',
dest='reportbytes',
default=False,
help="Report sizes in bytes")
lsparser.add_argument(
'-l',
action='store_true',
dest='detailed',
default=False,
help="List details")
l... | lient,argv):
rmparser = argparse.ArgumentParser(prog='pyox hdfs rm',description="rm")
rmparser.add_argument(
'-r',
action='store_true',
dest='recursive',
default=False,
help="Recursively remove files/directories")
rmparser.add_argument(
'paths',
nargs='*',
help='... | fs_rm_command(c | identifier_name |
hdfs_command.py | ='pyox hdfs ls',description="ls")
lsparser.add_argument(
'-b',
action='store_true',
dest='reportbytes',
default=False,
help="Report sizes in bytes")
lsparser.add_argument(
'-l',
action='store_true',
dest='detailed',
default=False,
help="List details")
... | help='a list of paths')
args = catparser.parse_args(argv)
for path in args.paths:
input = client.open(path,offset=args.offset,length=args.length)
for chunk in input:
sys.stdout.buffer.write(chunk)
def hdfs_download_command(client,argv):
dlparser = argparse.ArgumentParser(prog='pyox ... | help="the byte length to retrieve")
catparser.add_argument(
'paths',
nargs='*', | random_line_split |
hdfs_command.py | lsargs.paths = ['/']
for path in lsargs.paths:
listing = client.list_directory(path)
max = 0;
for name in sorted(listing):
if len(name)>max:
max = len(name)
for name in sorted(listing):
if not lsargs.detailed:
print(name)
continue
... | lsparser = argparse.ArgumentParser(prog='pyox hdfs ls',description="ls")
lsparser.add_argument(
'-b',
action='store_true',
dest='reportbytes',
default=False,
help="Report sizes in bytes")
lsparser.add_argument(
'-l',
action='store_true',
dest='detailed',
defau... | identifier_body | |
hdfs_command.py | ='pyox hdfs ls',description="ls")
lsparser.add_argument(
'-b',
action='store_true',
dest='reportbytes',
default=False,
help="Report sizes in bytes")
lsparser.add_argument(
'-l',
action='store_true',
dest='detailed',
default=False,
help="List details")
... | output.flush()
if args.verbose:
sys.stderr.write('\n')
sys.stderr.flush()
remaining -= length
offset += length
else:
input = client.open(args.source)
with open(destination,'wb') as output:
for chunk in input:
... | info = client.status(args.source)
remaining = info['length']
offset = 0
chunk = 0
chunks = ceil(remaining/args.chunk_size)
if args.verbose:
sys.stderr.write('File size: {}\n'.format(remaining))
with open(destination,'wb') as output:
while remaining>0:
ch... | conditional_block |
load3_db_weather.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Cloudant のデータベース作成
#
# Copyright (C) 2016 International Business Machines Corporation
# and others. All Rights Reserved.
# ... | # Cloudant認証情報の取得
f = open('cloudant_credentials_id.json', 'r')
cred = json.load(f)
f.close()
print cred
# データベース名の取得
f = open('database_name.json', 'r')
dbn = json.load(f)
f.close()
print dbn['name']
client = Cloudant(cred['credentials']['username'],
cred['credentials']['password'],
... | from cloudant.query import Query
#import cloudant
| random_line_split |
load3_db_weather.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Cloudant のデータベース作成
#
# Copyright (C) 2016 International Business Machines Corporation
# and others. All Rights Reserved.
# ... | "e_description": e_description,
"j_description": j_description
}
print data
rx = db.create_document(data)
if rx.exists():
print "SUCCESS!!"
# Disconnect from the server
client.disconnect()
| conditional_block | |
SetCompareAndRetainAllCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. 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 required ... | (name: string, values: Data[]): ClientMessage {
const clientMessage = ClientMessage.createForEncode();
clientMessage.setRetryable(false);
const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE);
clientMessage.addFrame(initialFrame);
clientMessage.setMessageType... | encodeRequest | identifier_name |
SetCompareAndRetainAllCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. 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. | *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the Licen... | * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
SetCompareAndRetainAllCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. 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 required ... |
static decodeResponse(clientMessage: ClientMessage): boolean {
const initialFrame = clientMessage.nextFrame();
return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET);
}
}
| {
const clientMessage = ClientMessage.createForEncode();
clientMessage.setRetryable(false);
const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE);
clientMessage.addFrame(initialFrame);
clientMessage.setMessageType(REQUEST_MESSAGE_TYPE);
clientMessage.... | identifier_body |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use ... | (&self) -> Duration {
self.startup_time.elapsed()
}
}
| uptime | identifier_name |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use ... |
impl Reset {
/// Creates a new `Reset`.
pub fn new(resets_since_power_on: u32) -> Self {
Self {
startup_time: Instant::now(),
resets_since_power_on,
}
}
}
impl manticore::hardware::Reset for Reset {
fn resets_since_power_on(&self) -> u32 {
self.resets_si... | random_line_split | |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use ... |
fn uptime(&self) -> Duration {
self.startup_time.elapsed()
}
}
| {
self.resets_since_power_on
} | identifier_body |
__init__.py | import warnings
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base, synonym_for
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy_utils import (
InstrumentedList, coercion_listener, aggregates... |
Session = sessionmaker(bind=self.connection)
self.session = Session()
i18n.get_locale = get_locale
def teardown_method(self, method):
aggregates.manager.reset()
self.session.close_all()
if self.create_tables:
self.Base.metadata.drop_all(self.connection)... |
self.create_models()
sa.orm.configure_mappers()
if self.create_tables:
self.Base.metadata.create_all(self.connection) | random_line_split |
__init__.py | import warnings
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base, synonym_for
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy_utils import (
InstrumentedList, coercion_listener, aggregates... |
warnings.simplefilter('error', sa.exc.SAWarning)
sa.event.listen(sa.orm.mapper, 'mapper_configured', coercion_listener)
def get_locale():
class Locale():
territories = {'fi': 'Finland'}
return Locale()
class TestCase(object):
dns = 'sqlite:///:memory:'
create_tables = True
def set... | try:
conn.query_count += 1
except AttributeError:
conn.query_count = 0 | identifier_body |
__init__.py | import warnings
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base, synonym_for
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy_utils import (
InstrumentedList, coercion_listener, aggregates... | (clause, query):
# Test that query executes
query.all()
assert clause in str(query)
| assert_contains | identifier_name |
__init__.py | import warnings
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base, synonym_for
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy_utils import (
InstrumentedList, coercion_listener, aggregates... |
Session = sessionmaker(bind=self.connection)
self.session = Session()
i18n.get_locale = get_locale
def teardown_method(self, method):
aggregates.manager.reset()
self.session.close_all()
if self.create_tables:
self.Base.metadata.drop_all(self.connection... | self.Base.metadata.create_all(self.connection) | conditional_block |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { UserData } from "../providers/user-data";
... |
});
}
});
this.startEvents();
}
initializeApp() {
this.platform.ready().then(() => {
// The platform is ready and our plugins are available.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
//if has param (the profile page)
... | {this.rootPage = LoginPage;} | conditional_block |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { UserData } from "../providers/user-data";
... |
//set the color of the active page to be red
isActive(page: PageInterface) {
if (this.nav.getActive() && this.nav.getActive().component === page.component) {
return 'danger';
}
return;
}
//toggle logged in/out menu
enableMenu(loggedIn: boolean) {
this.menu.enable(loggedIn, 'logg... | {
//if has param (the profile page)
//set root and pass in param
if(page.hasOwnProperty('param')){
this.nav.setRoot(page.component, {
param1: page.param
});
}
else{
//set root without param
this.nav.setRoot(page.component);
}
} | identifier_body |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { UserData } from "../providers/user-data";
... | () {
this.platform.ready().then(() => {
// The platform is ready and our plugins are available.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
//if has param (the profile page)
//set root and pass in param
if(page.hasOwnProperty('param')){
... | initializeApp | identifier_name |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { UserData } from "../providers/user-data";
... | //set the has seen tutorial to true
this.userData.setHasSeenTutorial();
}else{
this.userData.hasLoggedIn().then((hasLoggedIn) => {
this.enableMenu(hasLoggedIn);
if(hasLoggedIn){this.rootPage = HomePage;}
else{this.rootPage = LoginPage;}
});
}
... | this.rootPage = TutorialPage;
//set menu to logged out menu as the user cannot be logged in yet
this.enableMenu(false); | random_line_split |
horizon.py | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
return {'components': dashboards,
'user': context['request'].user,
'current': current_dashboard,
'request': context['request']}
@register.inclusion_tag('horizon/_subnav_list.html', takes_context=True)
def horizon_dashboard_nav(context):
"""Generates sub-navigation entries ... | if callable(dash.nav) and dash.nav(context):
dashboards.append(dash)
elif dash.nav:
dashboards.append(dash) | conditional_block |
horizon.py | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | def render(self, context,):
output = self.nodelist.render(context)
output = output.replace('[[[', '{{{').replace(']]]', '}}}')
output = output.replace('[[', '{{').replace(']]', '}}')
output = output.replace('[%', '{%').replace('%]', '%}')
return output
@register.tag
def jst... | random_line_split | |
horizon.py | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | (context):
"""Generates sub-navigation entries for the current dashboard."""
if 'request' not in context:
return {}
dashboard = context['request'].horizon['dashboard']
panel_groups = dashboard.get_panel_groups()
non_empty_groups = []
for group in panel_groups.values():
allowed_p... | horizon_dashboard_nav | identifier_name |
horizon.py | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
@register.tag
def jstemplate(parser, token):
"""Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``,
``[[`` and ``]]`` with ``{{`` and ``}}`` and
``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts
with Django's template engine when using any of the Mustache-based
templating libraries.... | """Helper node for the ``jstemplate`` template tag."""
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context,):
output = self.nodelist.render(context)
output = output.replace('[[[', '{{{').replace(']]]', '}}}')
output = output.replace('[[', '{{').replac... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.