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 |
|---|---|---|---|---|
port-graph.component.ts | import { Component, OnInit, EventEmitter, Output, AfterViewInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';
import * as _moment from 'moment';
import { ToastrService } from 'ngx-toastr';
import { DygraphService } from 'src/app/common/services/dygra... | let formdata = this.filterForm.value;
let direction = formdata.direction;
let autoReloadTime = Number(
this.filterForm.controls["auto_reload_time"].value
);
let downsampling = formdata.download_sample;
let metric = formdata.metric;
let timezone = formdata.timezone;
if (this... |
callPortGraphAPI(){
| random_line_split |
autotypesetbutton.js | ///import core
///import uicore
///import ui/popup.js
///import ui/autotypesetpicker.js
///import ui/splitbutton.js
(function (){
var utils = baidu.editor.utils,
Popup = baidu.editor.ui.Popup,
AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
SplitButton = baidu.editor.ui.SplitButton,
... | (me){
var opt = me.editor.options.autotypeset,
cont = me.getDom(),
ipts = domUtils.getElementsByTagName(cont,"input");
for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
if(ipt.getAttribute("type")=="checkbox"){
var attrName = ipt.getAttribute("name");
... | getPara | identifier_name |
autotypesetbutton.js | ///import core
///import uicore
///import ui/popup.js
///import ui/autotypesetpicker.js
///import ui/splitbutton.js
(function (){
var utils = baidu.editor.utils,
Popup = baidu.editor.ui.Popup,
AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
SplitButton = baidu.editor.ui.SplitButton,
... | btn = cont.getElementsByTagName('button')[0];
btn.onclick = function(){
getPara(popupUI);
me.editor.execCommand('autotypeset')
};
flag = 1;
});
this.initSplitButton();
}
};
... | if(flag)return;
var cont = this.getDom(), | random_line_split |
autotypesetbutton.js | ///import core
///import uicore
///import ui/popup.js
///import ui/autotypesetpicker.js
///import ui/splitbutton.js
(function (){
var utils = baidu.editor.utils,
Popup = baidu.editor.ui.Popup,
AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
SplitButton = baidu.editor.ui.SplitButton,
... | }
});
var flag = 0;
this.popup.addListener('postRenderAfter',function(){
var popupUI = this;
if(flag)return;
var cont = this.getDom(),
btn = cont.getElementsByTagName('button')[0];
btn.onclick = ... | getPara(this);
this.getDom().style.display = 'none';
this._hidden = true;
this.fireEvent('hide');
}
| conditional_block |
autotypesetbutton.js | ///import core
///import uicore
///import ui/popup.js
///import ui/autotypesetpicker.js
///import ui/splitbutton.js
(function (){
var utils = baidu.editor.utils,
Popup = baidu.editor.ui.Popup,
AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
SplitButton = baidu.editor.ui.SplitButton,
... | }
}
}else{
opt[attrName] = true;
}
}
}
}
var selects = domUtils.getElementsByTagName(cont,"select");
for(var i=0,si;si=selects[i++];){
var a... | {
var opt = me.editor.options.autotypeset,
cont = me.getDom(),
ipts = domUtils.getElementsByTagName(cont,"input");
for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
if(ipt.getAttribute("type")=="checkbox"){
var attrName = ipt.getAttribute("name");
... | identifier_body |
coherence_inherent_cc.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... | () {}
| main | identifier_name |
coherence_inherent_cc.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file... | random_line_split | |
coherence_inherent_cc.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... | {} | identifier_body | |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() | print!(".");
}
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
| {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
let mut msg = zmq::Message::new().unwrap();
receiver.recv(&mut msg, 0).unwrap();... | identifier_body |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zm... | receiver.recv(&mut msg, 0).unwrap();
// Start our clock now
let start = Instant::now();
for i in 1..101 {
receiver.recv(&mut msg, 0).unwrap();
if i % 10 == 0 {
print!(":");
} else {
print!(".");
}
}
println!("\nTotal elapsed time: ... | let mut msg = zmq::Message::new().unwrap();
| random_line_split |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zm... |
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
| {
print!(".");
} | conditional_block |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn | () {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
let mut msg = zmq::Message::new().unwrap();
receiver.recv(&mut msg, 0).unwrap... | main | identifier_name |
Signal2.ts |
/*
* Signal2
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, subl... |
else
{
this.emitImpl(arg1, arg2);
}
}
private emitImpl(arg1:T1, arg2:T2)
{
var head = this.willEmit();
var p = head;
while(p != null)
{
p._listener(arg1, arg2)
if(!p.stayInList)
{
p.dispose();
}
p = p._next;
}
this.didEmit(head);
}
}
| {
this.defer(() => this.emitImpl(arg1, arg2));
} | conditional_block |
Signal2.ts |
/*
* Signal2
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, subl... | <T1,T2> extends SignalAbstract
{
/**
* Emit the signal, notifying each connected listener.
*
* @method emit
*/
public emit(arg1:T1, arg2:T2)
{
if(this.dispatching())
{
this.defer(() => this.emitImpl(arg1, arg2));
}
else
{
this.emitImpl(arg1, arg2);
}
}
private emitImpl(arg1:T1, arg2:T2)
... | Signal2 | identifier_name |
Signal2.ts | /*
* Signal2
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublic... | {
this.defer(() => this.emitImpl(arg1, arg2));
}
else
{
this.emitImpl(arg1, arg2);
}
}
private emitImpl(arg1:T1, arg2:T2)
{
var head = this.willEmit();
var p = head;
while(p != null)
{
p._listener(arg1, arg2)
if(!p.stayInList)
{
p.dispose();
}
p = p._next;
}
this.didEm... | * @method emit
*/
public emit(arg1:T1, arg2:T2)
{
if(this.dispatching()) | random_line_split |
classglobal.js | var classglobal =
[
[ "Buffer", "df/d84/classglobal.html#a77b5ab3a88955255ac7abc7251919fbc", null ],
[ "run", "df/d84/classglobal.html#a917c15ea7d2eafaa6df0aea5868a86e7", null ], | ]; | [ "require", "df/d84/classglobal.html#a9b11defd1000737a5b70b50edfcc8156", null ],
[ "GC", "df/d84/classglobal.html#a02a28758a633a7b1493471415c8949ba", null ],
[ "console", "df/d84/classglobal.html#a69cd8fa430cb4536156e8052a37c9303", null ] | random_line_split |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... |
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
| {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
} | identifier_body |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... |
}
if self.include_backtrace {
write!(f, "{}", self.err.backtrace())?;
}
Ok(())
}
}
/// Extensions to standard `failure::Error` trait.
pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with... | {
writeln!(f, " caused by: {}", cause)?;
} | conditional_block |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... | (&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
}
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
| display_causes_and_backtrace | identifier_name |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... | pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes, plus an optional
/// backtrace.
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace;
/// Wrap the error in `DisplayCau... | }
/// Extensions to standard `failure::Error` trait. | random_line_split |
estimated-input-latency-test.js | /**
* Copyright 2016 Google 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 by applic... | (trace) {
return Object.assign({
traces: {
[Audit.DEFAULT_PASS]: trace
}
}, computedArtifacts);
}
/* eslint-env mocha */
describe('Performance: estimated-input-latency audit', () => {
it('evaluates valid input correctly', () => {
const artifacts = generateArtifactsWithTrace({traceEvents: pwaTra... | generateArtifactsWithTrace | identifier_name |
estimated-input-latency-test.js | /**
* Copyright 2016 Google 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 by applic... |
/* eslint-env mocha */
describe('Performance: estimated-input-latency audit', () => {
it('evaluates valid input correctly', () => {
const artifacts = generateArtifactsWithTrace({traceEvents: pwaTrace});
return Audit.audit(artifacts).then(output => {
assert.equal(output.debugString, undefined);
a... | {
return Object.assign({
traces: {
[Audit.DEFAULT_PASS]: trace
}
}, computedArtifacts);
} | identifier_body |
estimated-input-latency-test.js | /**
* Copyright 2016 Google 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 by applic... | */
'use strict';
const Audit = require('../../audits/estimated-input-latency.js');
const Runner = require('../../runner.js');
const assert = require('assert');
const pwaTrace = require('../fixtures/traces/progressive-app.json');
const computedArtifacts = Runner.instantiateComputedArtifacts();
function generateArti... | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. | random_line_split |
Folders.js | import ko from 'ko';
import { ClientSideKeyName, Notification, Magics } from 'Common/Enums';
import { trim, noop } from 'Common/Utils';
import { getNotification, i18n } from 'Common/Translator';
import { removeFolderFromCacheList } from 'Common/Cache';
import { appSettingsGet } from 'Storage/Settings';
import * as L... | (folder) {
const nameToEdit = folder ? trim(folder.nameForEdit()) : '';
if ('' !== nameToEdit && folder.name() !== nameToEdit) {
Local.set(ClientSideKeyName.FoldersLashHash, '');
getApp().foldersPromisesActionHelper(
Promises.folderRename(folder.fullNameRaw, nameToEdit, FolderStore.foldersRenaming),
... | folderEditOnEnter | identifier_name |
Folders.js | import ko from 'ko';
import { ClientSideKeyName, Notification, Magics } from 'Common/Enums';
import { trim, noop } from 'Common/Utils';
import { getNotification, i18n } from 'Common/Translator';
import { removeFolderFromCacheList } from 'Common/Cache';
import { appSettingsGet } from 'Storage/Settings';
import * as L... | 0 === folderToRemove.privateMessageCountAll()
) {
this.folderForDeletion(null);
if (folderToRemove) {
const fRemoveFolder = function(folder) {
if (folderToRemove === folder) {
return true;
}
folder.subFolders.remove(fRemoveFolder);
return false;
};
Local.set(ClientSide... | deleteFolder(folderToRemove) {
if (
folderToRemove &&
folderToRemove.canBeDeleted() &&
folderToRemove.deleteAccess() && | random_line_split |
Folders.js | import ko from 'ko';
import { ClientSideKeyName, Notification, Magics } from 'Common/Enums';
import { trim, noop } from 'Common/Utils';
import { getNotification, i18n } from 'Common/Translator';
import { removeFolderFromCacheList } from 'Common/Cache';
import { appSettingsGet } from 'Storage/Settings';
import * as L... |
checkableFalseFolder(folder) {
Remote.folderSetCheckable(noop, folder.fullNameRaw, false);
folder.checkable(false);
}
}
export { FoldersUserSettings, FoldersUserSettings as default };
| {
Remote.folderSetCheckable(noop, folder.fullNameRaw, true);
folder.checkable(true);
} | identifier_body |
Folders.js | import ko from 'ko';
import { ClientSideKeyName, Notification, Magics } from 'Common/Enums';
import { trim, noop } from 'Common/Utils';
import { getNotification, i18n } from 'Common/Translator';
import { removeFolderFromCacheList } from 'Common/Cache';
import { appSettingsGet } from 'Storage/Settings';
import * as L... |
folder.edited(false);
}
folderEditOnEsc(folder) {
if (folder) {
folder.edited(false);
}
}
onShow() {
FolderStore.folderList.error('');
}
onBuild(oDom) {
oDom
.on('mouseover', '.delete-folder-parent', () => {
this.folderListHelp(i18n('SETTINGS_FOLDERS/HELP_DELETE_FOLDER'));
})
.on('m... | {
Local.set(ClientSideKeyName.FoldersLashHash, '');
getApp().foldersPromisesActionHelper(
Promises.folderRename(folder.fullNameRaw, nameToEdit, FolderStore.foldersRenaming),
Notification.CantRenameFolder
);
removeFolderFromCacheList(folder.fullNameRaw);
folder.name(nameToEdit);
} | conditional_block |
ActiveCallListPanel.tsx | import React, { FunctionComponent } from 'react';
import BackHeader from 'ringcentral-widgets/components/BackHeaderV2';
import classNames from 'classnames';
import {
EvActiveCallListUIFunctions,
EvActiveCallListUIProps,
} from '../../interfaces';
import {
HandUpButton,
HoldCallButton,
} from '../SmallCallContr... | (styles.emphasisCallInfo, styles.children)}
>
{i18n.getString('justMe', currentLocale)}
</span>,
<div className={classNames(styles.otherCallInfo, styles.children)}>
<span className={styles.name}>
{callItem.session.transferSessions?.[callIte... | classNames | identifier_name |
ActiveCallListPanel.tsx | import React, { FunctionComponent } from 'react';
import BackHeader from 'ringcentral-widgets/components/BackHeaderV2';
import classNames from 'classnames';
import {
EvActiveCallListUIFunctions,
EvActiveCallListUIProps,
} from '../../interfaces';
import {
HandUpButton,
HoldCallButton,
} from '../SmallCallContr... | export { ActiveCallListPanel }; | random_line_split | |
ActiveCallListPanel.tsx | import React, { FunctionComponent } from 'react';
import BackHeader from 'ringcentral-widgets/components/BackHeaderV2';
import classNames from 'classnames';
import {
EvActiveCallListUIFunctions,
EvActiveCallListUIProps,
} from '../../interfaces';
import {
HandUpButton,
HoldCallButton,
} from '../SmallCallContr... |
</span>,
<div className={classNames(styles.otherCallInfo, styles.children)}>
<span className={styles.name}>
{callItem.session.transferSessions?.[callItem.session.sessionId]
?.destination ?? null}
</span>
{/* TODO: add p... | {i18n.getString('justMe', currentLocale)} | identifier_body |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T: ?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [... |
impl FaI {
fn from_data<T: ?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
let mut hash_arr: [u8; FINGERPRINT_SIZE] = [0; FINGERPRINT_SIZE];
let hash = get_hash::<_, H>(data);
let mut n = 0;
let fp;
loop {
for i in 0..FINGERPRINT_SIZE {
hash_arr[i] = hash[i] + n;
}... | {
let hash = get_hash::<_, H>(&fp.data);
let alt_i = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
(i ^ alt_i) as usize
} | identifier_body |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T: ?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [... |
n += 1;
}
let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1);
FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
... | {
fp = val;
break;
} | conditional_block |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T: ?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [... | FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
pub fn get_fai<T: ?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
FaI::from_data::<_, H>(data)
}
#[test]
fn test_fp_an... | let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1); | random_line_split |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn | <T: ?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0; 4];
{
let mut hasher = <H as Default>::default();
data.hash(&mut hasher);
let _ = (&mut result[..]).write_u32::<BigEndian>(hasher.finish() as u32);
}
result
}
pub fn get_alt_index<H: Hasher + Default>(fp: Fingerprin... | get_hash | identifier_name |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... |
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> Root<SVGSVGElement> {
Node::reflect_node(box SVGSVGElement::new_inherited(local_name, prefix, document),
document,
... | {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
} | identifier_body |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | {
svggraphicselement: SVGGraphicsElement
}
impl SVGSVGElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> SVGSVGElement {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inhe... | SVGSVGElement | identifier_name |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | }
pub trait LayoutSVGSVGElementHelpers {
fn data(&self) -> SVGSVGData;
}
impl LayoutSVGSVGElementHelpers for LayoutJS<SVGSVGElement> {
#[allow(unsafe_code)]
fn data(&self) -> SVGSVGData {
unsafe {
let SVG = &*self.unsafe_get();
let width_attr = SVG.upcast::<Element>().get_... | random_line_split | |
gentoo-compare-json.py | #!/usr/bin/python3
# This script will compare the versions of ebuilds in the funtoo portage tree against
# the versions of ebuilds in the target portage tree. Any higher versions in the
# target Portage tree will be printed to stdout.
import portage.versions
import os,sys
import subprocess
import json
from merge_ut... |
gbest = portage.versions.best(gebuilds)
if fbest == gbest:
continue
# a little trickery to ignore rev differences:
fps = list(portage.versions.catpkgsplit(fbest))[1:]
gps = list(portage.versions.catpkgsplit(gbest))[1:]
gps[-1] = "r0"
fps[-1] = "r0"
if gps[-2] in [ "9999", "99999", "9... | continue | random_line_split |
gentoo-compare-json.py | #!/usr/bin/python3
# This script will compare the versions of ebuilds in the funtoo portage tree against
# the versions of ebuilds in the target portage tree. Any higher versions in the
# target Portage tree will be printed to stdout.
import portage.versions
import os,sys
import subprocess
import json
from merge_ut... | (portdir, ebuild, warn):
a = subprocess.getstatusoutput(dirpath + "/keywords.sh %s %s" % ( portdir, ebuild ) )
if a[0] == 0:
my_set = set(a[1].split())
return (0, my_set)
else:
return a
if len(sys.argv) != 3:
print("Please specify funtoo tree as first argument, gentoo tree as second argument.")
sys.exit(1... | getKeywords | identifier_name |
gentoo-compare-json.py | #!/usr/bin/python3
# This script will compare the versions of ebuilds in the funtoo portage tree against
# the versions of ebuilds in the target portage tree. Any higher versions in the
# target Portage tree will be printed to stdout.
import portage.versions
import os,sys
import subprocess
import json
from merge_ut... | while True:
fbest = portage.versions.best(filtered)
if fbest == "":
break
retval, fkeywords = getKeywords(portdir, "%s/%s/%s.ebuild" % (cat, pkg, fbest.split("/")[1] ), warn)
if len(keywords & fkeywords) == 0:
filtered.remove(fbest)
else:
break
return filtered
def get_cpv_in_portdir(portdir,cat,... | """
This function accepts a path to a portage tree, a list of ebuilds, and a list of
keywords. It will iteratively find the "best" version in the ebuild list (the most
recent), and then manually extract this ebuild's KEYWORDS using the getKeywords()
function. If at least one of the keywords in "keywords" cannot be... | identifier_body |
gentoo-compare-json.py | #!/usr/bin/python3
# This script will compare the versions of ebuilds in the funtoo portage tree against
# the versions of ebuilds in the target portage tree. Any higher versions in the
# target Portage tree will be printed to stdout.
import portage.versions
import os,sys
import subprocess
import json
from merge_ut... |
elif keyw == "~amd64":
label = "fcx8664"
json_out[label] = []
if keyw[0] == "~":
# for unstable, add stable arch and ~* and * keywords too
keyw = [ keyw, keyw[1:], "~*", "*"]
else:
# for stable, also consider the * keyword
keyw = [ keyw, "*"]
version_compare(portdir,gportdir,keyw,label)
for key in json... | label = "fcx8632" | conditional_block |
core-apis.js | 'use strict';
const test = require('tape');
const express = require('express');
const rested = require('../lib');
class MyResource {
constructor(id, info) {
this.id = id;
this.info = JSON.parse(JSON.stringify(info));
}
createId() {
this.id = 'foo';
return this.id;
}
}
test('Core APIs', function (t) {
... |
});
route(col, { rights: true });
route(col, 'myresource', { rights: true });
route(col, '/myresource', { rights: true });
t.end();
});
t.test('Collection edge behaviors', function (t) {
t.throws(function () {
rested.createCollection('Not a class');
}, 'Resource class must be a function');
con... | {
cb();
} | identifier_body |
core-apis.js | 'use strict';
const test = require('tape');
const express = require('express');
const rested = require('../lib');
class MyResource {
constructor(id, info) {
this.id = id;
this.info = JSON.parse(JSON.stringify(info));
}
| () {
this.id = 'foo';
return this.id;
}
}
test('Core APIs', function (t) {
t.test('Collection instances', function (t) {
const col = rested.createCollection(MyResource);
t.strictEqual(rested.getCollection('myresource'), col);
rested.delCollection('myresource');
t.end();
});
t.test('Rest instance', fu... | createId | identifier_name |
core-apis.js | 'use strict';
const test = require('tape');
const express = require('express');
const rested = require('../lib');
class MyResource {
constructor(id, info) {
this.id = id;
this.info = JSON.parse(JSON.stringify(info));
}
createId() {
this.id = 'foo';
return this.id;
}
}
test('Core APIs', function (t) {
... | t.test('Collection JSON', function (t) {
const col = rested.createCollection(MyResource);
col.set('abc', new MyResource('abc', {}));
t.equal(JSON.stringify(col), '{"abc":{"id":"abc","info":{}}}', 'JSON.stringify(collection) produces valid JSON');
col.loadMap({
def: new MyResource('def', {}),
ghi: {}
... | });
});
});
| random_line_split |
block_device.py | _only_fields)
class BlockDeviceDict(dict):
"""Represents a Block Device Mapping in Nova."""
_fields = bdm_new_fields
_db_only_fields = (bdm_db_only_fields |
bdm_db_inherited_fields)
_required_fields = set(['source_type'])
def __init__(self, bdm_dict=None, do_not_default=None):
... | bdm_dict['delete_on_termination'] = strutils.bool_from_string(
bdm_dict['delete_on_termination'])
if bdm_dict.get('device_name') is not None:
validate_device_name(bdm_dict['device_name'])
validate_and_default_volume_size(bdm_dict)
if bdm_dict.get('boot_... | """Basic data format validations."""
dict_fields = set(key for key, _ in bdm_dict.iteritems())
# Check that there are no bogus fields
if not (dict_fields <=
(self._fields | self._db_only_fields)):
raise exception.InvalidBDMFormat(
details="Some fields... | identifier_body |
block_device.py | _only_fields)
class BlockDeviceDict(dict):
"""Represents a Block Device Mapping in Nova."""
_fields = bdm_new_fields
_db_only_fields = (bdm_db_only_fields |
bdm_db_inherited_fields)
_required_fields = set(['source_type'])
def __init__(self, bdm_dict=None, do_not_default=None):
... | (cls, legacy_bdm):
copy_over_fields = bdm_legacy_fields & bdm_new_fields
copy_over_fields |= (bdm_db_only_fields |
bdm_db_inherited_fields)
# NOTE (ndipanov): These fields cannot be computed
# from legacy bdm, so do not default them
# to avoid overwr... | from_legacy | identifier_name |
block_device.py | _api_only_fields)
class BlockDeviceDict(dict):
"""Represents a Block Device Mapping in Nova."""
_fields = bdm_new_fields
_db_only_fields = (bdm_db_only_fields |
bdm_db_inherited_fields)
_required_fields = set(['source_type'])
def __init__(self, bdm_dict=None, do_not_default=None)... | """get root device name from image meta data.
If it isn't specified, return None.
"""
root_device_name = None
# NOTE(yamahata): see image_service.s3.s3create()
for bdm in properties.get('mappings', []):
if bdm['virtual'] == 'root':
root_device_name = bdm['device']
# NOT... | return ([image_bdm] if image_bdm else []) + new_bdms
def properties_root_device_name(properties): | random_line_split |
block_device.py | _only_fields)
class BlockDeviceDict(dict):
"""Represents a Block Device Mapping in Nova."""
_fields = bdm_new_fields
_db_only_fields = (bdm_db_only_fields |
bdm_db_inherited_fields)
_required_fields = set(['source_type'])
def __init__(self, bdm_dict=None, do_not_default=None):
... |
return legacy_block_device_mapping
def from_legacy_mapping(legacy_block_device_mapping, image_uuid='',
root_device_name=None):
"""Transform a legacy list of block devices to the new data format."""
new_bdms = [BlockDeviceDict.from_legacy(legacy_bdm)
for legacy_bd... | dev['virtual_name'] = dev['virtual_name'][:-1] + str(i) | conditional_block |
pwang13.py | class O:
"""
Basic Class which
- Helps dynamic updates
- Pretty Prints
"""
def __init__(self, **kwargs):
self.has().update(**kwargs)
def has(self):
return self.__dict__
def update(self, **kwargs):
|
def __repr__(self):
show = [':%s %s' % (k, self.has()[k])
for k in sorted(self.has().keys())
if k[0] is not "_"]
txt = ' '.join(show)
if len(txt) > 60:
show = map(lambda x: '\t' + x + '\n', show)
return '{' + ' '.join(show) + '}'
def sa... | self.has().update(kwargs)
return self | identifier_body |
pwang13.py | class O:
"""
Basic Class which
- Helps dynamic updates
- Pretty Prints
"""
def __init__(self, **kwargs):
self.has().update(**kwargs)
def has(self):
return self.__dict__
def update(self, **kwargs):
self.has().update(kwargs)
return self
def _... | # using the auxilary classes provided above.
self.decisions = (Decision('r', 0, 10), Decision('h', 0, 20))
# print(self.decisions)
self.objectives = (Objective("S"), Objective("T"))
@staticmethod
def evaluate(point):
[r, h] = point.decisions
# print(point.decisio... | def __init__(self):
O.__init__(self)
# TODO 2: Code up decisions and objectives below for the problem | random_line_split |
pwang13.py | class O:
"""
Basic Class which
- Helps dynamic updates
- Pretty Prints
"""
def __init__(self, **kwargs):
self.has().update(**kwargs)
def has(self):
return self.__dict__
def update(self, **kwargs):
self.has().update(kwargs)
return self
def _... |
cone = Problem()
# point = cone.generate_one()
# cone.evaluate(point)
# print (point)
def populate(problem, size):
population = []
# TODO 6: Create a list of points of length 'size'
for _ in xrange(size):
population.append(problem.generate_one())
return population
# return (problem.gen... | return point
# return point | conditional_block |
pwang13.py | class O:
"""
Basic Class which
- Helps dynamic updates
- Pretty Prints
"""
def __init__(self, **kwargs):
self.has().update(**kwargs)
def has(self):
return self.__dict__
def | (self, **kwargs):
self.has().update(kwargs)
return self
def __repr__(self):
show = [':%s %s' % (k, self.has()[k])
for k in sorted(self.has().keys())
if k[0] is not "_"]
txt = ' '.join(show)
if len(txt) > 60:
show = map(lambda x: '\... | update | identifier_name |
multiple_files.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
.... | main | identifier_name |
multiple_files.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
... | {
let mut rng = task_rng();
// a subset of the XID_start unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
... | identifier_body |
multiple_files.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // compiler changes.
assert!(err.as_slice().contains("expected item but found"))
}
} | // can't exec it directly
let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
// positive test so that this test will be updated when the | random_line_split |
TaskLogo.js | /* ************************************************************************
Copyright: 2009 OETIKER+PARTNER AG
License: GPLv3 or later
Authors: Tobi Oetiker <tobi@oetiker.ch>
Utf8Check: äöü
************************************************************************ */
/**
* A container that looks a bit ... | var t = new qx.ui.container.Composite(new qx.ui.layout.VBox(3)).set({ opacity : 0.5 });
t.addListener('mouseover', function(e) {
this.setOpacity(1);
}, t);
t.addListener('mouseout', function(e) {
this.setOpacity(0.5);
}, t);
t.add(new qx.ui.basic... | this.setCursor('pointer');
this.addListener('click', function(e) {
qx.bom.Window.open(link, '_blank');
});
}
| conditional_block |
TaskLogo.js | /* ************************************************************************
Copyright: 2009 OETIKER+PARTNER AG
License: GPLv3 or later
Authors: Tobi Oetiker <tobi@oetiker.ch>
Utf8Check: äöü
************************************************************************ */
/**
* A container that looks a bit ... |
this.add(t);
}
}); | random_line_split | |
aes_ecb_decrypter.rs | /* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <dima@hlabs.org>
*/
extern crate serialize;
extern crate aes_lib;
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn | (mut file: File, key: &[u8]) -> Vec<u8> {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
decrypt_aes_ecb(encrypted.as_slice(), key)
}
/*
* Main entry point
*/
fn main() {
let key = b"YELLOW SUBMARINE";
let path... | decrypt_aes_ecb_file | identifier_name |
aes_ecb_decrypter.rs | /* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <dima@hlabs.org>
*/
extern crate serialize;
extern crate aes_lib;
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn decrypt_aes_ecb_file(mut file: File, key: &[u8]) -> Vec<u8> |
/*
* Main entry point
*/
fn main() {
let key = b"YELLOW SUBMARINE";
let path = Path::new("aes_ecb_encrypted.txt");
let decrypted = match File::open(&path) {
Ok(file) => decrypt_aes_ecb_file(file, key),
Err(err) => panic!("Unable to open aes_ecb_encrypted.txt: {}", err)
};
println... | {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
decrypt_aes_ecb(encrypted.as_slice(), key)
} | identifier_body |
aes_ecb_decrypter.rs | /* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <dima@hlabs.org>
*/
|
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn decrypt_aes_ecb_file(mut file: File, key: &[u8]) -> Vec<u8> {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
... | extern crate serialize;
extern crate aes_lib; | random_line_split |
test_ansiblegate.py | import pytest
pytestmark = [
pytest.mark.skip_on_windows(reason="Not supported on Windows"),
pytest.mark.skip_if_binaries_missing(
"ansible",
"ansible-doc",
"ansible-playbook",
check_all=True,
reason="ansible is not installed",
),
]
@pytest.fixture
def ansible_ping... | (ansible_ping_func):
"""
Test that the ansible functions are actually loaded
"""
expected = "foobar"
ret = ansible_ping_func(data=expected)
assert ret == {"ping": expected}
| test_passing_data_to_ansible_modules | identifier_name |
test_ansiblegate.py | import pytest
pytestmark = [
pytest.mark.skip_on_windows(reason="Not supported on Windows"),
pytest.mark.skip_if_binaries_missing(
"ansible",
"ansible-doc",
"ansible-playbook",
check_all=True,
reason="ansible is not installed",
),
]
@pytest.fixture
def ansible_ping... |
pytest.fail("Where is the ping function these days in Ansible?!")
def test_ansible_functions_loaded(ansible_ping_func):
"""
Test that the ansible functions are actually loaded
"""
ret = ansible_ping_func()
assert ret == {"ping": "pong"}
def test_passing_data_to_ansible_modules(ansible_ping... | return modules.ansible.ping | conditional_block |
test_ansiblegate.py | import pytest
pytestmark = [
pytest.mark.skip_on_windows(reason="Not supported on Windows"),
pytest.mark.skip_if_binaries_missing(
"ansible",
"ansible-doc",
"ansible-playbook",
check_all=True,
reason="ansible is not installed",
),
]
| # The ansible hack injects, in this case, "system.ping" as an attribute to the loaded module
return getattr(modules.ansible, "system.ping")
if "ansible.ping" in modules:
# Ansible >= 2.10
return modules.ansible.ping
pytest.fail("Where is the ping function these days in Ansible?... | @pytest.fixture
def ansible_ping_func(modules):
if "ansible.system.ping" in modules:
# we need to go by getattr() because salt's loader will try to find "system" in the dictionary and fail | random_line_split |
test_ansiblegate.py | import pytest
pytestmark = [
pytest.mark.skip_on_windows(reason="Not supported on Windows"),
pytest.mark.skip_if_binaries_missing(
"ansible",
"ansible-doc",
"ansible-playbook",
check_all=True,
reason="ansible is not installed",
),
]
@pytest.fixture
def ansible_ping... |
def test_ansible_functions_loaded(ansible_ping_func):
"""
Test that the ansible functions are actually loaded
"""
ret = ansible_ping_func()
assert ret == {"ping": "pong"}
def test_passing_data_to_ansible_modules(ansible_ping_func):
"""
Test that the ansible functions are actually loaded... | if "ansible.system.ping" in modules:
# we need to go by getattr() because salt's loader will try to find "system" in the dictionary and fail
# The ansible hack injects, in this case, "system.ping" as an attribute to the loaded module
return getattr(modules.ansible, "system.ping")
if "ansibl... | identifier_body |
__init__.py | """Support for EcoNet products."""
from datetime import timedelta
import logging
from aiohttp.client_exceptions import ClientError
from pyeconet import EcoNetApiInterface
from pyeconet.equipment import EquipmentType
from pyeconet.errors import (
GenericHTTPError,
InvalidCredentialsError,
InvalidResponseFor... | @property
def unique_id(self):
"""Return the unique ID of the entity."""
return f"{self._econet.device_id}_{self._econet.device_name}"
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_FAHRENHEIT
@property
def should_poll(se... | return self._econet.device_name
| random_line_split |
__init__.py | """Support for EcoNet products."""
from datetime import timedelta
import logging
from aiohttp.client_exceptions import ClientError
from pyeconet import EcoNetApiInterface
from pyeconet.equipment import EquipmentType
from pyeconet.errors import (
GenericHTTPError,
InvalidCredentialsError,
InvalidResponseFor... | (now):
"""Fetch the latest changes from the API."""
await api.refresh_equipment()
config_entry.async_on_unload(async_track_time_interval(hass, resubscribe, INTERVAL))
config_entry.async_on_unload(
async_track_time_interval(hass, fetch_update, INTERVAL + timedelta(minutes=1))
)
... | fetch_update | identifier_name |
__init__.py | """Support for EcoNet products."""
from datetime import timedelta
import logging
from aiohttp.client_exceptions import ClientError
from pyeconet import EcoNetApiInterface
from pyeconet.equipment import EquipmentType
from pyeconet.errors import (
GenericHTTPError,
InvalidCredentialsError,
InvalidResponseFor... |
async def resubscribe(now):
"""Resubscribe to the MQTT updates."""
await hass.async_add_executor_job(api.unsubscribe)
api.subscribe()
async def fetch_update(now):
"""Fetch the latest changes from the API."""
await api.refresh_equipment()
config_entry.async_on_unlo... | _eqip.set_update_callback(update_published) | conditional_block |
__init__.py | """Support for EcoNet products."""
from datetime import timedelta
import logging
from aiohttp.client_exceptions import ClientError
from pyeconet import EcoNetApiInterface
from pyeconet.equipment import EquipmentType
from pyeconet.errors import (
GenericHTTPError,
InvalidCredentialsError,
InvalidResponseFor... |
@property
def name(self):
"""Return the name of the entity."""
return self._econet.device_name
@property
def unique_id(self):
"""Return the unique ID of the entity."""
return f"{self._econet.device_id}_{self._econet.device_name}"
@property
def temperature_unit... | """Return device registry information for this entity."""
return DeviceInfo(
identifiers={(DOMAIN, self._econet.device_id)},
manufacturer="Rheem",
name=self._econet.device_name,
) | identifier_body |
mfn.menu.js | /*
@Name: Horizontal multilevel menu
@Author: Muffin Group
@WWW: www.muffingroup.com
@Version: 1.5.2 | var menu = $(this);
var defaults = {
delay : 100,
hoverClass : 'hover',
arrows : true,
animation : 'fade',
addLast : true
};
options = $.extend(defaults, options);
// add class if menu item has sumbenu
menu.find("li:has(ul)")
.addClass("submenu")
.app... | */
(function($){
$.fn.extend({
muffingroup_menu: function(options) { | random_line_split |
mfn.menu.js | /*
@Name: Horizontal multilevel menu
@Author: Muffin Group
@WWW: www.muffingroup.com
@Version: 1.5.2
*/
(function($){
$.fn.extend({
muffingroup_menu: function(options) {
var menu = $(this);
var defaults = {
delay : 100,
hoverClass : 'hover',
arrows : true,
animation... |
// add bullets in each top-level menu item
menu.children( "li:not(:last)" ).append( "<em>•</em>" );
// hover
menu.find("li").hover(function() {
$(this).addClass(options.hoverClass);
if (options.animation === "fade") {
$(this).children("ul").fadeIn(options.delay);
} else if (opti... | {
menu.find( "li ul li:has(ul) > a" ).append( "<span class='menu-arrow'><i class='icon-chevron-right'></i></span>" );
} | conditional_block |
rpcbind_test.py | #!/usr/bin/env python
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test for -rpcbind, as well as -rpcallowip and -rpcconnect
# Add python-bitcoinrpc to module search path:... | (tmpdir, allow_ips, rpchost, rpcport):
'''
Start a node with rpcwallow IP, and request getinfo
at a non-localhost IP.
'''
base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips]
nodes = start_nodes(1, tmpdir, [base_args])
try:
# connect to node through non... | run_allowip_test | identifier_name |
rpcbind_test.py | #!/usr/bin/env python
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test for -rpcbind, as well as -rpcallowip and -rpcconnect
# Add python-bitcoinrpc to module search path:... |
if __name__ == '__main__':
main()
| print("Failed")
sys.exit(1) | conditional_block |
rpcbind_test.py | #!/usr/bin/env python
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test for -rpcbind, as well as -rpcallowip and -rpcconnect
# Add python-bitcoinrpc to module search path:... | os.makedirs(options.tmpdir)
initialize_chain(options.tmpdir)
run_test(options.tmpdir)
success = True
except AssertionError as e:
print("Assertion failed: "+e.message)
except Exception as e:
print("Unexpected exception caught during testing: "+str(e))
... | import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave dogecoinds and test.* datadir on exit or error")
parser.add_option("--srcdir", dest="srcdir", default="../../src",... | identifier_body |
rpcbind_test.py | #!/usr/bin/env python
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test for -rpcbind, as well as -rpcallowip and -rpcconnect
# Add python-bitcoinrpc to module search path:... | success = True
except AssertionError as e:
print("Assertion failed: "+e.message)
except Exception as e:
print("Unexpected exception caught during testing: "+str(e))
traceback.print_tb(sys.exc_info()[2])
if not options.nocleanup:
print("Cleaning up")
wait_dog... | random_line_split | |
mwc-button-base.d.ts | /**
@license
Copyright 2019 Google 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 by applicable law or agr... | extends LitElement {
raised: boolean;
unelevated: boolean;
outlined: boolean;
dense: boolean;
disabled: boolean;
trailingIcon: boolean;
fullwidth: boolean;
icon: string;
label: string;
expandContent: boolean;
buttonElement: HTMLElement;
ripple: Promise<Ripple | null>;
... | ButtonBase | identifier_name |
mwc-button-base.d.ts | /**
@license
Copyright 2019 Google 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 by applicable law or agr... | outlined: boolean;
dense: boolean;
disabled: boolean;
trailingIcon: boolean;
fullwidth: boolean;
icon: string;
label: string;
expandContent: boolean;
buttonElement: HTMLElement;
ripple: Promise<Ripple | null>;
protected shouldRenderRipple: boolean;
protected rippleHandler... | /** @soyCompatible */
export declare class ButtonBase extends LitElement {
raised: boolean;
unelevated: boolean; | random_line_split |
issue-19358.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | struct Bar<T> where T: Trait {
bar: T,
}
impl Trait for int {}
fn main() {
let a = Foo { foo: 12i };
let b = Bar { bar: 12i };
println!("{:?} {:?}", a, b);
} | random_line_split | |
issue-19358.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let a = Foo { foo: 12i };
let b = Bar { bar: 12i };
println!("{:?} {:?}", a, b);
}
| main | identifier_name |
setup.py | import codecs
import re
from os import path
from setuptools import setup, find_packages
def read(*parts):
file_path = path.join(path.dirname(__file__), *parts)
return codecs.open(file_path).read()
def | (*parts):
version_file = read(*parts)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='django_qbe',
version... | find_version | identifier_name |
setup.py | import codecs
import re
from os import path
from setuptools import setup, find_packages
def read(*parts):
file_path = path.join(path.dirname(__file__), *parts)
return codecs.open(file_path).read()
def find_version(*parts):
|
setup(
name='django_qbe',
version=find_version('django_qbe', '__init__.py'),
author='Javier de la Rosa',
author_email='versae@gmail.com',
url='http://versae.github.com/qbe/',
description='Django admin tool for custom reports',
long_description=read('README.rst'),
license='MIT',
key... | version_file = read(*parts)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.") | identifier_body |
setup.py | import codecs
import re
from os import path
from setuptools import setup, find_packages
def read(*parts):
file_path = path.join(path.dirname(__file__), *parts)
return codecs.open(file_path).read()
def find_version(*parts):
version_file = read(*parts)
version_match = re.search(r"^__version__ = ['\"](... |
raise RuntimeError("Unable to find version string.")
setup(
name='django_qbe',
version=find_version('django_qbe', '__init__.py'),
author='Javier de la Rosa',
author_email='versae@gmail.com',
url='http://versae.github.com/qbe/',
description='Django admin tool for custom reports',
long_d... | return version_match.group(1) | conditional_block |
setup.py | import codecs
import re
from os import path
from setuptools import setup, find_packages
def read(*parts):
file_path = path.join(path.dirname(__file__), *parts)
return codecs.open(file_path).read() | version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='django_qbe',
version=find_version('django_qbe', '__init__.py')... |
def find_version(*parts):
version_file = read(*parts) | random_line_split |
test_idct.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... | (self):
# values from Matlab/Octave
inputArray = [ 0.89442718, -0.60150099, -0.12078822, -0.37174806, 0.82789522]
expected = [ 0, 0, 1, 0, 1 ]
self.assertAlmostEqualVector(IDCT(outputSize=len(expected), inputSize = len(inputArray))(inputArray), expected, 1e-6)
def testLifteringRegr... | testRegression | identifier_name |
test_idct.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... | TextTestRunner(verbosity=2).run(suite) | conditional_block | |
test_idct.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... |
def testRegression(self):
# values from Matlab/Octave
inputArray = [ 0.89442718, -0.60150099, -0.12078822, -0.37174806, 0.82789522]
expected = [ 0, 0, 1, 0, 1 ]
self.assertAlmostEqualVector(IDCT(outputSize=len(expected), inputSize = len(inputArray))(inputArray), expected, 1e-6)
... | self.assertConfigureFails(IDCT(), { 'inputSize': 0, 'outputSize': 2 })
self.assertConfigureFails(IDCT(), { 'inputSize': 6, 'outputSize': 0 }) | identifier_body |
test_idct.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... |
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite) |
suite = allTests(TestIDCT) | random_line_split |
test.py | #!/usr/bin/python2.7
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import time
import unittest
from pycopia import anypath
from pycopia import asyncio
from pycopia import asyncserver
from pycop... | (counters, starttimes):
thetime = time.time()
counters[4] += 1
starttimes[4] = thetime
print ("test oneshot at", thetime)
s = pycopia.OS.sequencer.Sequencer()
start = time.time()
s.add_task(_test_job, 2.0, duration=20.0, callback_args=(counters,))... | _test_oneshot | identifier_name |
test.py | #!/usr/bin/python2.7
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import time
import unittest
from pycopia import anypath
from pycopia import asyncio
from pycopia import asyncserver
from pycop... | counters[4] += 1
starttimes[4] = thetime
print ("test oneshot at", thetime)
s = pycopia.OS.sequencer.Sequencer()
start = time.time()
s.add_task(_test_job, 2.0, duration=20.0, callback_args=(counters,))
s.add_task(_test_job2, 3.0, duration=30.0, callba... | counters = [0, 0, 0, 0, 0]
starttimes = [None, None, None, None, None]
def _test_job(counters):
print ("test job 1")
counters[0] += 1
def _test_job2(counters):
print ("test job 2")
counters[1] += 1
def _test_delay_job(counters, starttimes):... | identifier_body |
test.py | #!/usr/bin/python2.7
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import time
import unittest
from pycopia import anypath
from pycopia import asyncio
from pycopia import asyncserver
from pycop... |
print ("test delay job 2 at", time.time())
counters[3] += 1
def _test_oneshot(counters, starttimes):
thetime = time.time()
counters[4] += 1
starttimes[4] = thetime
print ("test oneshot at", thetime)
s = pycopia.OS.sequencer.Sequen... | starttimes[3] = time.time() | conditional_block |
test.py | #!/usr/bin/python2.7
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import time
import unittest
from pycopia import anypath
from pycopia import asyncio
from pycopia import asyncserver
from pycop... | pwent = passwd.getpwself()
print(repr(pwent))
print(str(pwent))
print(int(pwent))
print(pwent.name)
print(pwent.home)
print(pwent.uid)
print(pwent[3])
def test_shparser(self):
argv = None
def _check_argv(argv):
self.assertE... | self.assertEqual(ip.address, 0x01010101)
def test_passwd(argv): | random_line_split |
CombDiacritMarks.js | /*
* /MathJax/jax/output/HTML-CSS/fonts/TeX/SansSerif/Regular/CombDiacritMarks.js
* | * Copyright (c) 2009-2015 The MathJax Consortium
*
* 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 appli... | random_line_split | |
projectImporter.ts | import * as Path from 'path'
import * as util from 'util'
import chalk from 'chalk'
import {Rundeck} from 'ts-rundeck'
import {exec} from 'async/child-process'
import * as Tmp from 'async/tmp'
import * as FS from 'async/fs'
export enum KeyType {
Public = 'publicKey',
Private = 'privateKey',
Password = 'p... | (readonly repoPath: string, readonly projectName: string, readonly client: Rundeck) {}
async importProject() {
const dir = await Tmp.dir({prefix: 'demo_projects_'})
const importFileName = Path.join(dir, `${this.projectName}.zip`)
const projectDir = Path.join(this.repoPath, this.projectName... | constructor | identifier_name |
projectImporter.ts | import * as Path from 'path'
import * as util from 'util'
import chalk from 'chalk'
import {Rundeck} from 'ts-rundeck'
import {exec} from 'async/child-process'
import * as Tmp from 'async/tmp'
import * as FS from 'async/fs'
export enum KeyType {
Public = 'publicKey',
Private = 'privateKey',
Password = 'p... |
/**
* Project import
*/
console.log('Importing project...')
await this.client.projectArchiveImport(this.projectName, await FS.readFile(importFileName), {importConfig: true})
// await exec(`rd projects archives import --file ${importFileName} --project ${this.projectNa... | {
console.log('Creating project...')
await this.client.projectCreate({name: this.projectName})
} | conditional_block |
projectImporter.ts | import * as Path from 'path'
import * as util from 'util'
import chalk from 'chalk'
import {Rundeck} from 'ts-rundeck'
import {exec} from 'async/child-process'
import * as Tmp from 'async/tmp'
import * as FS from 'async/fs'
export enum KeyType {
Public = 'publicKey',
Private = 'privateKey',
Password = 'p... | * Key import
*/
// const keyRepoPath = Path.join('projects', this.projectName, 'system/keys')
// if (await FS.exists(keyRepoPath)) {
// console.log('Importing keys...')
// const keyFiles = (await exec(`find projects/${this.projectName}/system/keys -type f`)).std... |
/** | random_line_split |
projectImporter.ts | import * as Path from 'path'
import * as util from 'util'
import chalk from 'chalk'
import {Rundeck} from 'ts-rundeck'
import {exec} from 'async/child-process'
import * as Tmp from 'async/tmp'
import * as FS from 'async/fs'
export enum KeyType {
Public = 'publicKey',
Private = 'privateKey',
Password = 'p... | * Project import
*/
console.log('Importing project...')
await this.client.projectArchiveImport(this.projectName, await FS.readFile(importFileName), {importConfig: true})
// await exec(`rd projects archives import --file ${importFileName} --project ${this.projectName}`)
... | {
const dir = await Tmp.dir({prefix: 'demo_projects_'})
const importFileName = Path.join(dir, `${this.projectName}.zip`)
const projectDir = Path.join(this.repoPath, this.projectName)
console.log('Creating project archive...')
console.log(chalk.blue(this.projectName))
aw... | identifier_body |
plusone.js | // $Id$
// Run the following code when the DOM has been fully loaded.
jQuery(document).ready(function () {
// Attach some code to the click event for the
// link with class "plusone-link".
jQuery('a.plusone-link').click(function () {
// When clicked, first define an anonymous function
// to... | success: voteSaved,
data: 'js=1' // Pass a key/value pair.
});
// Prevent the browser from handling the click.
return false;
});
}); | dataType: 'json', | random_line_split |
fileio.py | #!/usr/bin/env python
# Copyright (C) 2014 Swift Navigation Inc.
# Contact: Gareth McMullin <gareth@swift-nav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" ... | self.link.send(SBP_MSG_FILEIO_WRITE, header + chunk)
reply = self.link.wait(SBP_MSG_FILEIO_WRITE, timeout=1.0)
if not reply:
raise Exception("Timeout waiting for FILEIO_WRITE reply")
if reply != header:
raise Exception("Reply FILEIO_WRITE doesn't match request")
offset += l... | while data:
chunk = data[:chunksize]
data = data[chunksize:]
header = struct.pack("<I", offset) + filename + '\0' | random_line_split |
fileio.py | #!/usr/bin/env python
# Copyright (C) 2014 Swift Navigation Inc.
# Contact: Gareth McMullin <gareth@swift-nav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" ... |
else:
print data
elif args.delete:
f.remove(args.delete[0])
elif args.list is not None:
print_dir_listing(f.readdir(args.list[0]))
else:
print "No command given, listing root directory:"
print_dir_listing(f.readdir())
except Ke... | print hexdump(data) | conditional_block |
fileio.py | #!/usr/bin/env python
# Copyright (C) 2014 Swift Navigation Inc.
# Contact: Gareth McMullin <gareth@swift-nav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" ... | (self, link):
self.link = link
def read(self, filename):
"""
Read the contents of a file.
Parameters
----------
filename : str
Name of the file to read.
Returns
-------
out : str
Contents of the file.
"""
chunksize = 255 - 6 - len(filename)
buf = ''
... | __init__ | identifier_name |
fileio.py | #!/usr/bin/env python
# Copyright (C) 2014 Swift Navigation Inc.
# Contact: Gareth McMullin <gareth@swift-nav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" ... | raise Exception("Timeout waiting for FILEIO_READ reply")
if data[:len(msg)] != msg:
raise Exception("Reply FILEIO_READ doesn't match request")
chunk = data[len(msg):]
buf += chunk
if len(chunk) != chunksize:
return buf
def readdir(self, dirname='.'):
"""
List ... | """
Read the contents of a file.
Parameters
----------
filename : str
Name of the file to read.
Returns
-------
out : str
Contents of the file.
"""
chunksize = 255 - 6 - len(filename)
buf = ''
while True:
msg = struct.pack("<IB", len(buf), chunksize) +... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.