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 |
|---|---|---|---|---|
takeLast.d.ts | import { MonoTypeOperatorFunction } from '../types';
/**
* Emits only the last `count` values emitted by the source Observable.
*
* <span class="informal">Remembers the latest `count` values, then emits those
* only when the source completes.</span>
*
* 
*
* `takeLast` returns an Observable tha... | * whether or not more values will be emitted on the source. For this reason,
* all values are emitted synchronously, followed by the complete notification.
*
* ## Example
* Take the last 3 values of an Observable with many values
* ```ts
* import { range } from 'rxjs';
* import { takeLast } from 'rxjs/operators... | * values then all of its values are emitted. This operator must wait until the
* `complete` notification emission from the source in order to emit the `next`
* values on the output Observable, because otherwise it is impossible to know | random_line_split |
outline.ts | /*
* oultine.ts
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This prog... |
// add the outline node
top().children.push(outlineItem);
// make it the the active container if it's a heading
if (outlineItem.type === 'heading') {
containers.push(outlineItem);
}
});
// return children of root
return rootOutlineItem.children;
}
function hasOutlineIdsTransaction(t... | {
containers.pop();
} | conditional_block |
outline.ts | /*
* oultine.ts
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This prog... |
export default extension;
| {
return plugin.getState(state)!;
} | identifier_body |
outline.ts | /*
* oultine.ts
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This prog... | name: 'outline',
filter: hasOutlineIdsTransaction,
nodeFilter: isOutlineNode,
append: (tr: Transaction) => {
const usedIds = new Set<string>();
const needsOutlineId = (node: ProsemirrorNode) => {
if (isOutlineNode(node)) {
if (node.attrs.navi... | appendTransaction: (schema: Schema) => {
return [
{ | random_line_split |
outline.ts | /*
* oultine.ts
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This prog... | (transactions: Transaction[], oldState: EditorState, newState: EditorState) {
return (
transactions.some(tr => tr.getMeta(kSetMarkdownTransaction)) ||
hasOutlineIdsTransaction(transactions) ||
transactionsHaveChange(transactions, oldState, newState, isOutlineNode)
);
}
export function getOutline(state:... | transactionsAffectOutline | identifier_name |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... | else {
cx.span_err(sp, "#[dom_struct] applied to something other than a struct");
anno
}
}
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do n... | {
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for internal usage
item2.attrs.push(quote_... | conditional_block |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... |
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do not
/// implement the method.
pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &A... | {
if let Annotatable::Item(item) = anno {
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for in... | identifier_body |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... |
for &FieldInfo { ref self_, span, .. } in fields {
stmts.push(call_trace(span, self_.clone()));
}
cx.expr_block(cx.block(trait_span, stmts, None))
} | Struct(ref fs) | EnumMatching(_, _, ref fs) => fs,
_ => cx.span_bug(trait_span, "impossible substructure in `jstraceable`")
}; | random_line_split |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... | (cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: ty::Path::new(vec!("dom","bindings","trace","JSTraceable")),
additional_bounds: Vec::ne... | expand_jstraceable | identifier_name |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_s... |
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
}
| {
return Ok(::utils::constants::VERKEY.to_string());
} | conditional_block |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_s... | did::create_and_store_my_did(get_wallet_handle(), &my_did_json.to_string())
.wait()
.map_err(VcxError::from)
}
pub fn get_local_verkey(did: &str) -> VcxResult<String> {
if settings::indy_mocks_enabled() {
return Ok(::utils::constants::VERKEY.to_string());
}
did::key_for_local_d... | random_line_split | |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn | (seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_string(), ::utils::constants::VERKEY.to_string()));
}
let my_did_json = json!({"seed": seed, "method_name": method_name});
did::create_and_... | create_and_store_my_did | identifier_name |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_s... | {
if settings::indy_mocks_enabled() {
return Ok(::utils::constants::VERKEY.to_string());
}
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
} | identifier_body | |
setup.py | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-HTMLtoPDF',
version='0.1',
packages=['django_htmlT... | 'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
) | 'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7', | random_line_split |
less.js | if (typeof window !== 'undefined') {
var less = require('npm:less/lib/less-browser/index')(window, window.less || {})
var head = document.getElementsByTagName('head')[0];
// get all injected style tags in the page
var styles = document.getElementsByTagName('style');
var styleIds = [];
for (var ... | }
exports.fetch = function (load) {
// don't reload styles loaded in the head
for (var i = 0; i < styleIds.length; i++)
if (load.address == styleIds[i])
return '';
return loadStyle(load.address);
}
}
else {
exports.translate = function (load) {
... | random_line_split | |
logHelper.ts | import * as appInsights from 'applicationinsights';
export class | {
public static error(id: string, data: any) {
if (!id || !data) {
throw Error('You must provide a id and data');
}
const errorId = `/errors/server/${id}`;
let errorMessage = 'No Data';
if (data && data.message) {
errorMessage = data.message;
} else if (data) {
errorMessage... | LogHelper | identifier_name |
logHelper.ts | import * as appInsights from 'applicationinsights';
export class LogHelper {
public static error(id: string, data: any) {
if (!id || !data) {
throw Error('You must provide a id and data');
}
const errorId = `/errors/server/${id}`;
let errorMessage = 'No Data';
if (data && data.message) {
... |
return client.trackEvent({
name,
properties,
measurements,
});
}
}
| {
console.log(properties);
return;
} | conditional_block |
logHelper.ts | import * as appInsights from 'applicationinsights';
export class LogHelper {
public static error(id: string, data: any) {
if (!id || !data) {
throw Error('You must provide a id and data');
}
const errorId = `/errors/server/${id}`;
let errorMessage = 'No Data';
if (data && data.message) {
... | }
public static warn(id: string, data: any) {
if (!id || !data) {
throw Error('You must provide a id and data');
}
const warningId = `/warnings/server/${id}`;
LogHelper.trackEvent(warningId, data);
}
public static log(id: string, data: any) {
if (!id || !data) {
throw Error('... | } else if (data) {
errorMessage = JSON.stringify(data);
}
LogHelper.trackEvent(errorId, { error: errorMessage }); | random_line_split |
customformlayout.tsx | import React, { useState } from 'react';
import { AutoFields, ColorPickerField } from '@react-page/editor';
// The editor core
import type { Value, CellPlugin } from '@react-page/editor';
import Editor, { createValue } from '@react-page/editor';
| // import '@react-page/editor/lib/index.css';
// The rich text area plugin
import slate from '@react-page/plugins-slate';
import PageLayout from '../../components/PageLayout';
const customContentPluginWithSpecialForm: CellPlugin<{
firstName: string;
lastName: string;
street: string;
zip: string;
city: stri... | // import the main css, uncomment this: (this is commented in the example because of https://github.com/vercel/next.js/issues/19717) | random_line_split |
movie.search.result.list.ts | import {Component, Input} from "@angular/core";
import {MovieSearchResult} from "./movie.search.strategy";
@Component({
selector: 'movie-search-result-list',
template: `
<div *ngIf="items == null" class="inset-base">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
</div>
... | export class MovieSearchResultList {
@Input() items: MovieSearchResult[];
} | }) | random_line_split |
movie.search.result.list.ts | import {Component, Input} from "@angular/core";
import {MovieSearchResult} from "./movie.search.strategy";
@Component({
selector: 'movie-search-result-list',
template: `
<div *ngIf="items == null" class="inset-base">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
</div>
... | {
@Input() items: MovieSearchResult[];
} | MovieSearchResultList | identifier_name |
OneRMEditSetFormScreen.js | import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import SetForm from 'app/shared_features/set_card/expanded/SetForm';
import * as Actions from './OneRMEditSetFormActions';
import * as DateUtils from 'app/utility/DateUtils';
const mapStateToProps = (state, ownProps) => {
const rpe... | mapStateToProps,
mapDispatchToProps
)(SetForm);
export default OneRMEditSetFormScreen; | random_line_split | |
index.d.ts | // Type definitions for extra-watch-webpack-plugin 1.0
// Project: https://github.com/pigcan/extra-watch-webpack-plugin#readme
// Definitions by: Dave Cardwell <https://github.com/davecardwell>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.7
import { Plugin } from "webpack... | }
declare namespace ExtraWatchWebpackPlugin {
interface Options {
/**
* (absolute path or glob pattern), attach extra files to webpack's watch system
* @default []
*/
files?: string | ReadonlyArray<string> | undefined;
/**
* attach extra dirs to webpack's... | cwd: string;
files: string[];
dirs: string[];
};
constructor(options?: ExtraWatchWebpackPlugin.Options); | random_line_split |
index.d.ts | // Type definitions for extra-watch-webpack-plugin 1.0
// Project: https://github.com/pigcan/extra-watch-webpack-plugin#readme
// Definitions by: Dave Cardwell <https://github.com/davecardwell>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.7
import { Plugin } from "webpack... | extends Plugin {
static defaults: {
cwd: string;
files: string[];
dirs: string[];
};
constructor(options?: ExtraWatchWebpackPlugin.Options);
}
declare namespace ExtraWatchWebpackPlugin {
interface Options {
/**
* (absolute path or glob pattern), attach extra fi... | ExtraWatchWebpackPlugin | identifier_name |
text_io_xml.py | bl_info = {
"name" : "text objects to-from xml",
"author" : "chebhou",
"version" : (1, 0),
"blender" : (2, 7, 3),
"location" : "file->export->text to-from xml",
"discription" : "copys an text objectx from-to xml file",
"wiki_url" : " https://github.com/chebhou",
"tracker_url" : "https://... |
class text_export(Operator, ExportHelper):
"""write and read text objects to a file"""
bl_idname = "export_scene.text_xml"
bl_label = "text from-to xml"
bl_options = {'REGISTER', 'UNDO'} #should remove undo ?
# ExportHelper mixin class uses this
filename_ex... | random_line_split | |
text_io_xml.py | bl_info = {
"name" : "text objects to-from xml",
"author" : "chebhou",
"version" : (1, 0),
"blender" : (2, 7, 3),
"location" : "file->export->text to-from xml",
"discription" : "copys an text objectx from-to xml file",
"wiki_url" : " https://github.com/chebhou",
"tracker_url" : "https://... | register() | conditional_block | |
text_io_xml.py | bl_info = {
"name" : "text objects to-from xml",
"author" : "chebhou",
"version" : (1, 0),
"blender" : (2, 7, 3),
"location" : "file->export->text to-from xml",
"discription" : "copys an text objectx from-to xml file",
"wiki_url" : " https://github.com/chebhou",
"tracker_url" : "https://... | if self.convert == 'W':
txt_export(self.filepath)
else:
txt_sync(self.filepath)
bpy.context.scene.update()
self.report({'INFO'},"Conversion is Done")
return {'FINISHED'}
def menu_func_export(self, context):
self.layout.operato... | """write and read text objects to a file"""
bl_idname = "export_scene.text_xml"
bl_label = "text from-to xml"
bl_options = {'REGISTER', 'UNDO'} #should remove undo ?
# ExportHelper mixin class uses this
filename_ext = ".xml"
#parameters and variables
convert ... | identifier_body |
text_io_xml.py | bl_info = {
"name" : "text objects to-from xml",
"author" : "chebhou",
"version" : (1, 0),
"blender" : (2, 7, 3),
"location" : "file->export->text to-from xml",
"discription" : "copys an text objectx from-to xml file",
"wiki_url" : " https://github.com/chebhou",
"tracker_url" : "https://... | (filepath):
dom = minidom.parse(filepath)
scenes =dom.getElementsByTagName('scene')
for scene in scenes:
scene_name=scene.getAttribute('name')
print("\n",scene_name)
bl_scene = bpy.data.scenes[scene_name]
txt_objs =scene.getElementsByTagName('object')
for obj in txt_o... | txt_sync | identifier_name |
rents.js | 'use strict';
angular.module('dashboardApp')
.controller('RentsCtrl', function ($scope, Rents, $location, $routeParams, Auth, rents) {
$scope.rents = rents;
$scope.returnBook = function(rent){ | });
};
$scope.getStyle = function(rent){
if (rent.rent && (new Date(rent.rent.endDate) < new Date() && !rent.rent.returnDate)) {
return 'warning';
}
};
$scope.query = function(){
if (!$scope.mayQuery) {
return false;
}
var query = {page: $scope.page + 1};
query = angul... | Rents.returnBook({'rentId': rent.rentId}, function(res){
console.log(res);
rent.status = res.status;
rent.rent.returnDate = res.rent.returnDate; | random_line_split |
rents.js | 'use strict';
angular.module('dashboardApp')
.controller('RentsCtrl', function ($scope, Rents, $location, $routeParams, Auth, rents) {
$scope.rents = rents;
$scope.returnBook = function(rent){
Rents.returnBook({'rentId': rent.rentId}, function(res){
console.log(res);
rent.status = res.status;
... |
};
$scope.query = function(){
if (!$scope.mayQuery) {
return false;
}
var query = {page: $scope.page + 1};
query = angular.extend(query, $routeParams, {user: Auth.getUser().userId});
console.log(query);
Rents.query(query,
function(rents){
if (!rents.length) {
... | {
return 'warning';
} | conditional_block |
test_common.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
macro_rules! test {
($name: expr, $skip: expr) => {
::json_tests::test_common::run_test_path(::std::path::Path::new(concat!("res/ethereum/tests/", $name)), &$skip, do_json_test);
}
}
#[macro_export]
macro_rules! declare_test {
(skip => $arr: expr, $id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case... | {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
} | identifier_body |
test_common.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | }) {
run_test_path(&p, skip, runner)
}
} else {
let mut path = p.to_path_buf();
path.set_extension("json");
run_test_file(&path, runner)
}
}
pub fn run_test_file(path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>) {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening... | {
Some(e.path())
} | conditional_block |
test_common.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | }
} | random_line_split | |
test_common.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>) {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
}
macro... | run_test_file | identifier_name |
teller.detail.component.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* 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... |
isClosed$: Observable<boolean>;
constructor(private store: OfficesStore) {}
ngOnInit(): void {
this.teller$ = this.store.select(fromOffices.getSelectedTeller)
.filter(teller => !!teller);
this.isClosed$ = this.teller$
.map(teller => teller.state === 'CLOSED');
}
} | templateUrl: './teller.detail.component.html'
})
export class OfficeTellerDetailComponent implements OnInit {
teller$: Observable<Teller>; | random_line_split |
teller.detail.component.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* 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... | (): void {
this.teller$ = this.store.select(fromOffices.getSelectedTeller)
.filter(teller => !!teller);
this.isClosed$ = this.teller$
.map(teller => teller.state === 'CLOSED');
}
}
| ngOnInit | identifier_name |
extern-types-pointer-cast.rs | // Copyright 2017 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 ... | assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
} | fn main() {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC); | random_line_split |
extern-types-pointer-cast.rs | // Copyright 2017 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 ... | {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
} | identifier_body | |
extern-types-pointer-cast.rs | // Copyright 2017 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 ... | () {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
}
| main | identifier_name |
test_server_external_events.py | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | self.assertRaises(webob.exc.HTTPBadRequest,
self.api.create, req, body)
def test_create_bad_events(self):
body = {'events': 'foo'}
req = self._create_req(body)
self.assertRaises(webob.exc.HTTPBadRequest,
self.api.create, req, body)... | req = self._create_req(body) | random_line_split |
test_server_external_events.py | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
self.assertEqual([], expected_events)
return result, code
def test_create(self):
req = self._create_req(self.default_body)
result, code = self._assert_call(req, self.default_body,
fake_instance_uuids[:2],
... | expected_events.remove(event.name) | conditional_block |
test_server_external_events.py | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
def test_create_event_instance_has_no_host(self):
body = self.default_body
body['events'][0]['server_uuid'] = fake_instance_uuids[-1]
req = self._create_req(body)
# the instance without host should not be passed to the compute layer
result, code = self._assert_call(req, bod... | body = self.default_body
body['events'][1]['server_uuid'] = MISSING_UUID
req = self._create_req(body)
result, code = self._assert_call(req, body, [fake_instance_uuids[0]],
['network-vif-plugged'])
self.assertEqual('failed', result['events'][1]['st... | identifier_body |
test_server_external_events.py | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (cls, context, uuid):
try:
return fake_instances[uuid]
except KeyError:
raise exception.InstanceNotFound(instance_id=uuid)
@mock.patch('nova.objects.instance.Instance.get_by_uuid', fake_get_by_uuid)
class ServerExternalEventsTest(test.NoDBTestCase):
def setUp(self):
super(ServerExt... | fake_get_by_uuid | identifier_name |
receiver.ts | import {Message} from "protocol/message"
import {isString} from "core/util/types"
import {assert} from "core/util/assert"
export type Fragment = string | ArrayBuffer
export class Receiver {
message: Message<unknown> | null = null
protected _partial: Message<unknown> | null = null
protected _fragments: [string... |
_BUFFER_PAYLOAD(fragment: Fragment): void {
this._assume_binary(fragment)
assert(this._partial != null && this._buf_header != null)
this._partial.assemble_buffer(this._buf_header, fragment)
this._check_complete()
}
private _assume_text(fragment: Fragment): asserts fragment is string {
if (!i... | this._current_consumer = this._BUFFER_PAYLOAD
} | random_line_split |
receiver.ts | import {Message} from "protocol/message"
import {isString} from "core/util/types"
import {assert} from "core/util/assert"
export type Fragment = string | ArrayBuffer
export class Receiver {
message: Message<unknown> | null = null
protected _partial: Message<unknown> | null = null
protected _fragments: [string... |
_HEADER(fragment: Fragment): void {
this._assume_text(fragment)
this.message = null
this._partial = null
this._fragments = [fragment]
this._buf_header = null
this._current_consumer = this._METADATA
}
_METADATA(fragment: Fragment): void {
this._assume_text(fragment)
this._fragmen... | {
this._current_consumer(fragment)
} | identifier_body |
receiver.ts | import {Message} from "protocol/message"
import {isString} from "core/util/types"
import {assert} from "core/util/assert"
export type Fragment = string | ArrayBuffer
export class Receiver {
message: Message<unknown> | null = null
protected _partial: Message<unknown> | null = null
protected _fragments: [string... | (fragment: Fragment): void {
this._assume_text(fragment)
this._fragments.push(fragment)
this._current_consumer = this._CONTENT
}
_CONTENT(fragment: Fragment): void {
this._assume_text(fragment)
this._fragments.push(fragment)
const [header_json, metadata_json, content_json] = this._fragments... | _METADATA | identifier_name |
Classfluid.ts | import { AchievementType, AchievementRewardType, Stat, Achievement } from '../../../../shared/interfaces';
import { Player } from '../../../../shared/models';
import * as Professions from '../professions';
export class Classfluid extends Achievement {
static readonly statWatches = ['Character/ProfessionChanges'];
... | [Stat.STR]: 1.1,
[Stat.DEX]: 1.1,
[Stat.CON]: 1.1,
[Stat.INT]: 1.1,
[Stat.AGI]: 1.1,
[Stat.LUK]: 1.1
} }
];
return baseRewards;
}
} | static rewardsForTier(): any[] {
const baseRewards: any[] = [
{ type: AchievementRewardType.StatMultipliers, stats: { | random_line_split |
Classfluid.ts | import { AchievementType, AchievementRewardType, Stat, Achievement } from '../../../../shared/interfaces';
import { Player } from '../../../../shared/models';
import * as Professions from '../professions';
export class Classfluid extends Achievement {
static readonly statWatches = ['Character/ProfessionChanges'];
... | (): any[] {
const baseRewards: any[] = [
{ type: AchievementRewardType.StatMultipliers, stats: {
[Stat.STR]: 1.1,
[Stat.DEX]: 1.1,
[Stat.CON]: 1.1,
[Stat.INT]: 1.1,
[Stat.AGI]: 1.1,
[Stat.LUK]: 1.1
} }
];
return baseRewards;
}
}
| rewardsForTier | identifier_name |
Classfluid.ts | import { AchievementType, AchievementRewardType, Stat, Achievement } from '../../../../shared/interfaces';
import { Player } from '../../../../shared/models';
import * as Professions from '../professions';
export class Classfluid extends Achievement {
static readonly statWatches = ['Character/ProfessionChanges'];
... |
static rewardsForTier(): any[] {
const baseRewards: any[] = [
{ type: AchievementRewardType.StatMultipliers, stats: {
[Stat.STR]: 1.1,
[Stat.DEX]: 1.1,
[Stat.CON]: 1.1,
[Stat.INT]: 1.1,
[Stat.AGI]: 1.1,
[Stat.LUK]: 1.1
} }
];
return baseReward... | {
const uniqueClasses = player.$statistics.getChildrenCount('Profession');
return uniqueClasses === Object.keys(Professions).length ? 1 : 0;
} | identifier_body |
Chariot.js | var Chariot = function ( $core, $control ) {
var self = require( "/globHammer/core/rock/RockContent" )( $core, $control );
self.execute = function(){
self.display.position.x = self.core.rock.x;
self.display.position.y = self.core.rock.y;
}
self.clickUp = function(){}
self.show = function ( id ){
tr... |
//trace( self.core.glob.soulLayer.contains( self.display));
//self.core.glob.soulLayer.removeChild( self.display);
}
self.buildToon = function( toon ){
var max;
if ( toon.src != null ) max = toon.src.length;
if ( toon.frames != null ) max = toon.frames.length;
var textureList = [];
//PWEEZE REMOVE... | random_line_split | |
Chariot.js |
var Chariot = function ( $core, $control ) {
var self = require( "/globHammer/core/rock/RockContent" )( $core, $control );
self.execute = function(){
self.display.position.x = self.core.rock.x;
self.display.position.y = self.core.rock.y;
}
self.clickUp = function(){}
self.show = function ( id ){
t... | ;
//here is perhaps where the lanscape should go
self.display.addChild( display );
}
self.toons = {};
return self;
};
exports = module.exports = Chariot; | {
display.loop = false;
display.onComplete = function() {
var soul = self.core.soul;
if ( toon.end != null ) soul[ toon.end ]();
};
} | conditional_block |
test_disconnect_host_volume_create_negative1.py | import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
volume = None
disconnect = False
host = None
def test():
| except:
test_util.test_logger("host: [%s] is disconnected" % host.uuid)
disconnect = True
# create_volume on 2 clusters
ps = res_ops.query_resource(res_ops.PRIMARY_STORAGE)[0]
systemtags1 = ["volumeProvisioningStrategy::ThickProvisioning", "capability::virtio-scsi",
"mini... | global disconnect, volume, host
# query&get clusters
cond = res_ops.gen_query_conditions('name', '=', "cluster1")
cluster1 = res_ops.query_resource(res_ops.CLUSTER, cond)[0]
cond = res_ops.gen_query_conditions('name', '=', "cluster2")
cluster2 = res_ops.query_resource(res_ops.CLUSTER, cond)[0]
... | identifier_body |
test_disconnect_host_volume_create_negative1.py | import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
volume = None
disconnect = False
host = None
def test():
global disconnec... | ():
global host, disconnect
if disconnect:
host_ops.update_kvm_host(host.uuid, 'username', "root")
host_ops.reconnect_host(host.uuid)
disconnect = False
| env_recover | identifier_name |
test_disconnect_host_volume_create_negative1.py | import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
volume = None
disconnect = False
host = None
def test():
global disconnec... |
def env_recover():
global host, disconnect
if disconnect:
host_ops.update_kvm_host(host.uuid, 'username', "root")
host_ops.reconnect_host(host.uuid)
disconnect = False
| host_ops.update_kvm_host(host.uuid, 'username', "root")
host_ops.reconnect_host(host.uuid)
disconnect = False | conditional_block |
test_disconnect_host_volume_create_negative1.py | import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
volume = None
disconnect = False
host = None
def test():
global disconnec... |
def error_cleanup():
global host, disconnect
if disconnect:
host_ops.update_kvm_host(host.uuid, 'username', "root")
host_ops.reconnect_host(host.uuid)
disconnect = False
def env_recover():
global host, disconnect
if disconnect:
host_ops.update_kvm_host(host.uuid, 'user... | host_ops.reconnect_host(host.uuid)
print e.message.encode("utf-8")
| random_line_split |
test-zlib-zero-byte.js | // Copyright Joyent, Inc. and other Node contributors.
//
// 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,... | t.plan(2);
var gz = zlib.Gzip()
var emptyBuffer = new Buffer(0);
var received = 0;
gz.on('data', function(c) {
received += c.length;
});
gz.on('end', function() {
t.equal(received, 20);
});
gz.on('finish', function() {
t.ok(true);
});
gz.write(emptyBuffer);
gz.end();
}... |
tape('zero byte', function(t) {
| random_line_split |
app.component.ts | import { AfterContentInit, Component, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { views } from './app-nav-views';
import { MOBILE } from './services/constants';
import { MatSidenav } from '@angular/material';
import {environment} from '../envir... | (event) {
if (!environment.production) {
console.log('Activate Event:', event);
}
}
deactivateEvent (event) {
if (!environment.production) {
console.log('Deactivate Event', event);
}
}
}
| activateEvent | identifier_name |
app.component.ts | import { AfterContentInit, Component, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { views } from './app-nav-views';
import { MOBILE } from './services/constants';
import { MatSidenav } from '@angular/material';
import {environment} from '../envir... |
activateEvent (event) {
if (!environment.production) {
console.log('Activate Event:', event);
}
}
deactivateEvent (event) {
if (!environment.production) {
console.log('Deactivate Event', event);
}
}
}
| {
this.sidenav.open();
} | identifier_body |
app.component.ts | import { AfterContentInit, Component, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { views } from './app-nav-views';
import { MOBILE } from './services/constants';
import { MatSidenav } from '@angular/material';
import {environment} from '../envir... |
}
deactivateEvent (event) {
if (!environment.production) {
console.log('Deactivate Event', event);
}
}
}
| {
console.log('Activate Event:', event);
} | conditional_block |
app.component.ts | import { AfterContentInit, Component, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { views } from './app-nav-views';
import { MOBILE } from './services/constants';
import { MatSidenav } from '@angular/material';
import {environment} from '../envir... |
deactivateEvent (event) {
if (!environment.production) {
console.log('Deactivate Event', event);
}
}
} | if (!environment.production) {
console.log('Activate Event:', event);
}
} | random_line_split |
upload.py | # -*- coding: utf-8 -*-
from plone import api
from plone.app.mosaic import _
from zope.publisher.browser import BrowserView
import json
class MosaicUploadView(BrowserView):
"""Handle file uploads"""
def __call__(self):
context = self.context
request = self.request
# Set header to js... | and getattr(context, newid, None) is None:
return newid
count += 1 | random_line_split | |
upload.py | # -*- coding: utf-8 -*-
from plone import api
from plone.app.mosaic import _
from zope.publisher.browser import BrowserView
import json
class MosaicUploadView(BrowserView):
"""Handle file uploads"""
def __call__(self):
context = self.context
request = self.request
# Set header to js... | (self, name):
"""Generate a unique id which doesn't match the system generated ids"""
context = self.context
id = ''
name = name.replace('\\', '/') # Fixup Windows filenames
name = name.split('/')[-1] # Throw away any path part.
for c in name:
if c.isalnum(... | cleanupFilename | identifier_name |
upload.py | # -*- coding: utf-8 -*-
from plone import api
from plone.app.mosaic import _
from zope.publisher.browser import BrowserView
import json
class MosaicUploadView(BrowserView):
"""Handle file uploads"""
def __call__(self):
context = self.context
request = self.request
# Set header to js... | sc = str(count)
newid = "copy{0:s}_of_{1:s}".format(sc, id)
if context.check_id(newid) is None \
and getattr(context, newid, None) is None:
return newid
count += 1
| """Generate a unique id which doesn't match the system generated ids"""
context = self.context
id = ''
name = name.replace('\\', '/') # Fixup Windows filenames
name = name.split('/')[-1] # Throw away any path part.
for c in name:
if c.isalnum() or c in '._':
... | identifier_body |
upload.py | # -*- coding: utf-8 -*-
from plone import api
from plone.app.mosaic import _
from zope.publisher.browser import BrowserView
import json
class MosaicUploadView(BrowserView):
"""Handle file uploads"""
def __call__(self):
context = self.context
request = self.request
# Set header to js... |
# 2) check if the current user has permissions to add stuff
if not context.portal_membership.checkPermission('Add portal content',
context):
error = {}
error['status'] = 1
error['message'] =\
_... | error = {}
error['status'] = 1
error['message'] =\
_(u"Not allowed to upload a file of this type to this folder")
return json.dumps(error) | conditional_block |
num.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/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates t... | (value: T) -> Option<Finite<T>> {
if value.is_finite() {
Some(Finite(value))
} else {
None
}
}
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestrict... | new | identifier_name |
num.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/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates t... | type Target = T;
fn deref(&self) -> &T {
let &Finite(ref value) = self;
value
}
} |
impl<T: Float> Deref for Finite<T> { | random_line_split |
num.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/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates t... | else {
None
}
}
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestricted value.");
Finite(value)
}
}
impl<T: Float> Deref for Finite<T> {
type Target = T;
... | {
Some(Finite(value))
} | conditional_block |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | header["msg_type"] = JsonValue::String(msg_type.to_owned());
header["username"] = JsonValue::String("kernel".to_owned());
header["msg_id"] = JsonValue::String(Uuid::new_v4().to_string());
header["date"] = JsonValue::String(Utc::now().to_rfc3339());
JupyterMessage {
z... |
// Creates a new child message of this message. ZMQ identities are not transferred.
pub(crate) fn new_message(&self, msg_type: &str) -> JupyterMessage {
let mut header = self.header.clone(); | random_line_split |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
fn from_raw_message(raw_message: RawMessage) -> Result<JupyterMessage> {
fn message_to_json(message: &[u8]) -> Result<JsonValue> {
Ok(json::parse(std::str::from_utf8(message)?)?)
}
if raw_message.jparts.len() < 4 {
bail!("Insufficient message parts {}", raw_message... | {
Self::from_raw_message(RawMessage::read(connection)?)
} | identifier_body |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | else {
String::new()
};
let mut parts: Vec<&[u8]> = Vec::new();
for part in &self.zmq_identities {
parts.push(part);
}
parts.push(DELIMITER);
parts.push(hmac.as_bytes());
for part in &self.jparts {
parts.push(part);
}
... | {
let mut mac = mac_template.clone();
self.digest(&mut mac);
hex::encode(mac.finalize().into_bytes().as_slice())
} | conditional_block |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (connection: &Connection) -> Result<RawMessage> {
Self::from_multipart(connection.socket.recv_multipart(0)?, connection)
}
pub(crate) fn from_multipart(
mut multipart: Vec<Vec<u8>>,
connection: &Connection,
) -> Result<RawMessage> {
let delimiter_index = multipart
... | read | identifier_name |
my_mainwindow.py | __author__ = 'PaleNeutron'
import os
from urllib.parse import urlparse, unquote
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class MyMainWindow(QtWidgets.QMainWindow):
file_loaded = QtCore.pyqtSignal(str)
image_loaded = QtCore.pyqtSignal(QtGui.QImage)
def __init__(self):
su... | (self, file_path):
self.file_loaded.emit(file_path)
# def image_loaded(self, file_path):
# with open(file_path, "b") as f:
# r = f.read()
# with open("images/cover.jpg", "wb") as f:
# f.write(r)
# def epub_loaded(self, file_path):
# self.epub_path ... | load_file | identifier_name |
my_mainwindow.py | __author__ = 'PaleNeutron'
import os
from urllib.parse import urlparse, unquote
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class MyMainWindow(QtWidgets.QMainWindow):
file_loaded = QtCore.pyqtSignal(str)
image_loaded = QtCore.pyqtSignal(QtGui.QImage)
def __init__(self):
su... |
# def image_loaded(self, file_path):
# with open(file_path, "b") as f:
# r = f.read()
# with open("images/cover.jpg", "wb") as f:
# f.write(r)
# def epub_loaded(self, file_path):
# self.epub_path = file_path
# self.file_loaded.emit(False, )
def... | self.file_loaded.emit(file_path) | identifier_body |
my_mainwindow.py | __author__ = 'PaleNeutron'
import os
from urllib.parse import urlparse, unquote
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class MyMainWindow(QtWidgets.QMainWindow):
file_loaded = QtCore.pyqtSignal(str)
image_loaded = QtCore.pyqtSignal(QtGui.QImage)
def __init__(self):
su... |
return path
def dropEvent(self, ev):
# formats = ev.mimeData().formats()
# for i in formats:
# print(i)
# if ev.mimeData().hasFormat(self.win_file_mime):
# ev.accept()
# file_path = bytes(ev.mimeData().data(self.win_file_mime).data())[:-2].decode('u... | path = None | conditional_block |
my_mainwindow.py | __author__ = 'PaleNeutron'
import os
from urllib.parse import urlparse, unquote
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class MyMainWindow(QtWidgets.QMainWindow):
file_loaded = QtCore.pyqtSignal(str)
image_loaded = QtCore.pyqtSignal(QtGui.QImage)
def __init__(self):
| self.windowList = []
self.text_path = ''
self.epub_path = ''
self.win_file_mime = "application/x-qt-windows-mime;value=\"FileNameW\""
self.text_uri_mime = "text/uri-list"
self.create_content_browser()
def create_content_browser(self):
self.content_bro... | super(MyMainWindow, self).__init__()
| random_line_split |
json_port.rs | // see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteo... | try!(encoder.encode_term(response));
try!(encoder.flush());
}
// response packet size
let out_packet_size = wrtr.len() as u16;
try!(w.write_u16::<BigEndian>(out_packet_size));
// response term itself
try!(w.write_all... | {
// encode response term
let mut encoder = erl_ext::Encoder::new(&mut wrtr,
true, true, true);
try!(encoder.write_prelude()); | random_line_split |
json_port.rs | // see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteo... |
fn read_write_loop<R: io::Read, W: io::Write>(mut r: R, mut w: W) -> Result<(), Error> {
loop {
// {packet, 2}
let _in_packet_size = r.read_u16::<BigEndian>();
{
let mut decoder = erl_ext::Decoder::new(&mut r);
assert!(true == try!(decoder.read_prelude()));
... | {
let in_f = io::stdin();
let out_f = io::stdout();
match read_write_loop(in_f, out_f) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: '{}'", err),
Ok(()) => () // unreachable in this example
};
} | identifier_body |
json_port.rs | // see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteo... | (json_bytes: Vec<u8>) -> erl_ext::Eterm {
// Vec<u8> to utf-8 String
let json_string = match String::from_utf8(json_bytes) {
Ok(s) => s,
Err(_) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("bad_utf8"))))
... | bytes_to_json | identifier_name |
index.android.ts | import { ImageAssetBase, getRequestedImageSize } from './image-asset-common';
import { path as fsPath, knownFolders } from '../file-system';
import { ad } from '../utils';
import { Screen } from '../platform';
export * from './image-asset-common';
export class ImageAsset extends ImageAssetBase {
private _android: str... |
}
| {
org.nativescript.widgets.Utils.loadImageAsync(
ad.getApplicationContext(),
this.android,
JSON.stringify(this.options || {}),
Screen.mainScreen.widthPixels,
Screen.mainScreen.heightPixels,
new org.nativescript.widgets.Utils.AsyncImageCallback({
onSuccess(bitmap) {
callback(bitmap, null);
... | identifier_body |
index.android.ts | import { ImageAssetBase, getRequestedImageSize } from './image-asset-common';
import { path as fsPath, knownFolders } from '../file-system';
import { ad } from '../utils';
import { Screen } from '../platform';
export * from './image-asset-common';
export class ImageAsset extends ImageAssetBase { | super();
let fileName = typeof asset === 'string' ? asset.trim() : '';
if (fileName.indexOf('~/') === 0) {
fileName = fsPath.join(knownFolders.currentApp().path, fileName.replace('~/', ''));
}
this.android = fileName;
}
// @ts-ignore
get android(): string {
return this._android;
}
set android(valu... | private _android: string; //file name of the image
constructor(asset: string) { | random_line_split |
index.android.ts | import { ImageAssetBase, getRequestedImageSize } from './image-asset-common';
import { path as fsPath, knownFolders } from '../file-system';
import { ad } from '../utils';
import { Screen } from '../platform';
export * from './image-asset-common';
export class ImageAsset extends ImageAssetBase {
private _android: str... | (ex) {
callback(null, ex);
},
})
);
}
}
| onError | identifier_name |
index.android.ts | import { ImageAssetBase, getRequestedImageSize } from './image-asset-common';
import { path as fsPath, knownFolders } from '../file-system';
import { ad } from '../utils';
import { Screen } from '../platform';
export * from './image-asset-common';
export class ImageAsset extends ImageAssetBase {
private _android: str... |
this.android = fileName;
}
// @ts-ignore
get android(): string {
return this._android;
}
set android(value: string) {
this._android = value;
}
public getImageAsync(callback: (image, error) => void) {
org.nativescript.widgets.Utils.loadImageAsync(
ad.getApplicationContext(),
this.android,
JSO... | {
fileName = fsPath.join(knownFolders.currentApp().path, fileName.replace('~/', ''));
} | conditional_block |
prob1.py | #!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 1
# Convert hex to base64
# Example hex: 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
# Example base64: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
import base64
impo... | print("Failure"); | conditional_block | |
prob1.py | #!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 1
# Convert hex to base64
# Example hex: 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
# Example base64: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
import base64
impo... |
def base64toHex(b64):
'''Convert Base64 string to hex string'''
return rawToHex(base64toRaw(b64));
def hexToBase64(hx):
'''Convert hex string to Base64'''
return rawToBase64(hexToRaw(hx));
def test1():
hx = b'49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f75... | hx = '';
for r in raw:
if type(r) != int:
r = ord(r);
hx += rawToHexLUT[r];
return bytes(hx, 'UTF-8'); | identifier_body |
prob1.py | #!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 1
# Convert hex to base64
# Example hex: 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
# Example base64: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
import base64
impo... | (hx):
'''Convert hex string to Base64'''
return rawToBase64(hexToRaw(hx));
def test1():
hx = b'49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d';
b64 = b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t';
if (base64toHex(b64) !=... | hexToBase64 | identifier_name |
prob1.py | #!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 1
# Convert hex to base64
# Example hex: 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
# Example base64: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
import base64
impo... | hx += rawToHexLUT[r];
return bytes(hx, 'UTF-8');
def base64toHex(b64):
'''Convert Base64 string to hex string'''
return rawToHex(base64toRaw(b64));
def hexToBase64(hx):
'''Convert hex string to Base64'''
return rawToBase64(hexToRaw(hx));
def test1():
hx = b'49276d206b696c6... | r = ord(r);
| random_line_split |
PeriodDeltaChain.js | /** PeriodLister Class */
function PeriodDeltaChain(params) {
this.period_root_id = params.period_root_id;
this.date_format = this.set_or_default(params.date_format, '');
this.set_due_date(params.due_date);
this.period_class = this.set_or_default(params.period_class, 'period');
}
PeriodDeltaChain.prototype.re... | else {
jQuery(period_selector + ' a').show();
}
}
PeriodDeltaChain.prototype.set_due_date = function(new_due_date) {
delete this.due_date;
this.due_date = convert_date(new_due_date);
}
PeriodDeltaChain.prototype.set_or_default = function(value, default_value) {
if (typeof value == 'undefined') {
retu... | {
jQuery(period_selector + ' a').hide();
} | conditional_block |
PeriodDeltaChain.js | /** PeriodLister Class */
function PeriodDeltaChain(params) {
this.period_root_id = params.period_root_id;
this.date_format = this.set_or_default(params.date_format, '');
this.set_due_date(params.due_date);
this.period_class = this.set_or_default(params.period_class, 'period');
}
PeriodDeltaChain.prototype.re... | {
if (due_date.indexOf(' ') > -1) {
var arr_date = due_date.split(/[ T]/).filter(function (s) {
return s !== '';
});
due_date = arr_date[0] + ' ' + arr_date[1] + ' ' + arr_date[2];
}
return due_date;
} | identifier_body | |
PeriodDeltaChain.js | /** PeriodLister Class */
function | (params) {
this.period_root_id = params.period_root_id;
this.date_format = this.set_or_default(params.date_format, '');
this.set_due_date(params.due_date);
this.period_class = this.set_or_default(params.period_class, 'period');
}
PeriodDeltaChain.prototype.refresh = function() {
var current_time = this.due_d... | PeriodDeltaChain | identifier_name |
PeriodDeltaChain.js | /** PeriodLister Class */
function PeriodDeltaChain(params) {
this.period_root_id = params.period_root_id;
this.date_format = this.set_or_default(params.date_format, '');
this.set_due_date(params.due_date);
this.period_class = this.set_or_default(params.period_class, 'period');
}
PeriodDeltaChain.prototype.re... |
jQuery(from_time_node).html(from_time.format(format));
jQuery(to_time_node).html(to_time.add('hours', hours_value).format(format));
current_time = to_time;
});
if (jQuery(period_selector).length < 2) {
jQuery(period_selector + ' a').hide();
} else {
jQuery(period_selector + ' a').show();
... | var from_time = moment(current_time, me.date_format);
var to_time = moment(current_time, me.date_format); | random_line_split |
test_worker_medium.py | # -*- Mode: Python; test-case-name:flumotion.test.test_worker_worker -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modifi... |
return self.deferredAvatar
def getDeferredLogout(self):
if self.deferredLogout is None:
self.deferredLogout = defer.Deferred()
return self.deferredLogout
def requestAvatar(self, avatarId, keycard, mind, *ifaces):
avatar = TestWorkerAvatar(avatarId, mind)
se... | self.deferredAvatar = defer.Deferred() | conditional_block |
test_worker_medium.py | # -*- Mode: Python; test-case-name:flumotion.test.test_worker_worker -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modifi... |
def requestAvatar(self, avatarId, keycard, mind, *ifaces):
avatar = TestWorkerAvatar(avatarId, mind)
self.getDeferredAvatar().callback(avatar)
return (pb.IPerspective, avatar,
lambda: self.avatarLogout(avatar))
def avatarLogout(self, avatar):
self.debug('worker... | if self.deferredLogout is None:
self.deferredLogout = defer.Deferred()
return self.deferredLogout | identifier_body |
test_worker_medium.py | # -*- Mode: Python; test-case-name:flumotion.test.test_worker_worker -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modifi... | (testsuite.TestCase):
def setUp(self):
self.realm = TestWorkerRealm()
def tearDown(self):
return self.realm.shutdown()
def testConnect(self):
m = medium.WorkerMedium(None)
connectionInfo = self.realm.getConnectionInfo()
connectionInfo.authenticator.avatarId = 'foo'... | TestWorkerMedium | identifier_name |
test_worker_medium.py | # -*- Mode: Python; test-case-name:flumotion.test.test_worker_worker -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modifi... |
class TestWorkerMedium(testsuite.TestCase):
def setUp(self):
self.realm = TestWorkerRealm()
def tearDown(self):
return self.realm.shutdown()
def testConnect(self):
m = medium.WorkerMedium(None)
connectionInfo = self.realm.getConnectionInfo()
connectionInfo.authent... | def avatarLogout(self, avatar):
self.debug('worker logged out: %s', avatar.avatarId)
self.getDeferredLogout().callback(avatar)
| random_line_split |
ebook.py | 176, "I"),
("drm_flags", 180, "I"),
("unknown@184", 184, "I"),
("unknown@188", 188, "I"),
("unknown@192", 192, "H"),
("last_image_record", 194, "H"),
("unknown@196", 196, "I"),
("fcis_record", 200, "I"),
("unknown@204", 204, "I"),
("flis_record", 208, "I"),
("unknown@212", 212, ... | ret = {}
n = 0
if (pos != data.find('EXTH')):
LOG(0, "EXTH header not found where it should be @%d" % pos)
return None
else:
end = pos + calcsize(EXTH_FMT)
(hlen, count) = unpack(EXTH_FMT, data[pos:end])
LOG(4, "pos: %d, EXTH header len: %d, record count: %d" % (
... | identifier_body | |
ebook.py | 84, "I"),
("full_name_len", 88, "I"),
("locale_highbytes", 92, "H"),
("locale_country", 94, "B"),
("locale_language", 95, "B"),
("input_lang", 96, "I"),
("output_lang", 100, "I"),
("format_version", 104, "I"),
("first_image_idx", 108, "I"),
("huff/cdic_record", 112, "I"),
("huff/... | (filename):
import palm
db = palm.Database(filename)
return db
class Book:
def __init__(self, fn):
self.filename = fn
# Set some fields to defaults
self.title = fn
self.author = "??"
self.language = "??"
# Rob Addition: Description
self.descrip... | parse_palmdb | identifier_name |
ebook.py | 84, "I"),
("full_name_len", 88, "I"),
("locale_highbytes", 92, "H"),
("locale_country", 94, "B"),
("locale_language", 95, "B"),
("input_lang", 96, "I"),
("output_lang", 100, "I"),
("format_version", 104, "I"),
("first_image_idx", 108, "I"),
("huff/cdic_record", 112, "I"),
("huff/... | self.title = ' '.join(self.exth['updated title'])
if 'description' in self.exth:
self.description = ' <P> '.join(self.exth['description'])
elif self.type == 'TEXtREAd':
LOG(2, "This is an older MOBI book")
self.rawdata = d
... | (type(self.exth['updated title']) is str)): | random_line_split |
ebook.py | 84, "I"),
("full_name_len", 88, "I"),
("locale_highbytes", 92, "H"),
("locale_country", 94, "B"),
("locale_language", 95, "B"),
("input_lang", 96, "I"),
("output_lang", 100, "I"),
("format_version", 104, "I"),
("first_image_idx", 108, "I"),
("huff/cdic_record", 112, "I"),
("huff/... |
elif self.mobi['locale_country'] in lang:
country = lang[self.mobi['locale_country']]
LOG(2, "Book language is %s (%s)" % (
lang[0][1], country[1]))
self.language = "%s (%s-%s)" % (
lang[0][1],
... | LOG(2, "Book language: %s" % lang[0][1])
self.language = "%s (%s)" % (lang[0][1], lang[0][0]) | conditional_block |
app.js | const fs = require('fs');
const path = require('path');
const EventEmitter = require('events');
const cors = require('cors');
const bodyParser = require('body-parser');
const compression = require('compression');
const cookieParser = require(... | .then((adminPassword) => {
log.info(`[ admin .p12 password ] ${adminPassword}`);
})
.then(() => {
log.info('Creating manager certificate...');
return addDevice({ admin: true, deviceName: 'manager', password: 'manager' });
}... | {
startingQueue = startingQueue
.then(() => {
log.info('No SSL certificates found, generating new ones...');
const result = sslConfig(null, null, true);
log.info(`[ chalPassword ] ${result.chalPassword}`);
log.info(`[ outPassword ] ${re... | conditional_block |
app.js | const fs = require('fs');
const path = require('path');
const EventEmitter = require('events');
const cors = require('cors');
const bodyParser = require('body-parser');
const compression = require('compression');
const cookieParser = require(... | if (status instanceof Error) {
log.error(status);
}
try {
fs.unlinkSync(LOCK_FILE);
} catch (e) {
process.exit(1);
}
process.exit(status || 0);
};
/* istanbul ignore next */
process.on('unhandledRejection', (err) => {
if (err.name === 'ReqlDriverError' &&
e... | };
/* istanbul ignore next */
const clearLock = (status) => { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.