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 |
|---|---|---|---|---|
ViewFrog.py | #!/usr/bin/env python
"""
"""
import vtk
def view_frog(fileName, tissues):
colors = vtk.vtkNamedColors()
tissueMap = CreateTissueMap()
colorLut = CreateFrogLut()
# Setup render window, renderer, and interactor.
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWind... | ():
fileName, tissues = get_program_parameters()
view_frog(fileName, tissues)
def get_program_parameters():
import argparse
description = 'The complete frog without skin.'
epilogue = '''
For Figure 12-9b in the VTK Book:
Specify these tissues as parameters after the file name:
blood ... | main | identifier_name |
UserService.js | "use strict";
var fluid = require("infusion");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.oauth2");
fluid.defaults("gpii.oauth2.userService", {
gradeNames: ["fluid.eventedComponent", "autoInit"],
components: {
dataStore: {
type: "gpii.oauth2.dataStore"
... |
return false;
};
| {
return user;
} | conditional_block |
UserService.js | "use strict";
var fluid = require("infusion");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.oauth2");
fluid.defaults("gpii.oauth2.userService", {
gradeNames: ["fluid.eventedComponent", "autoInit"],
components: {
dataStore: {
type: "gpii.oauth2.dataStore"
... | // username, password
},
getUserById: {
func: "{dataStore}.findUserById"
}
}
});
gpii.oauth2.userService.authenticateUser = function (dataStore, username, password) {
var user = dataStore.findUserByUsername(username);
// TODO store password... | },
invokers: {
authenticateUser: {
funcName: "gpii.oauth2.userService.authenticateUser",
args: ["{dataStore}", "{arguments}.0", "{arguments}.1"] | random_line_split |
file.js | var model = require('./model');
var backbone = require('backbone');
var fs = require('fs');
var util = require('util');
var fpath = require('path');
var hive = require('./hive');
var EMPTY_FILE = '';
var exports = module.exports = model.extend({
initialize: function(attributes) {
var _self = this;
var path = thi... |
}
return this;
},
ext: function() {
return fpath.extname(this.get('name'));
},
absolute: function() {
return fpath.resolve(this.get('path'));
},
dir: function() {
return fpath.dirname(this.absolute());
},
sync: function(method, model) {
model.syncing = true;
var path = model.absolute();
swit... | {
fs.watchFile(path, function() {
_self.sync('read', _self);
_self.change();
});
} | conditional_block |
file.js | var model = require('./model');
var backbone = require('backbone');
var fs = require('fs');
var util = require('util');
var fpath = require('path');
var hive = require('./hive');
var EMPTY_FILE = '';
var exports = module.exports = model.extend({
initialize: function(attributes) {
var _self = this;
var path = thi... | fs.unlink(path, function(err) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: null, exists: false});
});
break;
}
},
paste: function(destination, name) {
var _self = this;
_self.syncing = true;
if(typeof destination === 'string') {
... | });
break;
case 'delete':
hive.log(method + '-ing file @ ' + path); | random_line_split |
spin.js | (tag, prop) {
var el = document.createElement(tag || 'div')
, n
for(n in prop) el[n] = prop[n]
return el
}
/**
* Appends children and returns the parent.
*/
function ins(parent /* child1, child2, ...*/) {
for (var i=1, n=arguments.length; i<n; i++)
parent.appendChi... |
// Built-in defaults
var defaults = {
lines: 12, // The number of lines to draw
length: 7, // The length of each line
width: 5, // The line thickness
radius: 10, // The radius of the inner circle
rotate: 0, // Rotation offset
... | {
var o = { x:el.offsetLeft, y:el.offsetTop }
while((el = el.offsetParent))
o.x+=el.offsetLeft, o.y+=el.offsetTop
return o
} | identifier_body |
spin.js | El(tag, prop) {
var el = document.createElement(tag || 'div')
, n
for(n in prop) el[n] = prop[n]
return el
}
/**
* Appends children and returns the parent.
*/
function ins(parent /* child1, child2, ...*/) {
for (var i=1, n=arguments.length; i<n; i++)
parent.appendC... | , el = self.el = css(createEl(0, {className: o.className}), {position: o.position, width: 0, zIndex: o.zIndex})
, mid = o.radius+o.length+o.width
, ep // element position
, tp // target position
if (target) {
target.insertBefore(el, target.firstChild||null)
... | spin: function(target) {
this.stop()
var self = this
, o = self.opts
| random_line_split |
spin.js | El(tag, prop) {
var el = document.createElement(tag || 'div')
, n
for(n in prop) el[n] = prop[n]
return el
}
/**
* Appends children and returns the parent.
*/
function | (parent /* child1, child2, ...*/) {
for (var i=1, n=arguments.length; i<n; i++)
parent.appendChild(arguments[i])
return parent
}
/**
* Insert a new stylesheet to hold the @keyframe or VML rules.
*/
var sheet = (function() {
var el = createEl('style', {type : 'text/css'})
... | ins | identifier_name |
project-settings-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { strings } from '../../../common/strings';
import * as m... |
_handleRemoveProject() {
this.props.handleRemoveProject(this.props.project);
this.hide();
}
async _handleRename(name: string) {
const { project } = this.props;
await models.project.update(project, { name });
}
show() {
this.modal?.show();
}
hide() {
this.modal?.hide();
}
... | {
this.modal = n;
} | identifier_body |
project-settings-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { strings } from '../../../common/strings';
import * as m... |
const isRemote = isRemoteProject(project);
return (
<Modal ref={this._handleSetModalRef} freshState>
<ModalHeader key={`header::${project._id}`}>
{strings.project.singular} Settings{' '}
<div className="txt-sm selectable faint monospace">{project._id}</div>
</ModalHe... | {
return null;
} | conditional_block |
project-settings-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { strings } from '../../../common/strings';
import * as m... | () {
this.modal?.show();
}
hide() {
this.modal?.hide();
}
render() {
const { project } = this.props;
if (!projectHasSettings(project)) {
return null;
}
const isRemote = isRemoteProject(project);
return (
<Modal ref={this._handleSetModalRef} freshState>
<ModalH... | show | identifier_name |
project-settings-modal.tsx | import { autoBindMethodsForReact } from 'class-autobind-decorator';
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { AUTOBIND_CFG } from '../../../common/constants';
import { strings } from '../../../common/strings';
import * as m... |
show() {
this.modal?.show();
}
hide() {
this.modal?.hide();
}
render() {
const { project } = this.props;
if (!projectHasSettings(project)) {
return null;
}
const isRemote = isRemoteProject(project);
return (
<Modal ref={this._handleSetModalRef} freshState>
... | await models.project.update(project, { name });
} | random_line_split |
Embed.CDN.js | /* Embed.CDN
Extend the basic 'embed' functionality with Google Analytics tracking and url parsing to support URLs created with the Timeline generator form.
*/
/* CodeKit Import
http://incident57.com/codekit/
================================================== */
// @codekit-append "Embed.js";
/* REPLACE THIS WIT... | };
var url_config = getUrlVars(); | document.title = headline;
the_load_time = Math.floor((new Date().getTime() - load_time_start)/100)/10;
_gaq.push(['_trackEvent', 'Timeline', headline, the_page_url, the_load_time]);
| random_line_split |
Embed.CDN.js | /* Embed.CDN
Extend the basic 'embed' functionality with Google Analytics tracking and url parsing to support URLs created with the Timeline generator form.
*/
/* CodeKit Import
http://incident57.com/codekit/
================================================== */
// @codekit-append "Embed.js";
/* REPLACE THIS WIT... |
url_vars = url_vars.split('&');
for(var i = 0; i < url_vars.length; i++) {
uv = url_vars[i].split('=');
varobj[uv[0]] = uv[1];
}
return varobj;
};
var onHeadline = function(e, headline) {
var the_page_title = "/" + headline,
the_page_url = location.href;
document.title = headline;
the_load_time =... | {
url_vars = url_vars.split('#')[0];
} | conditional_block |
request.rs | //! Types for the [`m.key.verification.request`] event.
//!
//! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{DeviceId, MilliSecondsSinceUnixEpoch, T... |
}
| {
Self { from_device, transaction_id, methods, timestamp }
} | identifier_body |
request.rs | //! Types for the [`m.key.verification.request`] event.
//!
//! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{DeviceId, MilliSecondsSinceUnixEpoch, T... | /// An opaque identifier for the verification request.
///
/// Must be unique with respect to the devices involved.
pub transaction_id: Box<TransactionId>,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// The time in milliseconds for when the ... | random_line_split | |
request.rs | //! Types for the [`m.key.verification.request`] event.
//!
//! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{DeviceId, MilliSecondsSinceUnixEpoch, T... | (
from_device: Box<DeviceId>,
transaction_id: Box<TransactionId>,
methods: Vec<VerificationMethod>,
timestamp: MilliSecondsSinceUnixEpoch,
) -> Self {
Self { from_device, transaction_id, methods, timestamp }
}
}
| new | identifier_name |
CheckCards.tsx | //Libraries
import React, {FunctionComponent} from 'react'
//Components
import CheckCard from 'src/alerting/components/CheckCard'
import FilterList from 'src/shared/components/Filter'
import {
EmptyState, | Panel,
Gradients,
Button,
IconFont,
ComponentColor,
} from '@influxdata/clockface'
// Types
import {Check} from 'src/types'
import {ComponentSize} from '@influxdata/clockface'
interface Props {
checks: Check[]
searchTerm: string
showFirstTimeWidget: boolean
onCreateCheck: () => void
}
const CheckCa... | ResourceList, | random_line_split |
CheckCards.tsx | //Libraries
import React, {FunctionComponent} from 'react'
//Components
import CheckCard from 'src/alerting/components/CheckCard'
import FilterList from 'src/shared/components/Filter'
import {
EmptyState,
ResourceList,
Panel,
Gradients,
Button,
IconFont,
ComponentColor,
} from '@influxdata/clockface'
//... |
if (showFirstTimeWidget) {
return (
<Panel
gradient={Gradients.PolarExpress}
size={ComponentSize.Large}
className="alerting-first-time"
>
<Panel.Body>
<h1>
Looks like it's your
<br />
first time here
</h1>
... | {
return (
<EmptyState size={ComponentSize.Small} className="alert-column--empty">
<EmptyState.Text
text="No checks match your search"
highlightWords={['checks']}
/>
</EmptyState>
)
} | conditional_block |
Accept.ts | import { AnswersQuestions, Interaction, Question, UsesAbilities } from '@serenity-js/core';
import { formatted } from '@serenity-js/core/lib/io';
import { AlertPromise } from 'selenium-webdriver';
/**
* @desc
* Instructs the {@link @serenity-js/core/lib/screenplay/actor~Actor} to accept
* a {@link ModalDialog}.
... | * Makes the provided {@link @serenity-js/core/lib/screenplay/actor~Actor}
* perform this {@link @serenity-js/core/lib/screenplay~Interaction}.
*
* @param {UsesAbilities & AnswersQuestions} actor
* An {@link @serenity-js/core/lib/screenplay/actor~Actor} to perform this {@link @serenity-js/cor... | /**
* @desc | random_line_split |
Accept.ts | import { AnswersQuestions, Interaction, Question, UsesAbilities } from '@serenity-js/core';
import { formatted } from '@serenity-js/core/lib/io';
import { AlertPromise } from 'selenium-webdriver';
/**
* @desc
* Instructs the {@link @serenity-js/core/lib/screenplay/actor~Actor} to accept
* a {@link ModalDialog}.
... |
/**
* @param {@serenity-js/core/lib/screenplay~Question<AlertPromise> | AlertPromise} modalDialogWindow
*/
constructor(private readonly modalDialogWindow: Question<AlertPromise> | AlertPromise) {
super();
}
/**
* @desc
* Makes the provided {@link @serenity-js/core/lib/scr... | {
return new Accept(modalDialogWindow);
} | identifier_body |
Accept.ts | import { AnswersQuestions, Interaction, Question, UsesAbilities } from '@serenity-js/core';
import { formatted } from '@serenity-js/core/lib/io';
import { AlertPromise } from 'selenium-webdriver';
/**
* @desc
* Instructs the {@link @serenity-js/core/lib/screenplay/actor~Actor} to accept
* a {@link ModalDialog}.
... | (): string {
return formatted `#actor accepts ${ this.modalDialogWindow }`;
}
}
| toString | identifier_name |
selection-list.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AfterContentInit, ElementRef, QueryList, Renderer2, EventEmitter, ChangeDetectorRef, OnDestroy } from '@angu... | implements AfterContentInit, OnDestroy, FocusableOption {
private _renderer;
private _element;
private _changeDetector;
selectionList: MdSelectionList;
private _lineSetter;
private _disableRipple;
private _selected;
/** Whether the checkbox is disabled. */
private _disabled;
pri... | MdListOption | identifier_name |
selection-list.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AfterContentInit, ElementRef, QueryList, Renderer2, EventEmitter, ChangeDetectorRef, OnDestroy } from '@angu... | * Map all the options' destroy event subscriptions and merge them into one stream.
*/
private _onDestroySubscription();
/**
* Map all the options' onFocus event subscriptions and merge them into one stream.
*/
private _onFocusSubscription();
/** Passes relevant key presses to our key... | random_line_split | |
Calendar.js | var EPOCH = 1900;
var PATTERN = /(\d+)[^\/|-]/g;
function | (year) {
if(year % 4 === 0){
if(year % 100 === 0 && year % 400 !== 0)
return false;
else
return true;
}
return false;
}
/*
* kabisats:
* Calculating how many kabisats' years in time span between
* given year and primordial year, Y0
*/
function kabisats(year) {
var kabcount = 0;
fo... | iskabisat | identifier_name |
Calendar.js | var EPOCH = 1900;
var PATTERN = /(\d+)[^\/|-]/g;
function iskabisat(year) {
if(year % 4 === 0){
if(year % 100 === 0 && year % 400 !== 0)
return false;
else
return true;
}
return false;
}
/*
* kabisats:
* Calculating how many kabisats' years in time span between
* given year and primor... |
function bali_calendar(date) {
var day = calcdays(date);
return {
Triwara: triwara(day),
Pancawara: pancawara(day),
Saptawara: saptawara(day),
Wuku: wuku(day)
};
}
module.exports.bali_calendar = bali_calendar;
| {
var wukulist = [
"Sinta", "Landep", "Ukir", "Kulantir", "Tolu",
"Gumbreg", "Wariga", "Warigadean", "Julungwangi", "Sungsang",
"Dungulan", "Kuningan", "Langkir", "Medangsya", "Pujut",
"Pahang", "Krulut", "Merakih", "Tambir", "Medangkungan",
"Matal", "Uye", "Menail", "Prangbakat", "Bala",
"Ugu... | identifier_body |
Calendar.js | var EPOCH = 1900;
var PATTERN = /(\d+)[^\/|-]/g;
function iskabisat(year) {
if(year % 4 === 0){
if(year % 100 === 0 && year % 400 !== 0)
return false;
else
return true;
}
return false;
}
/*
* kabisats:
* Calculating how many kabisats' years in time span between
* given year and primor... |
module.exports.bali_calendar = bali_calendar; | random_line_split | |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::cod... | BlobOrUSVString::USVString(s) => FormDatum::StringData(s.0),
BlobOrUSVString::Blob(b) => FormDatum::BlobData(JS::from_rooted(&b))
};
self.data.borrow_mut().insert(Atom::from(name.0), vec!(val));
}
}
impl FormData {
fn get_file_or_blob(&self, value: &Blob, filename: Opti... | random_line_split | |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::cod... | (&self, name: USVString) {
self.data.borrow_mut().remove(&Atom::from(name.0));
}
// https://xhr.spec.whatwg.org/#dom-formdata-get
fn Get(&self, name: USVString) -> Option<BlobOrUSVString> {
self.data.borrow()
.get(&Atom::from(name.0))
.map(|entry| match ent... | Delete | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::cod... |
}
}
// https://xhr.spec.whatwg.org/#dom-formdata-delete
fn Delete(&self, name: USVString) {
self.data.borrow_mut().remove(&Atom::from(name.0));
}
// https://xhr.spec.whatwg.org/#dom-formdata-get
fn Get(&self, name: USVString) -> Option<BlobOrUSVString> {
self.data.borr... | {
entry.insert(vec!(blob));
} | conditional_block |
util.rs | use crate::types::*;
use ethereum_types::H256;
use hmac::{Hmac, Mac, NewMac};
use secp256k1::PublicKey;
use sha2::Sha256;
use sha3::{Digest, Keccak256};
use std::fmt::{self, Formatter};
pub fn keccak256(data: &[u8]) -> H256 {
H256::from(Keccak256::digest(data).as_ref())
}
pub fn sha256(data: &[u8]) -> H256 {
... | let pubkey = PublicKey::from_secret_key(SECP256K1, &prikey);
assert_eq!(pubkey, id2pk(pk2id(&pubkey)).unwrap());
}
} |
#[test]
fn pk2id2pk() {
let prikey = SecretKey::new(&mut secp256k1::rand::thread_rng()); | random_line_split |
util.rs | use crate::types::*;
use ethereum_types::H256;
use hmac::{Hmac, Mac, NewMac};
use secp256k1::PublicKey;
use sha2::Sha256;
use sha3::{Digest, Keccak256};
use std::fmt::{self, Formatter};
pub fn keccak256(data: &[u8]) -> H256 {
H256::from(Keccak256::digest(data).as_ref())
}
pub fn sha256(data: &[u8]) -> H256 {
... |
pub fn hex_debug<T: AsRef<[u8]>>(s: &T, f: &mut Formatter) -> fmt::Result {
f.write_str(&hex::encode(&s))
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::{SecretKey, SECP256K1};
#[test]
fn pk2id2pk() {
let prikey = SecretKey::new(&mut secp256k1::rand::thread_rng());
let p... | {
let mut s = [0_u8; 65];
s[0] = 4;
s[1..].copy_from_slice(&id.as_bytes());
PublicKey::from_slice(&s)
} | identifier_body |
util.rs | use crate::types::*;
use ethereum_types::H256;
use hmac::{Hmac, Mac, NewMac};
use secp256k1::PublicKey;
use sha2::Sha256;
use sha3::{Digest, Keccak256};
use std::fmt::{self, Formatter};
pub fn keccak256(data: &[u8]) -> H256 {
H256::from(Keccak256::digest(data).as_ref())
}
pub fn sha256(data: &[u8]) -> H256 {
... | (pk: &PublicKey) -> PeerId {
PeerId::from_slice(&pk.serialize_uncompressed()[1..])
}
pub fn id2pk(id: PeerId) -> Result<PublicKey, secp256k1::Error> {
let mut s = [0_u8; 65];
s[0] = 4;
s[1..].copy_from_slice(&id.as_bytes());
PublicKey::from_slice(&s)
}
pub fn hex_debug<T: AsRef<[u8]>>(s: &T, f: &m... | pk2id | identifier_name |
classes_d.js | var searchData=
[
['packedaccessrecord',['PackedAccessRecord',['../structPackedAccessRecord.html',1,'']]],
['partinfo',['PartInfo',['../structPartInfo.html',1,'']]],
['partitioner',['Partitioner',['../classPartitioner.html',1,'']]],
['partitionevent',['PartitionEvent',['../classPartitioner_1_1PartitionEvent.htm... | ]; | ['proxystat',['ProxyStat',['../classProxyStat.html',1,'']]] | random_line_split |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n != s3.len() {
return false;
}
... | #[test]
fn test_is_interleave1() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbcbcac".to_owned(),
),
true
);
}
#[test]
fn test_is_interleave2() {
assert... | mod tests {
use super::*;
| random_line_split |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n != s3.len() {
return false;
}
... | fn test_is_interleave1() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbcbcac".to_owned(),
),
true
);
}
#[test]
fn test_is_interleave2() {
assert_eq!(
... | i + 1, s2, j, s3, k + 1)
{
return true;
}
if j < s2.len()
&& s3[k] == s2[j]
&& Self::is_interleave1_helper(s1, i, s2, j + 1, s3, k + 1)
{
return true;
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test... | identifier_body |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n != s3.len() {
return false;
}
... | : &[u8],
k: usize,
) -> bool {
// 都到达终点了,匹配
if k == s3.len() {
return i == s1.len() && j == s2.len();
}
if i < s1.len()
&& s3[k] == s1[i]
&& Self::is_interleave1_helper(s1, i + 1, s2, j, s3, k + 1)
{
return true;
... | : &[u8],
j: usize,
s3 | conditional_block |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n != s3.len() {
return false;
}
... | );
}
}
| identifier_name | |
init.js | /*
* Content script
*
* This script puts the injected scripts on the page and acts as a relay between the background and
* injected scripts.
*/
(function() {
"use strict";
function loadScript(url) {
var script = document.createElement('script');
script.src = chrome.extension.getURL(url);
(documen... |
});
})();
| {
window.postMessage(request, '*');
} | conditional_block |
init.js | /*
* Content script
*
* This script puts the injected scripts on the page and acts as a relay between the background and
* injected scripts.
*/
(function() {
"use strict";
function | (url) {
var script = document.createElement('script');
script.src = chrome.extension.getURL(url);
(document.head || document.documentElement).appendChild(script);
}
// Load injected scripts onto the page
$(document).on('ready', function() {
loadScript('scripts/injected/relay.js');
});
// Lis... | loadScript | identifier_name |
init.js | /*
* Content script
*
* This script puts the injected scripts on the page and acts as a relay between the background and
* injected scripts.
*/
(function() {
"use strict";
function loadScript(url) {
var script = document.createElement('script');
script.src = chrome.extension.getURL(url);
(documen... | chrome.runtime.sendMessage(data);
}
});
// Listen for messages from the background scripts
// Messages heading out from here have two options, "say" or "kick"
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request.id == 'extension' && request.target == 'injected... | window.addEventListener('message', function(e) {
var data = e.data;
if(typeof(data) == 'object' && data.id == 'injected') { | random_line_split |
init.js | /*
* Content script
*
* This script puts the injected scripts on the page and acts as a relay between the background and
* injected scripts.
*/
(function() {
"use strict";
function loadScript(url) |
// Load injected scripts onto the page
$(document).on('ready', function() {
loadScript('scripts/injected/relay.js');
});
// Listen for messages from the injected scripts
window.addEventListener('message', function(e) {
var data = e.data;
if(typeof(data) == 'object' && data.id == 'injected') {
... | {
var script = document.createElement('script');
script.src = chrome.extension.getURL(url);
(document.head || document.documentElement).appendChild(script);
} | identifier_body |
module.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 {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {A11yModule} from '@angu... | exports: [MatTooltip, TooltipComponent, MatCommonModule, CdkScrollableModule],
declarations: [MatTooltip, TooltipComponent],
providers: [MAT_TOOLTIP_SCROLL_STRATEGY_FACTORY_PROVIDER],
})
export class MatTooltipModule {} | @NgModule({
imports: [A11yModule, CommonModule, OverlayModule, MatCommonModule], | random_line_split |
module.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 {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {A11yModule} from '@angu... | {}
| MatTooltipModule | identifier_name |
trait-inheritance-auto-xc-2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let a = &A { x: 3 };
f(a);
}
| main | identifier_name |
trait-inheritance-auto-xc-2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
} | identifier_body |
trait-inheritance-auto-xc-2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // aux-build:trait_inheritance_auto_xc_2_aux.rs
extern crate "trait_inheritance_auto_xc_2_aux" as aux;
// aux defines impls of Foo, Bar and Baz for A
use aux::{Foo, Bar, Baz, A};
// We want to extend all Foo, Bar, Bazes to Quuxes
pub trait Quux: Foo + Bar + Baz { }
impl<T:Foo + Bar + Baz> Quux for T { }
fn f<T:Quux... | random_line_split | |
mod.rs | pub mod v03;
pub mod v10;
use chrono::{DateTime, TimeZone, Utc};
use serde_json::{json, Value};
pub fn id() -> String {
"0001".to_string()
}
pub fn ty() -> String {
"test_event.test_application".to_string()
}
pub fn source() -> String {
"http://localhost/".to_string()
}
pub fn json_datacontenttype() ->... | }
pub fn time() -> DateTime<Utc> {
Utc.ymd(2020, 3, 16).and_hms(11, 50, 00)
}
pub fn string_extension() -> (String, String) {
("string_ex".to_string(), "val".to_string())
}
pub fn bool_extension() -> (String, bool) {
("bool_ex".to_string(), true)
}
pub fn int_extension() -> (String, i64) {
("int_ex"... | pub fn subject() -> String {
"cloudevents-sdk".to_string() | random_line_split |
mod.rs | pub mod v03;
pub mod v10;
use chrono::{DateTime, TimeZone, Utc};
use serde_json::{json, Value};
pub fn id() -> String {
"0001".to_string()
}
pub fn ty() -> String {
"test_event.test_application".to_string()
}
pub fn source() -> String {
"http://localhost/".to_string()
}
pub fn json_datacontenttype() ->... | () -> String {
"http://localhost/schema".to_string()
}
pub fn json_data() -> Value {
json!({"hello": "world"})
}
pub fn json_data_binary() -> Vec<u8> {
serde_json::to_vec(&json!({"hello": "world"})).unwrap()
}
pub fn xml_data() -> String {
"<hello>world</hello>".to_string()
}
pub fn subject() -> Str... | dataschema | identifier_name |
mod.rs | pub mod v03;
pub mod v10;
use chrono::{DateTime, TimeZone, Utc};
use serde_json::{json, Value};
pub fn id() -> String |
pub fn ty() -> String {
"test_event.test_application".to_string()
}
pub fn source() -> String {
"http://localhost/".to_string()
}
pub fn json_datacontenttype() -> String {
"application/json".to_string()
}
pub fn xml_datacontenttype() -> String {
"application/xml".to_string()
}
pub fn dataschema() ... | {
"0001".to_string()
} | identifier_body |
bookings.py | #!/usr/bin/env python
"""list all previously made bookings"""
import os
import sys
import cgi
import datetime
import json
import shuttle
import shconstants
import smtplib
import shcookie
print "Content-type: text/html\r\n"
shuttle.do_login(shcookie.u, shcookie.p)
form = cgi.FieldStorage()
if 'action' in form:
a... |
if 'cl' in b:
print ''' <form method="post" action="%s" onsubmit="return confirm('Cancel?');">
<input type="hidden" name="action" value="cancel"/>
<input type="hidden" name="id" value="%s"/>
<input type="submit" value="cancel"/>
</form>''' % (os.environ["SCRIPT_NAME"], b['cl'])
print '<... | stop = shuttle.get_stop_gps(b['r'], b['dl'])
if stop != None:
dst = shuttle.get_maps_eta((loc['lat'], loc['lon']), (stop[0], stop[1]))
print ' <span class="et">ETA: %s (<a href="https://www.google.com/maps?q=%f,%f">%s</a>)</span>' % (
dst[1], loc['lat'], loc['lon'], dst[0]) | conditional_block |
bookings.py | #!/usr/bin/env python
"""list all previously made bookings"""
import os
import sys
import cgi
import datetime
import json
import shuttle
import shconstants
import smtplib
import shcookie
print "Content-type: text/html\r\n"
shuttle.do_login(shcookie.u, shcookie.p)
form = cgi.FieldStorage()
if 'action' in form:
a... | <input type="hidden" name="action" value="cancel"/>
<input type="hidden" name="id" value="%s"/>
<input type="submit" value="cancel"/>
</form>''' % (os.environ["SCRIPT_NAME"], b['cl'])
print '</div>'
print '</div></body><!--'
# print datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
print '--></html... | random_line_split | |
datatable.js | var dataTable; // datatable object
var table; // actual table jquery object
var tableContainer; // actual table container object
var tableWrapper; // actual table wrapper jquery object
var tableInitialized = false;
var ajaxParams = {}; // set filter mode
var countSelectedRecor... |
if (res.sStatus) {
if (tableOptions.resetGroupActionInputOnSuccess) {
$('.table-group-action-input', tableWrapper).val("");
}
}
... | {
Metronic.alert({type: (res.sStatus == 'OK' ? 'success' : 'danger'), icon: (res.sStatus == 'OK' ? 'check' : 'warning'), message: res.sMessage, container: tableWrapper, place: 'prepend'});
} | conditional_block |
datatable.js | var dataTable; // datatable object
var table; // actual table jquery object
var tableContainer; // actual table container object
var tableWrapper; // actual table wrapper jquery object
var tableInitialized = false;
var ajaxParams = {}; // set filter mode
var countSelectedRecor... | "bServerSide": true, // enable/disable server side ajax loading
"sAjaxSource": "", // define ajax source URL
"sServerMethod": "POST",
// handle ajax request
"fnServerData": function ( sSource, aoData, fnCallback, ... |
"bAutoWidth": false, // disable fixed width and enable fluid table
"bSortCellsTop": true, // make sortable only the first row in thead
"sPaginationType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended)
... | random_line_split |
randNNIWalks.py | #randNNIWalks.py
#writes random SPR walks to files
#calls GTP on each NNI random walk file to get
#the ditances between each tree and the first tree of the sequence
#the results are written to csv files with lines delimited by \t
import tree_utils as tu
import w_tree_utils as wtu
import os
import sys
import numpy as np... |
#create a file for each spr sequence
for k in range(runs):
rand_tree = genRandBinTree(list(range(size)))
total_nodes = size-1
#write current sequence to file
infile_prefix = "tmpnniseq" + str(__pid__)
infile = infile_prefix + str(k)
with open(inf... | global __pid__
global __prefix__
#set the seed
random.seed(seed)
np.random.seed(seed)
#select tree utils module
if weighted:
tum = wtu
genRandBinTree = lambda leaves: wtu.genRandBinTree(leaves,np.random.exponential)
else:
tum = tu
genRandBinTree = la... | identifier_body |
randNNIWalks.py | #randNNIWalks.py
#writes random SPR walks to files
#calls GTP on each NNI random walk file to get
#the ditances between each tree and the first tree of the sequence
#the results are written to csv files with lines delimited by \t
import tree_utils as tu
import w_tree_utils as wtu
import os
import sys
import numpy as np... |
#set the seed
random.seed(seed)
np.random.seed(seed)
#select tree utils module
if weighted:
tum = wtu
genRandBinTree = lambda leaves: wtu.genRandBinTree(leaves,np.random.exponential)
else:
tum = tu
genRandBinTree = lambda leaves: tu.genRandBinTree(leaves... | random_line_split | |
randNNIWalks.py | #randNNIWalks.py
#writes random SPR walks to files
#calls GTP on each NNI random walk file to get
#the ditances between each tree and the first tree of the sequence
#the results are written to csv files with lines delimited by \t
import tree_utils as tu
import w_tree_utils as wtu
import os
import sys
import numpy as np... | (daf,size,steps,runs,seed,weighted = False):
global __pid__
global __prefix__
#set the seed
random.seed(seed)
np.random.seed(seed)
#select tree utils module
if weighted:
tum = wtu
genRandBinTree = lambda leaves: wtu.genRandBinTree(leaves,np.random.exponential)
e... | randNNIwalk | identifier_name |
randNNIWalks.py | #randNNIWalks.py
#writes random SPR walks to files
#calls GTP on each NNI random walk file to get
#the ditances between each tree and the first tree of the sequence
#the results are written to csv files with lines delimited by \t
import tree_utils as tu
import w_tree_utils as wtu
import os
import sys
import numpy as np... |
if WEIGHTED:
__prefix__ = 'W' + __prefix__
else:
__prefix__ = 'U' + __prefix__
#take a single size or a range of sizes
if ":" in sys.argv[2]:
size_start, size_end = map(lambda x: int(x),sys.argv[2].split(':'))
else:
size_start = int(sys.argv[2])
... | __prefix__ = "RNI_" | conditional_block |
GroupDetails.js | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Navigator,
ScrollView,
ListView,
} from 'react-native'
import NavigationBar from 'react-native-navbar';
var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?';
class GroupDetails extends Component {
con... |
toQueryString(obj) {
return obj ? Object.keys(obj).sort().map(function (key) {
var val = obj[key];
if (Array.isArray(val)) {
return val.sort().map(function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
}).join('&'... | {
this.fetchData();
} | identifier_body |
GroupDetails.js | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Navigator,
ScrollView,
ListView,
} from 'react-native'
import NavigationBar from 'react-native-navbar';
var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?';
class GroupDetails extends Component {
con... | },
listView: {
backgroundColor: '#0000ff',
paddingBottom: 200,
},
});
module.exports = GroupDetails; | },
thumbnail: {
width: 53,
height: 81, | random_line_split |
GroupDetails.js | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Navigator,
ScrollView,
ListView,
} from 'react-native'
import NavigationBar from 'react-native-navbar';
var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?';
class GroupDetails extends Component {
con... | () {
this.props.navigator.pop();
}
renderRide (ride) {
return (
<View>
<Text style={styles.title}>{ride.title}</Text>
</View>
);
}
componentDidMount () {
this.fetchData();
}
toQueryString(obj) {
return obj ? Object.keys(... | backOnePage | identifier_name |
GroupDetails.js | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Navigator,
ScrollView,
ListView,
} from 'react-native'
import NavigationBar from 'react-native-navbar';
var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?';
class GroupDetails extends Component {
con... |
return encodeURIComponent(key) + '=' + encodeURIComponent(val);
}).join('&') : '';
}
fetchData() {
console.log(this.props.group_info.pk);
fetch(REQUEST_URL + this.toQueryString({"group": this.props.group_info.pk}))
.then((response) => response.json())
.then((response... | {
return val.sort().map(function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
}).join('&');
} | conditional_block |
account_validate_account_move.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
move_ids = list(set(move_ids))
if not move_ids:
raise osv.except_osv(_('Warning!'), _('Selected Entry Lines does not have any account move entries in draft state.'))
obj_move.button_validate(cr, uid, move_ids, context)
return {'type': 'ir.actions.act_window_close'}
# vim:ex... | if line.move_id.state=='draft':
move_ids.append(line.move_id.id) | conditional_block |
account_validate_account_move.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
class validate_account_move_lines(osv.osv_memory):
_name = "validate.account.move.lines"
_description = "Validate Account Move Lines"
def validate_move_lines(self, cr, uid, ids, context=None):
obj_move_line = self.pool.get('account.move.line')
obj_move = self.pool.get('account.move')
... | obj_move = self.pool.get('account.move')
if context is None:
context = {}
data = self.read(cr, uid, ids[0], context=context)
ids_move = obj_move.search(cr, uid, [('state','=','draft'),('journal_id','in',tuple(data['journal_ids'])),('period_id','in',tuple(data['period_ids']))], order=... | identifier_body |
account_validate_account_move.py | # -*- coding: utf-8 -*-
############################################################################## | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that i... | #
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
# | random_line_split |
account_validate_account_move.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | (osv.osv_memory):
_name = "validate.account.move.lines"
_description = "Validate Account Move Lines"
def validate_move_lines(self, cr, uid, ids, context=None):
obj_move_line = self.pool.get('account.move.line')
obj_move = self.pool.get('account.move')
move_ids = []
if contex... | validate_account_move_lines | identifier_name |
tests.py | from __future__ import absolute_import
from django.test import TestCase
from django.core.exceptions import FieldError
from .models import Poll, Choice, OuterA, Inner, OuterB
class NullQueriesTests(TestCase):
def | (self):
"""
Regression test for the use of None as a query value.
None is interpreted as an SQL NULL, but only in __exact queries.
Set up some initial polls and choices
"""
p1 = Poll(question='Why?')
p1.save()
c1 = Choice(poll=p1, choice='Because.')
... | test_none_as_null | identifier_name |
tests.py | from __future__ import absolute_import
from django.test import TestCase
from django.core.exceptions import FieldError
from .models import Poll, Choice, OuterA, Inner, OuterB
class NullQueriesTests(TestCase):
| Choice.objects.exclude(choice=None).order_by('id'),
[
'<Choice: Choice: Because. in poll Q: Why? >',
'<Choice: Choice: Why Not? in poll Q: Why? >'
]
)
# Valid query, but fails because foo isn't a keyword
sel... | def test_none_as_null(self):
"""
Regression test for the use of None as a query value.
None is interpreted as an SQL NULL, but only in __exact queries.
Set up some initial polls and choices
"""
p1 = Poll(question='Why?')
p1.save()
c1 = Choice(poll=p1, cho... | identifier_body |
tests.py | from __future__ import absolute_import |
from django.test import TestCase
from django.core.exceptions import FieldError
from .models import Poll, Choice, OuterA, Inner, OuterB
class NullQueriesTests(TestCase):
def test_none_as_null(self):
"""
Regression test for the use of None as a query value.
None is interpreted as an SQL ... | random_line_split | |
clean.js | var fs = require('graceful-fs');
var path = require('path');
var mout = require('mout');
var Q = require('q');
var rimraf = require('rimraf');
var Logger = require('bower-logger');
var endpointParser = require('bower-endpoint-parser');
var PackageRepository = require('../../core/PackageRepository');
var semver = requir... | (endpoints, options, config) {
var logger = new Logger();
var decEndpoints;
var names;
options = options || {};
config = mout.object.deepFillIn(config || {}, defaultConfig);
// If endpoints is an empty array, null them
if (endpoints && !endpoints.length) {
endpoints = null;
}
... | clean | identifier_name |
clean.js | var fs = require('graceful-fs');
var path = require('path');
var mout = require('mout');
var Q = require('q');
var rimraf = require('rimraf');
var Logger = require('bower-logger');
var endpointParser = require('bower-endpoint-parser');
var PackageRepository = require('../../core/PackageRepository');
var semver = requir... |
Q.all([
clearPackages(decEndpoints, config, logger),
clearLinks(names, config, logger),
!names ? clearCompletion(config, logger) : null
])
.spread(function (entries) {
return entries;
})
.done(function (entries) {
logger.emit('end', entries);
}, function... | {
decEndpoints = endpoints.map(function (endpoint) {
return endpointParser.decompose(endpoint);
});
names = decEndpoints.map(function (decEndpoint) {
return decEndpoint.name || decEndpoint.source;
});
} | conditional_block |
clean.js | var fs = require('graceful-fs');
var path = require('path');
var mout = require('mout');
var Q = require('q');
var rimraf = require('rimraf');
var Logger = require('bower-logger');
var endpointParser = require('bower-endpoint-parser');
var PackageRepository = require('../../core/PackageRepository');
var semver = requir... |
// If target is a wildcard, simply return true
if (decEndpoint.target === '*') {
return true;
}
// If it's a semver target, compare using semver spec
if (semver.validRange(decEndpoint.target)) {... | {
var repository = new PackageRepository(config, logger);
return repository.list()
.then(function (entries) {
var promises;
// Filter entries according to the specified packages
if (decEndpoints) {
entries = entries.filter(function (entry) {
return !!mo... | identifier_body |
clean.js | var fs = require('graceful-fs');
var path = require('path');
var mout = require('mout');
var Q = require('q');
var rimraf = require('rimraf');
var Logger = require('bower-logger');
var endpointParser = require('bower-endpoint-parser');
var PackageRepository = require('../../core/PackageRepository');
var semver = requir... |
promises = entries.map(function (entry) {
return repository.eliminate(entry.pkgMeta)
.then(function () {
logger.info('deleted', 'Cached package ' + entry.pkgMeta.name + ': ' + entry.canonicalDir, {
file: entry.canonicalDir
});
... | decEndpoint.target === entryPkgMeta._release;
});
});
} | random_line_split |
WaterPrimaryMaterialDemo.ts | import { Camera } from "laya/d3/core/Camera";
import { Scene3D } from "laya/d3/core/scene/Scene3D";
import { Stage } from "laya/display/Stage";
import { Handler } from "laya/utils/Handler";
import { Stat } from "laya/utils/Stat";
import { Laya3D } from "Laya3D";
import { CameraMoveScript } from "../common/CameraMoveScr... | import { Laya } from "Laya"; | random_line_split | |
WaterPrimaryMaterialDemo.ts | import { Laya } from "Laya";
import { Camera } from "laya/d3/core/Camera";
import { Scene3D } from "laya/d3/core/scene/Scene3D";
import { Stage } from "laya/display/Stage";
import { Handler } from "laya/utils/Handler";
import { Stat } from "laya/utils/Stat";
import { Laya3D } from "Laya3D";
import { CameraMoveScript } ... | {
constructor() {
Laya3D.init(0, 0);
Stat.show();
Laya.stage.scaleMode = Stage.SCALE_FULL;
Laya.stage.screenMode = Stage.SCREEN_NONE;
Scene3D.load("res/threeDimen/scene/LayaScene_water/Conventional/Default.ls", Handler.create(this, function (scene: Scene3D): void {
(<Scene3D>Laya.stage.addChild(scene));
... | WaterPrimaryMaterialDemo | identifier_name |
test_timer.py | from __future__ import absolute_import, unicode_literals
import pytest
from datetime import datetime
from case import Mock, patch
from kombu.asynchronous.timer import Entry, Timer, to_timestamp
from kombu.five import bytes_if_py2
class test_to_timestamp:
def test_timestamp(self):
assert to_timestamp(... |
def test_enter_exit(self):
x = Timer()
x.stop = Mock(name='timer.stop')
with x:
pass
x.stop.assert_called_with()
def test_supports_Timer_interface(self):
x = Timer()
x.stop()
tref = Mock()
x.cancel(tref)
tref.cancel.assert_ca... | assert x == x
assert x != y
class test_Timer: | random_line_split |
test_timer.py | from __future__ import absolute_import, unicode_literals
import pytest
from datetime import datetime
from case import Mock, patch
from kombu.asynchronous.timer import Entry, Timer, to_timestamp
from kombu.five import bytes_if_py2
class test_to_timestamp:
def test_timestamp(self):
assert to_timestamp(... |
def test_ordering(self):
# we don't care about results, just that it's possible
Entry(lambda x: 1) < Entry(lambda x: 2)
Entry(lambda x: 1) > Entry(lambda x: 2)
Entry(lambda x: 1) >= Entry(lambda x: 2)
Entry(lambda x: 1) <= Entry(lambda x: 2)
def test_eq(self):
x... | def test_call(self):
fun = Mock(name='fun')
tref = Entry(fun, (4, 4), {'moo': 'baz'})
tref()
fun.assert_called_with(4, 4, moo='baz')
def test_cancel(self):
tref = Entry(lambda x: x, (1,), {})
assert not tref.canceled
assert not tref.cancelled
tref.can... | identifier_body |
test_timer.py | from __future__ import absolute_import, unicode_literals
import pytest
from datetime import datetime
from case import Mock, patch
from kombu.asynchronous.timer import Entry, Timer, to_timestamp
from kombu.five import bytes_if_py2
class test_to_timestamp:
def test_timestamp(self):
assert to_timestamp(... | (self):
t = Timer()
try:
t.schedule.enter_after = Mock()
myfun = Mock()
myfun.__name__ = bytes_if_py2('myfun')
t.call_repeatedly(0.03, myfun)
assert t.schedule.enter_after.call_count == 1
args1, _ = t.schedule.enter_after.call_arg... | test_call_repeatedly | identifier_name |
bignum.rs | use openssl::bn::BigNum;
use std::ops::Deref;
use super::Part;
use result::JwtResult;
use rustc_serialize::base64::*;
pub struct BigNumComponent(pub BigNum);
impl Deref for BigNumComponent {
type Target = BigNum; | }
impl Into<BigNum> for BigNumComponent {
fn into(self) -> BigNum {
self.0
}
}
impl Part for BigNumComponent {
type Encoded = String;
fn to_base64(&self) -> JwtResult<String> {
Ok(ToBase64::to_base64(&self.to_vec()[..], URL_SAFE))
}
fn from_base64<B: AsRef<[u8]>>(... |
fn deref(&self) -> &Self::Target {
&self.0
} | random_line_split |
bignum.rs | use openssl::bn::BigNum;
use std::ops::Deref;
use super::Part;
use result::JwtResult;
use rustc_serialize::base64::*;
pub struct BigNumComponent(pub BigNum);
impl Deref for BigNumComponent {
type Target = BigNum;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Into<BigNum> for BigNumComp... |
}
#[cfg(test)]
mod test {
use super::*;
use Part;
#[test]
fn test_bignum_base64() {
let bn_b64 = "AQAB";
let bn = BigNumComponent::from_base64(bn_b64.as_bytes()).unwrap();
let result = bn.to_base64().unwrap();
assert_eq!(result, bn_b64);
}
} | {
let decoded = try!(encoded.as_ref().from_base64());
let bn = try!(BigNum::from_slice(&decoded));
Ok(BigNumComponent(bn))
} | identifier_body |
bignum.rs | use openssl::bn::BigNum;
use std::ops::Deref;
use super::Part;
use result::JwtResult;
use rustc_serialize::base64::*;
pub struct BigNumComponent(pub BigNum);
impl Deref for BigNumComponent {
type Target = BigNum;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Into<BigNum> for BigNumComp... | <B: AsRef<[u8]>>(encoded: B) -> JwtResult<BigNumComponent> {
let decoded = try!(encoded.as_ref().from_base64());
let bn = try!(BigNum::from_slice(&decoded));
Ok(BigNumComponent(bn))
}
}
#[cfg(test)]
mod test {
use super::*;
use Part;
#[test]
fn test_bignum_base64() {
... | from_base64 | identifier_name |
to_rawdata.py | #!/usr/bin/env python
# -*- coding: ascii -*-
"""
package.module
~~~~~~~~~~~~~
A description which can be long and explain the complete
functionality of this module even with indented code examples.
Class/Function however should not be documented here.
:copyright: year by my name, see AUTHORS for more details
:licen... | (filename):
""" """
try:
f_in = open(filename, 'r')
f_out = open(outputfilename, 'wb')
sample = 0
for line in f_in:
try:
sample = int(line)
data = struct.pack("i", sample) # pack integer in a binary string
f_out.write(data)
exce... | do_convert | identifier_name |
to_rawdata.py | #!/usr/bin/env python
# -*- coding: ascii -*-
"""
package.module
~~~~~~~~~~~~~
A description which can be long and explain the complete
functionality of this module even with indented code examples.
Class/Function however should not be documented here.
:copyright: year by my name, see AUTHORS for more details
:licen... | print "Converting..."
do_convert(sys.argv[1])
print "done. Written to " + outputfilename | conditional_block | |
to_rawdata.py | #!/usr/bin/env python
# -*- coding: ascii -*-
"""
package.module
~~~~~~~~~~~~~
A description which can be long and explain the complete
functionality of this module even with indented code examples.
Class/Function however should not be documented here.
:copyright: year by my name, see AUTHORS for more details
:licen... |
if __name__=='__main__':
print "Converting..."
do_convert(sys.argv[1])
print "done. Written to " + outputfilename
| """ """
try:
f_in = open(filename, 'r')
f_out = open(outputfilename, 'wb')
sample = 0
for line in f_in:
try:
sample = int(line)
data = struct.pack("i", sample) # pack integer in a binary string
f_out.write(data)
except:
print "Can... | identifier_body |
to_rawdata.py | #!/usr/bin/env python
# -*- coding: ascii -*-
"""
package.module
~~~~~~~~~~~~~
A description which can be long and explain the complete
functionality of this module even with indented code examples.
Class/Function however should not be documented here.
:copyright: year by my name, see AUTHORS for more details
:licen... | data = struct.pack("i", sample) # pack integer in a binary string
f_out.write(data)
except:
print "Cannot convert: " + line
finally:
f_in.close()
f_out.close()
if __name__=='__main__':
print "Converting..."
do_convert(sys.argv[1])
print "done... |
for line in f_in:
try:
sample = int(line) | random_line_split |
gen.js | /* eslint-env mocha */
'use strict'
const hat = require('hat')
const { getDescribe, getIt, expect } = require('../utils/mocha')
| module.exports = (common, options) => {
const describe = getDescribe(options)
const it = getIt(options)
describe('.key.gen', () => {
const keyTypes = [
{ type: 'rsa', size: 2048 }
]
let ipfs
before(async () => {
ipfs = (await common.spawn()).api
})
after(() => common.clean(... | /** @typedef { import("ipfsd-ctl/src/factory") } Factory */
/**
* @param {Factory} common
* @param {Object} options
*/ | random_line_split |
sails-client.service.ts | import { IO_INSTANCE, SocketIOConnectOpts, SocketIOSocket, io } from '../io';
import { ISailsRequest, ISailsRequestOpts, ISailsResponse } from './interfaces';
import { Inject, Injectable } from '@angular/core';
import { ISailsClientConfig } from './sails-client.config';
import { Observable } from 'rxjs/Observable';
im... |
ioInstance ? (this.io = ioInstance) : (this.io = io(uri, options));
this.uri = uri;
this.configOptions = options;
this.errorsSubject = new Subject();
this.requestErrors = this.errorsSubject.asObservable();
}
get(url: string, options?: ISailsRequestOpts): Observable<ISailsResponse> {
return... | {
this.defaultHeaders = config.headers;
} | conditional_block |
sails-client.service.ts | import { IO_INSTANCE, SocketIOConnectOpts, SocketIOSocket, io } from '../io';
import { ISailsRequest, ISailsRequestOpts, ISailsResponse } from './interfaces';
import { Inject, Injectable } from '@angular/core';
import { ISailsClientConfig } from './sails-client.config';
import { Observable } from 'rxjs/Observable';
im... | (event: string): Observable<any> {
let nextFunc: (msg: any) => void;
return Observable.create((obs: Observer<any>) => {
nextFunc = (msg: any) => obs.next(msg);
this.io.on(event, nextFunc);
return () => this.io.off(event, nextFunc);
});
}
get configuration() {
return <ISailsClient... | on | identifier_name |
sails-client.service.ts | import { IO_INSTANCE, SocketIOConnectOpts, SocketIOSocket, io } from '../io';
import { ISailsRequest, ISailsRequestOpts, ISailsResponse } from './interfaces';
import { Inject, Injectable } from '@angular/core';
import { ISailsClientConfig } from './sails-client.config';
import { Observable } from 'rxjs/Observable';
im... |
public io: SocketIOSocket;
public requestErrors: Observable<SailsError>;
constructor(config: ISailsClientConfig = {}, @Inject(IO_INSTANCE) ioInstance?: SocketIOSocket) {
const { uri, options } = this.getConfig(config);
if (config.headers) {
this.defaultHeaders = config.headers;
}
ioInstanc... | random_line_split | |
sails-client.service.ts | import { IO_INSTANCE, SocketIOConnectOpts, SocketIOSocket, io } from '../io';
import { ISailsRequest, ISailsRequestOpts, ISailsResponse } from './interfaces';
import { Inject, Injectable } from '@angular/core';
import { ISailsClientConfig } from './sails-client.config';
import { Observable } from 'rxjs/Observable';
im... |
get(url: string, options?: ISailsRequestOpts): Observable<ISailsResponse> {
return this.sendRequest(url, RequestMethod.GET, undefined, options);
}
post(url: string, body?: any, options?: ISailsRequestOpts): Observable<ISailsResponse> {
return this.sendRequest(url, RequestMethod.POST, body, options);
... | {
const { uri, options } = this.getConfig(config);
if (config.headers) {
this.defaultHeaders = config.headers;
}
ioInstance ? (this.io = ioInstance) : (this.io = io(uri, options));
this.uri = uri;
this.configOptions = options;
this.errorsSubject = new Subject();
this.requestErrors ... | identifier_body |
test_defaults.py | from unittest import TestCase
import validictory
class TestItems(TestCase):
def test_property(self):
schema = {
"type": "object",
"properties": {
"foo": {
"default": "bar"
},
"baz": {
"type": "... | 'default': 'baz'
},
]
}
data = ['foo', 'bar']
result = validictory.validate(data, schema, required_by_default=False)
self.assertEqual(result, ["foo", "bar", "baz"]) | random_line_split | |
test_defaults.py | from unittest import TestCase
import validictory
class | (TestCase):
def test_property(self):
schema = {
"type": "object",
"properties": {
"foo": {
"default": "bar"
},
"baz": {
"type": "integer"
}
}
}
data = ... | TestItems | identifier_name |
test_defaults.py | from unittest import TestCase
import validictory
class TestItems(TestCase):
def test_property(self):
schema = {
"type": "object",
"properties": {
"foo": {
"default": "bar"
},
"baz": {
"type": "... | schema = {
'type': 'object',
'type': 'array',
'items': [
{
'type': 'any'
},
{
'type': 'string'
},
{
'default': 'baz'
},
... | identifier_body | |
codemap.js | the V8 project 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and th... |
/**
* Map of memory pages occupied with static code.
*/
this.pages_ = [];
}
;
/**
* The number of alignment bits in a page address.
*/
CodeMap.PAGE_ALIGNMENT = 12;
/**
* Page size in bytes.
*/
CodeMap.PAGE_SIZE =
1 << CodeMap.PAGE_ALIGNMENT;
/**
* Adds a dynamic (i.e. moveable and discardable)... | {
/**
* Dynamic code entries. Used for JIT compiled code.
*/
this.dynamics_ = new SplayTree();
/**
* Name generator for entries having duplicate names.
*/
this.dynamicsNameGen_ = new CodeMap.NameGenerator();
/**
* Static code entries. Used for statically compiled code.
*/
this.statics_ =... | identifier_body |
codemap.js | the V8 project 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and th... |
return { entry : entry, offset : addr - dynaEntry.key };
}
return null;
};
/**
* Finds a code entry that contains the specified address. Both static and
* dynamic code entries are considered.
*
* @param {number} addr Address.
*/
CodeMap.prototype.findEntry = function(addr) {
var result = this.findAddr... | {
entry.name = this.dynamicsNameGen_.getName(entry.name);
entry.nameUpdated_ = true;
} | conditional_block |
codemap.js | the V8 project 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and th... | () {
/**
* Dynamic code entries. Used for JIT compiled code.
*/
this.dynamics_ = new SplayTree();
/**
* Name generator for entries having duplicate names.
*/
this.dynamicsNameGen_ = new CodeMap.NameGenerator();
/**
* Static code entries. Used for statically compiled code.
*/
this.statics... | CodeMap | identifier_name |
codemap.js | 9 the V8 project 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and t... | function(addr) {
var node = this.dynamics_.find(addr);
return node ? node.value : null;
};
/**
* Returns an array of all dynamic code entries.
*/
CodeMap.prototype.getAllDynamicEntries = function() {
return this.dynamics_.exportValues();
};
/**
* Returns an array of pairs of all dynamic code entries an... | CodeMap.prototype.findDynamicEntryByStartAddress = | random_line_split |
base.js | var doNothing = function () {}
/**
* The `Base` log defines methods that transports will share.
*/
var Base = module.exports = function (config, defaults) {
var cedar = require('../../cedar')
// A log is a shorthand for `log.log`, among other things.
var log = function () {
log.log.apply(log, arguments)... | }
})
})
// Copy `config` properties to the `log`.
Base.decorate(log, config, true)
// Apply default properties.
Base.decorate(log, defaults || Base.defaults)
// Set up logging methods.
Base.setMethods.apply(log)
// Re-run `setMethods` if `resetters` change.
setMethods = Base.setMethods
... | random_line_split | |
base.js | var doNothing = function () {}
/**
* The `Base` log defines methods that transports will share.
*/
var Base = module.exports = function (config, defaults) {
var cedar = require('../../cedar')
// A log is a shorthand for `log.log`, among other things.
var log = function () {
log.log.apply(log, arguments)... | else {
arg = JSON.stringify(arg, null, this.space)
}
list.push(arg)
}
return '[' + list.join(',') + ']'
},
// Start messages with a prefix for each log method.
prefixes: {
trace: 'TRACE ',
debug: 'DEBUG ',
log: 'LOG ',
info: 'INFO ',
warn: 'WARN ',
error: 'ERR... | {
arg = '"' + (arg.stack || arg.toString()).replace(/\n/, '\\n') + '"'
} | conditional_block |
avatar.view.js | import React, { Component, PropTypes } from 'react' |
import { capitalize } from 'utils'
import './avatar.view.styl'
const DEFAULT_AVATAR_URL = require('./assets/default-avator@2x.png')
export class Avatar extends Component {
static propTypes = {
className: PropTypes.string,
url: PropTypes.string,
size: PropTypes.string
}
static defaultProps = {
... | import cx from 'classnames' | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.