file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... | () -> Result<(), Box<dyn std::error::Error>> {
let profile_name = std::env::var("PROFILE").unwrap();
let output_name = std::env::var("OUTPUT").unwrap();
if profile_name.is_empty() || output_name.is_empty() {
println!("Usage: ./filter_profile.rs <profile in stackcollapse format> <output file>");
... | main | identifier_name |
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... |
const NORMALIZE_ERASING_LATE_BOUND_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::normalize_erasing_late_bound_regions";
if let Some(index) = stack.find(NORMALIZE_ERASING_LATE_BOUND_REGIONS) {
stack = &stack[..index + NORMALIZE_ERASI... | {
stack = &stack[..index + SUBST_AND_NORMALIZE_ERASING_REGIONS.len()];
} | conditional_block |
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... | {
let profile_name = std::env::var("PROFILE").unwrap();
let output_name = std::env::var("OUTPUT").unwrap();
if profile_name.is_empty() || output_name.is_empty() {
println!("Usage: ./filter_profile.rs <profile in stackcollapse format> <output file>");
std::process::exit(1);
}
let prof... | identifier_body | |
undo-item.js | /**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); | *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the Licen... | * you may 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 | random_line_split |
shift-management.component.ts | import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';
import { Shift } from './shift';
import { ShiftService } from './shift.service';
import { CreateShiftDialog } from './create-shift-dialog.component';
import { EditShiftDialog } from './edit-shift-dialog.componen... |
});
var currDateStr = new Date(shift.start_time).toLocaleDateString();
var shiftDateStr = new Date(this.date).toLocaleDateString();
// Insert if we didnt find it and its for the proper Date.
if (inShiftArr === false && currDateStr === shiftDateStr) {
th... | {
inShiftArr = true;
s.updateData(shift.start_time, shift.end_time,
shift.start_location, shift.end_location,
shift.route, shift.driver_id, shift.driver_name, shift.bus_id);
} | conditional_block |
shift-management.component.ts | import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';
import { Shift } from './shift';
import { ShiftService } from './shift.service';
import { CreateShiftDialog } from './create-shift-dialog.component';
import { EditShiftDialog } from './edit-shift-dialog.componen... | () {
let dialogRef = this.dialog.open(CreateShiftDialog);
dialogRef.afterClosed().subscribe(res => {
if(res) {
this.addShift(res[0],res[1],res[2],res[3],res[4],res[5],res[6],res[7],res[8]);
}
});
}
openEditDialog(shift) {
let dialogRef = this.dialog.open(EditShiftDialog, {
... | openCreateNewDialog | identifier_name |
shift-management.component.ts | import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';
import { Shift } from './shift';
import { ShiftService } from './shift.service';
import { CreateShiftDialog } from './create-shift-dialog.component';
import { EditShiftDialog } from './edit-shift-dialog.componen... | export class ShiftManagementComponent implements OnInit {
// Clients local Shift[] array for displaying
shifts: Shift[] = [];
date = new Date().toISOString();
// Listener for all shifts
getShiftsConnection;
selectedOption: string;
constructor(private ShiftService: ShiftService, public dialog: MdDialog... | @Component({
selector: 'shift-management',
templateUrl: './shift-management.component.html',
styleUrls: [ './shift-management.component.css' ]
}) | random_line_split |
setup.py | """ Setup file """
import os
from setuptools import find_packages, setup
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.rst")) as f:
README = f.read()
with open(os.path.join(HERE, "CHANGES.rst")) as f:
CHANGES = f.read()
REQUIREMENTS_TEST = open(os.path.join(HERE, "r... | setup(
name="dynamo3",
version="1.0.0",
description="Python 3 compatible library for DynamoDB",
long_description=README + "\n\n" + CHANGES,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Appro... | conditional_block | |
setup.py | """ Setup file """
import os
from setuptools import find_packages, setup
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.rst")) as f:
README = f.read()
with open(os.path.join(HERE, "CHANGES.rst")) as f:
CHANGES = f.read()
REQUIREMENTS_TEST = open(os.path.join(HERE, "r... | install_requires=REQUIREMENTS,
tests_require=REQUIREMENTS + REQUIREMENTS_TEST,
) | "dynamolocal=dynamo3.testing:DynamoLocalPlugin",
],
},
python_requires=">=3.6", | random_line_split |
BookmarkList-mocha.js | /*global beforeEach, describe, it,*/
/*eslint no-unused-expressions: 0*/
'use strict';
require('./testdom')('<html><body></body></html>');
var expect = require('chai').expect;
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var BookmarkList = require('./../../react/component/Bookma... | expect(item.props.children).to.equal(bookmarks[idx].url));
});
it('passes the tags via the tags attribute to the BookmarkListItem', function() {
items.forEach((item, idx) =>
expect(item.props.tags).to.equal(bookmarks[idx].tags));
});
});
}); | });
it('passes the url as children to the BookmarkListItem', function() {
items.forEach((item, idx) =>
| random_line_split |
agents.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Image Grounded Conversations (IGC) Task.
See https://www.aclweb.org/anthology/I17-1047/ for more details. One must d... |
PathManager.mkdirs(self.get_image_path(opt))
# Make one blank image
image = Image.new('RGB', (100, 100), color=0)
image.save(os.path.join(self.get_image_path(opt), self.blank_image_id), 'JPEG')
# Download the rest
download_multiprocess(urls, self.get_image_path(opt), des... | if i == 0:
fields = row
else:
data = dict(zip(fields, row))
urls.append(data['url'])
ids.append(data['id']) | conditional_block |
agents.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Image Grounded Conversations (IGC) Task.
See https://www.aclweb.org/anthology/I17-1047/ for more details. One must d... | self._download_images(opt)
self.data = []
with PathManager.open(dp, newline='\n') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
fields = []
for i, row in enumerate(reader):
if i == 0:
fields = row
... | ): | random_line_split |
agents.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Image Grounded Conversations (IGC) Task.
See https://www.aclweb.org/anthology/I17-1047/ for more details. One must d... | (self, opt: Opt):
"""
Download available IGC images.
"""
urls = []
ids = []
for dt in ['test', 'val']:
df = os.path.join(self.get_data_path(opt), f'IGC_crowd_{dt}.csv')
with PathManager.open(df, newline='\n') as csv_file:
reader = c... | _download_images | identifier_name |
agents.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Image Grounded Conversations (IGC) Task.
See https://www.aclweb.org/anthology/I17-1047/ for more details. One must d... |
class IGCOneSideTeacher(ABC, IGCTeacher):
"""
Override to only return one side of the conversation.
"""
@classmethod
def add_cmdline_args(
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) -> ParlaiParser:
super().add_cmdline_args(parser, partial_opt=partial_opt)... | shared = super().share()
shared['valid_image_ids'] = self.valid_image_ids
return shared | identifier_body |
fatdb.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... |
}
/// Itarator over inserted pairs of key values.
pub struct FatDBIterator<'db> {
trie_iterator: TrieDBIterator<'db>,
trie: &'db TrieDB<'db>,
}
impl<'db> FatDBIterator<'db> {
/// Creates new iterator.
pub fn new(trie: &'db TrieDB) -> super::Result<Self> {
Ok(FatDBIterator {
trie_iterator: TrieDBIterator::ne... | {
self.raw.get_with(&key.sha3(), query)
} | identifier_body |
fatdb.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... | pub struct FatDB<'db> {
raw: TrieDB<'db>,
}
impl<'db> FatDB<'db> {
/// Create a new trie with the backing database `db` and empty `root`
/// Initialise to the state entailed by the genesis block.
/// This guarantees the trie is built correctly.
pub fn new(db: &'db HashDB, root: &'db H256) -> super::Result<Self> {... |
/// A `Trie` implementation which hashes keys and uses a generic `HashDB` backing database.
/// Additionaly it stores inserted hash-key mappings for later retrieval.
///
/// Use it as a `Trie` or `TrieMut` trait object. | random_line_split |
fatdb.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... | <'a>(&'a self) -> super::Result<Box<TrieIterator<Item = TrieItem> + 'a>> {
FatDBIterator::new(&self.raw).map(|iter| Box::new(iter) as Box<_>)
}
fn root(&self) -> &H256 {
self.raw.root()
}
fn contains(&self, key: &[u8]) -> super::Result<bool> {
self.raw.contains(&key.sha3())
}
fn get_with<'a, 'key, Q: Que... | iter | identifier_name |
suitesParser.ts | import _ from 'lodash'
import path from 'path'
import { Suites } from '../types'
export type NightWatchTestSuite = {
before?: () => void,
beforeEach?: () => void,
after?: () => void,
afterEach?: () => void,
'@tags'?: string[],
'@disabled'?: boolean
} & { [testName: string]: (() => void) }
export type DirN... |
return result
}, {} as Suites)
}
export const parse = parseDirectoryNode
| {
Object.keys(childResult).forEach(childKey => {
result[`${childDir}${path.sep}${childKey}`] = childResult[childKey]
})
} | conditional_block |
suitesParser.ts | import _ from 'lodash'
import path from 'path'
import { Suites } from '../types'
export type NightWatchTestSuite = {
before?: () => void,
beforeEach?: () => void,
after?: () => void,
afterEach?: () => void,
'@tags'?: string[],
'@disabled'?: boolean
} & { [testName: string]: (() => void) }
export type DirN... | * (i.e. two or more words making up a test case sentence)
*/
export const isTestCaseName = (str: string) => /\s/g.test(str)
export const isTestSuite = (obj: object): obj is NightWatchTestSuite => (
_.some(obj, (_v: any, key: string) => isTestCaseName(key))
)
export const getTestNames = (testSuite: NightWatchTestS... |
/**
* Assume any key with a whitespace is a test case | random_line_split |
infogan_eval.py | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | (_):
hparams = infogan_eval_lib.HParams(
FLAGS.checkpoint_dir, FLAGS.eval_dir, FLAGS.noise_samples,
FLAGS.unstructured_noise_dims, FLAGS.continuous_noise_dims,
FLAGS.max_number_of_evaluations,
FLAGS.write_to_disk)
infogan_eval_lib.evaluate(hparams, run_eval_loop=True)
if __name__ == '__mai... | main | identifier_name |
infogan_eval.py | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | tf.disable_v2_behavior()
app.run(main) | conditional_block | |
infogan_eval.py | # coding=utf-8 | # 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES... | # Copyright 2022 The TensorFlow GAN Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
infogan_eval.py | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
if __name__ == '__main__':
tf.disable_v2_behavior()
app.run(main)
| hparams = infogan_eval_lib.HParams(
FLAGS.checkpoint_dir, FLAGS.eval_dir, FLAGS.noise_samples,
FLAGS.unstructured_noise_dims, FLAGS.continuous_noise_dims,
FLAGS.max_number_of_evaluations,
FLAGS.write_to_disk)
infogan_eval_lib.evaluate(hparams, run_eval_loop=True) | identifier_body |
Gruntfile.js | /*
* grunt-fea-build
* https://github.com/bpletzer/FET-build-dep
*
* Copyright (c) 2013 Benedikt Pletzer
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js'... |
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Configuration to be run (and then tested).
fea_build: {
default_options: {
options: {
},
files: {
'tmp/default_options': ['test/fixtures/testing', '... | random_line_split | |
scope.js | "use strict";
var assert = require("assert");
var stringmap = require("stringmap");
var stringset = require("stringset");
var is = require("simple-is");
var fmt = require("simple-fmt");
var error = require("./error");
var UUID = 1;
function Scope(args) {
assert(is.someof(args.kind, ["hoist", "block",... |
if ( hasAlready ) {
if ( kind == 'get' && existingKind == 'set' || kind == 'set' && existingKind == 'get' ) {
// all is fine
//TODO:: do something to allow getter and setter declaration both be in scope.decls
}
else if ( Scope.options.... | {// Special test for "catch-block". Maybe it's not so prettily, but it works
var parentScope = scope.parent;
if ( parentScope && parentScope.kind === "catch-block" ) {
hasAlready = parentScope.decls.has(name)
&& (existingKind = parentScope.decls.get(name... | conditional_block |
scope.js | "use strict";
var assert = require("assert");
var stringmap = require("stringmap");
var stringset = require("stringset");
var is = require("simple-is");
var fmt = require("simple-fmt");
var error = require("./error");
var UUID = 1;
function Scope(args) {
assert(is.someof(args.kind, ["hoist", "block",... | (node) {
return node && node.type === 'ObjectPattern';
}
function isArrayPattern(node) {
return node && node.type === 'ArrayPattern';
}
function isFunction(node) {
var type;
return node && ((type = node.type) === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpr... | isObjectPattern | identifier_name |
scope.js | "use strict";
var assert = require("assert");
var stringmap = require("stringmap");
var stringset = require("stringset");
var is = require("simple-is");
var fmt = require("simple-fmt");
var error = require("./error");
var UUID = 1;
function Scope(args) {
assert(is.someof(args.kind, ["hoist", "block",... |
visit(this);
};
//function __show(__a, scope) {
// __a += " " ;
//
// if( scope ) {
// console.log(__a + " | " + scope.uuid);
//
// if( (scope.children[0] || {}).uuid == scope.uuid ) {
// throw new Error("123")
// }
// scope.children.forEach(__show.bind(null, __a))
// }
//}
//
//Object.ke... | {
if (pre) {
pre(scope);
}
scope.children.forEach(function(childScope) {
visit(childScope);
});
if (post) {
post(scope);
}
} | identifier_body |
scope.js | "use strict";
var assert = require("assert");
var stringmap = require("stringmap");
var stringset = require("stringset");
var is = require("simple-is");
var fmt = require("simple-fmt");
var error = require("./error");
var UUID = 1;
function Scope(args) {
assert(is.someof(args.kind, ["hoist", "block",... | function detect(scope) {
if (scope !== outmost) {
scope.decls.keys().forEach(function(name) {
if (scope.getKind(name) === "let" && !scope.written.has(name)) {
return error(scope.getNode(name).loc.start.line, "{0} is declared as let but never modified so co... |
// detects let variables that are never modified (ignores top-level)
Scope.prototype.detectUnmodifiedLets = function() {
var outmost = this;
| random_line_split |
giraffe.d.ts | // Type definitions for Giraffe
// Project: https://github.com/barc/backbone.giraffe
// Definitions by: Matt McCray <https://github.com/darthapo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../backbone/backbone.d.ts" />
declare namespace Giraffe {
interface GiraffeObject... |
invoke( method:string, ...args:any[] );
dispose(): View<TModel>;
beforeDispose(): View<TModel>;
afterDispose(): View<TModel>;
static detachByElement( el:any, preserve?:boolean ): View<Model>;
static getClosestView<TModel>( el:any ): View<Model>;
static getByCid( cid:string ): View<Model>;... | removeChildren( preserve?:boolean ): View<TModel>;
detach( preserve?:boolean ): View<TModel>;
detachChildren( preserve?:boolean ): View<TModel>; | random_line_split |
giraffe.d.ts | // Type definitions for Giraffe
// Project: https://github.com/barc/backbone.giraffe
// Definitions by: Matt McCray <https://github.com/darthapo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../backbone/backbone.d.ts" />
declare namespace Giraffe {
interface GiraffeObject... | <TModel extends Model> extends View<TModel> {
collection: Collection<TModel>;
modelView: View<TModel>;
modelViewArgs: any[];
modelViewEl: any;
renderOnChange: boolean;
findByModel( model:Model ): View<TModel>;
addOne( model:Model ): View<TModel>;
removeOne( model:Model ... | CollectionView | identifier_name |
getat_func.rs | //! # getat_func
//!
//! Split function which returns only the requested item from the created array.
//!
#[cfg(test)]
#[path = "getat_func_test.rs"]
mod getat_func_test;
use envmnt;
pub(crate) fn invoke(function_args: &Vec<String>) -> Vec<String> | {
if function_args.len() != 3 {
error!(
"split expects only 3 arguments (environment variable name, split by character, index)"
);
}
let env_key = function_args[0].clone();
let split_by = function_args[1].clone();
let index: usize = match function_args[2].parse() {
... | identifier_body | |
getat_func.rs | //! # getat_func
//!
//! Split function which returns only the requested item from the created array.
//!
#[cfg(test)]
#[path = "getat_func_test.rs"]
mod getat_func_test;
use envmnt;
pub(crate) fn invoke(function_args: &Vec<String>) -> Vec<String> {
if function_args.len() != 3 {
error!(
"spli... |
let env_key = function_args[0].clone();
let split_by = function_args[1].clone();
let index: usize = match function_args[2].parse() {
Ok(value) => value,
Err(error) => {
error!("Invalid index value: {}", &error);
return vec![]; // should not get here
}
};
... | random_line_split | |
getat_func.rs | //! # getat_func
//!
//! Split function which returns only the requested item from the created array.
//!
#[cfg(test)]
#[path = "getat_func_test.rs"]
mod getat_func_test;
use envmnt;
pub(crate) fn | (function_args: &Vec<String>) -> Vec<String> {
if function_args.len() != 3 {
error!(
"split expects only 3 arguments (environment variable name, split by character, index)"
);
}
let env_key = function_args[0].clone();
let split_by = function_args[1].clone();
let index: u... | invoke | identifier_name |
timer.rs | // TODO: How can we test this module?
use std::cell::{RefCell, Cell};
use std::fmt;
use std::rc::Rc;
use cpu::irq::{self, IrqClient};
use io::regs::IoReg;
#[derive(Clone, Copy, Debug)]
pub enum Prescaler {
Div1 = 0,
Div64 = 1,
Div256 = 2,
Div1024 = 3,
}
impl Prescaler {
fn new(val: u16) -> Presc... | }
}
/// Returns the number of CPU clocks until this timer triggers an overflow
fn clocks_till_overflow(&self) -> u64 {
match self.val_cycles {
Cycles::Unscaled(cyc) => {
let period = unscale(1 << 16, self.prescaler);
(period - cyc % period)
... | out
} else { unreachable!() }
} | random_line_split |
timer.rs | // TODO: How can we test this module?
use std::cell::{RefCell, Cell};
use std::fmt;
use std::rc::Rc;
use cpu::irq::{self, IrqClient};
use io::regs::IoReg;
#[derive(Clone, Copy, Debug)]
pub enum Prescaler {
Div1 = 0,
Div64 = 1,
Div256 = 2,
Div1024 = 3,
}
impl Prescaler {
fn new(val: u16) -> Presc... | else {
let ctr = timer_states.global_counter.get();
let baseline = timer_states.start_counters[index].get();
let clock_diff = ctr - baseline;
timer_states.start_counters[index].set(ctr);
Cycles::Unscaled(clock_diff)
};
prev_overflowed = time... | {
Cycles::CountUp(prev_overflowed as u64)
} | conditional_block |
timer.rs | // TODO: How can we test this module?
use std::cell::{RefCell, Cell};
use std::fmt;
use std::rc::Rc;
use cpu::irq::{self, IrqClient};
use io::regs::IoReg;
#[derive(Clone, Copy, Debug)]
pub enum Prescaler {
Div1 = 0,
Div64 = 1,
Div256 = 2,
Div1024 = 3,
}
impl Prescaler {
fn | (val: u16) -> Prescaler {
match val {
0 => Prescaler::Div1,
1 => Prescaler::Div64,
2 => Prescaler::Div256,
3 => Prescaler::Div1024,
_ => unreachable!()
}
}
}
bf!(CntReg[u16] {
prescaler: 0:1,
count_up: 2:2,
irq_enable: 6:6,
... | new | identifier_name |
SpotLightHelper.js | /**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
import { Vector3 } from '../math/Vector3.js';
import { Object3D } from '../core/Object3D.js';
import { LineSegments } from '../objects/LineSegments.js';
import { LineBas... | var geometry = new BufferGeometry();
var positions = [
0, 0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, - 1, 0, 1,
0, 0, 0, 0, 1, 1,
0, 0, 0, 0, - 1, 1
];
for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
var p1 = ( i / l ) * Math.PI * 2;
var p2 = ( j / l ) * Math.PI * 2;
positions.push(
... | this.matrixAutoUpdate = false;
this.color = color;
| random_line_split |
SpotLightHelper.js | /**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
import { Vector3 } from '../math/Vector3.js';
import { Object3D } from '../core/Object3D.js';
import { LineSegments } from '../objects/LineSegments.js';
import { LineBas... |
SpotLightHelper.prototype = Object.create( Object3D.prototype );
SpotLightHelper.prototype.constructor = SpotLightHelper;
SpotLightHelper.prototype.dispose = function () {
this.cone.geometry.dispose();
this.cone.material.dispose();
};
SpotLightHelper.prototype.update = function () {
this.light.updateMatrixWor... | {
Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrix = light.matrixWorld;
this.matrixAutoUpdate = false;
this.color = color;
var geometry = new BufferGeometry();
var positions = [
0, 0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, - 1, 0, 1,
0, 0, 0, 0, 1, 1,
0, ... | identifier_body |
SpotLightHelper.js | /**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
import { Vector3 } from '../math/Vector3.js';
import { Object3D } from '../core/Object3D.js';
import { LineSegments } from '../objects/LineSegments.js';
import { LineBas... |
};
export { SpotLightHelper };
| {
this.cone.material.color.copy( this.light.color );
} | conditional_block |
SpotLightHelper.js | /**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
import { Vector3 } from '../math/Vector3.js';
import { Object3D } from '../core/Object3D.js';
import { LineSegments } from '../objects/LineSegments.js';
import { LineBas... | ( light, color ) {
Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrix = light.matrixWorld;
this.matrixAutoUpdate = false;
this.color = color;
var geometry = new BufferGeometry();
var positions = [
0, 0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, - 1, 0, 1,
0, 0, 0... | SpotLightHelper | identifier_name |
debug_result.py | """Graph debug results dumping class."""
import os
import json
import tvm
GRAPH_DUMP_FILE_NAME = '_tvmdbg_graph_dump.json'
class DebugResult(object):
"""Graph debug data module.
Data dump module manage all the debug data formatting.
Output data and input graphs are formatted and dumped to file.
Front... |
def _cleanup_tensors(self):
"""Remove the tensor dump file (graph wont be removed)
"""
for filename in os.listdir(self._dump_path):
if os.path.isfile(filename) and not filename.endswith(".json"):
os.remove(filename)
def get_graph_nodes(self):
"""Ret... | node = self._nodes_list[i]
input_list = []
for input_node in node['inputs']:
input_list.append(self._nodes_list[input_node[0]]['name'])
node['inputs'] = input_list
dtype = str("type: " + self._dtype_list[1][i])
if 'attrs' not in node:
... | conditional_block |
debug_result.py | """Graph debug results dumping class."""
import os
import json
import tvm
GRAPH_DUMP_FILE_NAME = '_tvmdbg_graph_dump.json'
class DebugResult(object):
"""Graph debug data module.
Data dump module manage all the debug data formatting.
Output data and input graphs are formatted and dumped to file.
Front... | (self):
"""Return the nodes dtype list
"""
return self._dtype_list
def dump_output_tensor(self):
"""Dump the outputs to a temporary folder, the tensors are in numpy format
"""
#cleanup existing tensors before dumping
self._cleanup_tensors()
eid = 0
... | get_graph_node_dtypes | identifier_name |
debug_result.py | """Graph debug results dumping class."""
import os
import json
import tvm
GRAPH_DUMP_FILE_NAME = '_tvmdbg_graph_dump.json'
class DebugResult(object):
"""Graph debug data module.
Data dump module manage all the debug data formatting.
Output data and input graphs are formatted and dumped to file.
Front... |
Parameters
----------
graph : json format
json formatted NNVM graph contain list of each node's
name, shape and type.
"""
graph_dump_file_name = GRAPH_DUMP_FILE_NAME
with open(os.path.join(self._dump_path, graph_dump_file_name), 'w') as outfile:
... | with open(os.path.join(self._dump_path, "output_tensors.params"), "wb") as param_f:
param_f.write(save_tensors(output_tensors))
def dump_graph_json(self, graph):
"""Dump json formatted graph. | random_line_split |
debug_result.py | """Graph debug results dumping class."""
import os
import json
import tvm
GRAPH_DUMP_FILE_NAME = '_tvmdbg_graph_dump.json'
class DebugResult(object):
"""Graph debug data module.
Data dump module manage all the debug data formatting.
Output data and input graphs are formatted and dumped to file.
Front... |
def dump_output_tensor(self):
"""Dump the outputs to a temporary folder, the tensors are in numpy format
"""
#cleanup existing tensors before dumping
self._cleanup_tensors()
eid = 0
order = 0
output_tensors = {}
for node, time in zip(self._nodes_list... | """Return the nodes dtype list
"""
return self._dtype_list | identifier_body |
issue-44197.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 ... | (_: &str) -> Result<String, ()> {
Err(())
}
fn bar2(baz: String) -> impl Generator<Yield = String, Return = ()> {
move || {
if let Ok(quux) = foo2(&baz) {
yield quux;
}
}
}
fn main() {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::... | foo2 | identifier_name |
issue-44197.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 ... |
}
}
fn main() {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::new()));
assert_eq!(bar2(String::new()).resume(), GeneratorState::Complete(()));
}
}
| {
yield quux;
} | conditional_block |
issue-44197.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 ... | }
fn bar2(baz: String) -> impl Generator<Yield = String, Return = ()> {
move || {
if let Ok(quux) = foo2(&baz) {
yield quux;
}
}
}
fn main() {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::new()));
assert_eq!(bar2(String::new()... | fn foo2(_: &str) -> Result<String, ()> {
Err(()) | random_line_split |
issue-44197.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 ... | {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::new()));
assert_eq!(bar2(String::new()).resume(), GeneratorState::Complete(()));
}
} | identifier_body | |
settings.js | 'use strict'
module.exports = function (Settings) {
// We have 1 settings object we save...
const settingsId = 'MasterSettings'
const defaultSettings = {
id : settingsId,
wksModelId: '',
wksModelDateTime: ''
}
Settings.load = function load (cb) {
Settings.exists(settingsId, (err, result) => {... | // default method is upsert, changes if settingsId doesn't exist
let method = Settings.upsert.bind(Settings)
let logMessage = `Settings.save(): Updating...`
if (doc) {
doc.id = settingsId
doc.wksModelDateTime = Date.now()
}
Settings.exists(settingsId, (err, result) => {
if (err... |
Settings.save = function save (doc, cb) {
// Reset the ID... | random_line_split |
settings.js | 'use strict'
module.exports = function (Settings) {
// We have 1 settings object we save...
const settingsId = 'MasterSettings'
const defaultSettings = {
id : settingsId,
wksModelId: '',
wksModelDateTime: ''
}
Settings.load = function load (cb) {
Settings.exists(settingsId, (err, result) => {... |
if (!result) {
// result is false, (doesn't exist, then...)
method = Settings.create.bind(Settings)
logMessage = `Settings.save(): Creating...`
}
console.log(logMessage)
method(doc, cb)
})
}
Settings.remoteMethod('load', {
http: {
verb: 'get'
},
... | {
console.log('Settings.save() failed on exists...')
} | conditional_block |
exception.rs | use crate::wrapper::{NIF_ENV, NIF_TERM};
/// Raise an "error exception".
///
/// # Unsafe
///
/// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// ... | /// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// And of course `env` must be a valid environment.
pub unsafe fn raise_badarg(env: NIF_ENV) -> NI... | random_line_split | |
exception.rs | use crate::wrapper::{NIF_ENV, NIF_TERM};
/// Raise an "error exception".
///
/// # Unsafe
///
/// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// ... | (env: NIF_ENV) -> NIF_TERM {
rustler_sys::enif_make_badarg(env)
}
| raise_badarg | identifier_name |
exception.rs | use crate::wrapper::{NIF_ENV, NIF_TERM};
/// Raise an "error exception".
///
/// # Unsafe
///
/// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// ... | {
rustler_sys::enif_make_badarg(env)
} | identifier_body | |
demo.component.ts | import {Component} from "@angular/core";
@Component({
templateUrl: './demo.component.html',
styles: [`
.live-demo-wrap p {
font-size: 14px;
margin: 10px 0 20px 0
}
.condition {
display: flex;
align-items: center;
margin: 10px;... | }
`]
})
export class DateTimePickerConfirmButtonDemoComponent {
showConfirmButton = true;
gr = ['date'];
date1 = 'now';
date2 = 'now';
date3 = {beginDate: 'now-1d', endDate: 'now'};
beginDate = "now-1d";
endDate = "now";
// ===================================================... |
.block {
display: inline-block;
margin-right: 30px; | random_line_split |
demo.component.ts | import {Component} from "@angular/core";
@Component({
templateUrl: './demo.component.html',
styles: [`
.live-demo-wrap p {
font-size: 14px;
margin: 10px 0 20px 0
}
.condition {
display: flex;
align-items: center;
margin: 10px;... | {
showConfirmButton = true;
gr = ['date'];
date1 = 'now';
date2 = 'now';
date3 = {beginDate: 'now-1d', endDate: 'now'};
beginDate = "now-1d";
endDate = "now";
// ====================================================================
// ignore the following lines, they are not importa... | DateTimePickerConfirmButtonDemoComponent | identifier_name |
adminPickupOptions.component.ts | 'use strict';
const angular = require('angular');
const uiRouter = require('angular-ui-router');
import routes from './adminPickupOptions.routes';
import {ModalBase} from '../shared/modal.base';
export class AdminPickupOptionsComponent extends ModalBase{
$http: ng.IHttpService;
$uibModal: ng.ui.bootstrap.IModal... | })
.name; | .component('adminPickupOptions', {
template: require('./adminPickupOptions.html'),
controller: AdminPickupOptionsComponent,
controllerAs: '$ctrl' | random_line_split |
adminPickupOptions.component.ts | 'use strict';
const angular = require('angular');
const uiRouter = require('angular-ui-router');
import routes from './adminPickupOptions.routes';
import {ModalBase} from '../shared/modal.base';
export class AdminPickupOptionsComponent extends ModalBase{
$http: ng.IHttpService;
$uibModal: ng.ui.bootstrap.IModal... |
create() {
let scope = this;
this.modal('adminPickupOptionEdit', this.getResolve(null), (pickupOption) => {
(scope.PickupOptionsService as any).reload();
scope.reload();
});
}
reload() {
(this.PickupOptionsService as any).get()
.then(pickupOptions => {
this.pickupOptions =... | {
let scope = this;
this.modal('adminPickupOptionEdit', this.getResolve(pickupOption), (pickupOption) => {
(scope.PickupOptionsService as any).reload();
scope.reload();
});
} | identifier_body |
adminPickupOptions.component.ts | 'use strict';
const angular = require('angular');
const uiRouter = require('angular-ui-router');
import routes from './adminPickupOptions.routes';
import {ModalBase} from '../shared/modal.base';
export class | extends ModalBase{
$http: ng.IHttpService;
$uibModal: ng.ui.bootstrap.IModalService;
pickupOptions: Object[] = [];
PickupOptionsService: Object;
/*@ngInject*/
constructor($http, $uibModal, PickupOptionsService) {
super($uibModal);
this.$http = $http;
this.PickupOptionsService = PickupOptionsSe... | AdminPickupOptionsComponent | identifier_name |
subcontractArrival.service.ts | import { Injectable, Inject } from '@angular/core';
import { MasterService } from '../../services/master.service';
import { HttpClient } from '@angular/common/http';
import { APP_CONFIG, IAppConfig } from '../../app.config';
import { AuthService } from '../../services/auth.service';
import { Observable } from 'rxjs/Obs... | this.setApiUrl('subcontractArrivals/');
}
getLatestBySubcontractOperation(subcontractOperationId): Observable<any> {
return this.http.get(this.apiUrl + 'latestBySubcontractOperationId?subcontractOperationId=' + subcontractOperationId, { headers: this.getJsonHeaders() })
.catch(err => this.handleError... | random_line_split | |
subcontractArrival.service.ts | import { Injectable, Inject } from '@angular/core';
import { MasterService } from '../../services/master.service';
import { HttpClient } from '@angular/common/http';
import { APP_CONFIG, IAppConfig } from '../../app.config';
import { AuthService } from '../../services/auth.service';
import { Observable } from 'rxjs/Obs... |
}
| {
return this.http.get(this.apiUrl + 'subcontractArrival?subcontractor=' + subcontractor + '&job=' + job +'&startDate=' + startDate + '&endDate=' + endDate + '&page=' + page + '&size=' + size, {headers: this.getJsonHeaders()})
.catch(err => this.handleError(err));
} | identifier_body |
subcontractArrival.service.ts | import { Injectable, Inject } from '@angular/core';
import { MasterService } from '../../services/master.service';
import { HttpClient } from '@angular/common/http';
import { APP_CONFIG, IAppConfig } from '../../app.config';
import { AuthService } from '../../services/auth.service';
import { Observable } from 'rxjs/Obs... | (private anHttp: HttpClient, @Inject(APP_CONFIG) private aConfig: IAppConfig, private anAuthService: AuthService) {
super(anHttp, aConfig, anAuthService);
this.setApiUrl('subcontractArrivals/');
}
getLatestBySubcontractOperation(subcontractOperationId): Observable<any> {
return this.http.get(this.apiUr... | constructor | identifier_name |
index.d.ts | // Type definitions for prosemirror-markdown 1.0
// Project: https://github.com/ProseMirror/prosemirror-markdown
// Definitions by: Bradley Ayers <https://github.com/bradleyayers>
// David Hahn <https://github.com/davidka>
// Tim Baumann <https://github.com/timjb>
// Definitions: https:/... |
constructor(nodes: { [name: string]: (state: MarkdownSerializerState, node: ProsemirrorNode, parent: ProsemirrorNode, index: number) => void }, marks: { [key: string]: any });
/**
* The node serializer
* functions for this serializer.
*/
nodes: { [name: string]: (p1: MarkdownSerializerState, p2: Prosemi... | rkdownSerializer { | identifier_name |
index.d.ts | // Type definitions for prosemirror-markdown 1.0
// Project: https://github.com/ProseMirror/prosemirror-markdown
// Definitions by: Bradley Ayers <https://github.com/bradleyayers>
// David Hahn <https://github.com/davidka>
// Tim Baumann <https://github.com/timjb>
// Definitions: https:/... | // This file was generated by https://github.com/bradleyayers/getdocs2ts. Please do not edit manually.
// When you find an error in these declarations, fix the getdocs comment upstream or 'getdocs2ts', then regenerate.
import { MarkdownIt } from 'markdown-it';
import { Node as ProsemirrorNode, Schema } from 'prosemirr... |
// IMPORTANT | random_line_split |
defaults.py | from socket import gethostname
from django.utils.translation import ugettext as _
from mezzanine.conf import register_setting
####################################################################
# This first set of settings already exists in Mezzanine but can #
# be overridden or appended to here with Cartridge ... | register_setting(
name="SHOP_CARD_TYPES",
description="Sequence of available credit card types for payment.",
editable=False,
default=("Mastercard", "Visa", "Diners", "Amex"),
)
register_setting(
name="SHOP_CART_EXPIRY_MINUTES",
description="Number of minutes of inactivity until carts are aband... | random_line_split | |
hooks-service.ts | import * as path from "path";
import * as util from "util";
import * as _ from "lodash";
import { annotate, getValueFromNestedObject } from "../helpers";
import { AnalyticsEventLabelDelimiter } from "../../constants";
import { IOptions, IPerformanceService } from "../../declarations";
import {
IHook,
IHooksService,
... | (
directoryPath: string,
hookName: string,
hookArguments?: IDictionary<any>
): Promise<any[]> {
hookArguments = hookArguments || {};
const results: any[] = [];
const hooks = this.getHooksByName(directoryPath, hookName);
for (let i = 0; i < hooks.length; ++i) {
const hook = hooks[i];
const result =... | executeHooksInDirectory | identifier_name |
hooks-service.ts | import * as path from "path";
import * as util from "util";
import * as _ from "lodash";
import { annotate, getValueFromNestedObject } from "../helpers";
import { AnalyticsEventLabelDelimiter } from "../../constants";
import { IOptions, IPerformanceService } from "../../declarations";
import {
IHook,
IHooksService,
... |
}
injector.register("hooksService", HooksService);
| {
const invalidArguments: string[] = [];
// We need to annotate the hook in order to have the arguments of the constructor.
annotate(hookConstructor);
_.each(hookConstructor.$inject.args, (argument: string) => {
try {
if (argument !== this.hookArgsName) {
this.$injector.resolve(argument);
}
... | identifier_body |
hooks-service.ts | import * as path from "path";
import * as util from "util";
import * as _ from "lodash";
import { annotate, getValueFromNestedObject } from "../helpers";
import { AnalyticsEventLabelDelimiter } from "../../constants";
import { IOptions, IPerformanceService } from "../../declarations";
import {
IHook,
IHooksService,
... |
}
const startTime = this.$performanceService.now();
if (inProc) {
this.$logger.trace(
"Executing %s hook at location %s in-process",
hookName,
hook.fullPath
);
const hookEntryPoint = require(hook.fullPath);
this.$logger.trace(`Validating ${hookName} arguments.`);
const invalidArgume... | {
command = process.argv[0];
inProc = this.shouldExecuteInProcess(this.$fs.readText(hook.fullPath));
} | conditional_block |
hooks-service.ts | import * as path from "path";
import * as util from "util";
import * as _ from "lodash";
import { annotate, getValueFromNestedObject } from "../helpers";
import { AnalyticsEventLabelDelimiter } from "../../constants";
import { IOptions, IPerformanceService } from "../../declarations";
import {
IHook,
IHooksService,
... | statement.expression.type !== "AssignmentExpression"
) {
return;
}
const left = statement.expression.left;
if (
left.type === "MemberExpression" &&
left.object &&
left.object.type === "Identifier" &&
left.object.name === "module" &&
left.property &&
left.property... | random_line_split | |
python.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... |
def build(self):
super().build()
setup_file = os.path.join(self.builddir, 'setup.py')
with simple_env_bzr(os.path.join(self.installdir, 'bin')):
self._run_pip(setup_file)
self._fix_permissions()
# Fix all shebangs to use the in-snap python.
file_utils... | for root, dirs, files in os.walk(self.installdir):
for filename in files:
_replicate_owner_mode(os.path.join(root, filename))
for dirname in dirs:
_replicate_owner_mode(os.path.join(root, dirname)) | identifier_body |
python.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | os.rmdir(bin_dir) | conditional_block | |
python.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | (self):
for root, dirs, files in os.walk(self.installdir):
for filename in files:
_replicate_owner_mode(os.path.join(root, filename))
for dirname in dirs:
_replicate_owner_mode(os.path.join(root, dirname))
def build(self):
super().build()
... | _fix_permissions | identifier_name |
python.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | It can be used for python projects where you would want to do:
- import python modules with a requirements.txt
- build a python project that has a setup.py
- install packages straight from pip
This plugin uses the common plugin keywords as well as those for "sources".
For more information check the 'plugi... | """The python plugin can be used for python 2 or 3 based parts.
| random_line_split |
AddSliceToNodesWhitelist.py | from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Nodes import Node, Nodes
from PLC.Slices import Slice, Slices
from PLC.Auth import Auth
class AddSliceToNodesWhitelist(Method):
"""
Adds the specified slice to the whitelist on the specified nodes. Nodes ... | return 1 | random_line_split | |
AddSliceToNodesWhitelist.py | from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Nodes import Node, Nodes
from PLC.Slices import Slice, Slices
from PLC.Auth import Auth
class AddSliceToNodesWhitelist(Method):
"""
Adds the specified slice to the whitelist on the specified nodes. Nodes ... |
slice.sync()
self.event_objects = {'Node': [node['node_id'] for node in nodes],
'Slice': [slice['slice_id']]}
return 1
| if node['peer_id'] is not None:
raise PLCInvalidArgument("%s not a local node" % node['hostname'])
if slice['slice_id'] not in node['slice_ids_whitelist']:
slice.add_to_node_whitelist(node, commit = False) | conditional_block |
AddSliceToNodesWhitelist.py | from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Nodes import Node, Nodes
from PLC.Slices import Slice, Slices
from PLC.Auth import Auth
class AddSliceToNodesWhitelist(Method):
| """
Adds the specified slice to the whitelist on the specified nodes. Nodes may be
either local or foreign nodes.
If the slice is already associated with a node, no errors are
returned.
Returns 1 if successful, faults otherwise.
"""
roles = ['admin']
accepts = [
Auth(),
... | identifier_body | |
AddSliceToNodesWhitelist.py | from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Nodes import Node, Nodes
from PLC.Slices import Slice, Slices
from PLC.Auth import Auth
class | (Method):
"""
Adds the specified slice to the whitelist on the specified nodes. Nodes may be
either local or foreign nodes.
If the slice is already associated with a node, no errors are
returned.
Returns 1 if successful, faults otherwise.
"""
roles = ['admin']
accepts = [
... | AddSliceToNodesWhitelist | identifier_name |
IHttpResponses.ts | ///<reference path="../../../tools/typings/tsd.d.ts" />
///<reference path="../../../tools/typings/app.d.ts" />
module adalO365CorsClient.shared {
'use strict';
/**
* Actual results from an OData response for SharePoint lists.
*/
interface ISpListOdataValue {
results: ISpList[];
}
/**
* Data o... | name: string;
webUrl: string;
}
/**
* Data object included in part of OData response for Office 365 Files API.
*/
interface IO365FileOdataData {
value: IO365FileOdataValue[];
}
/**
* HTTP response from OData query for Files's against Office 365's Files API.
*/
export interface IO36... | interface IO365FileOdataValue { | random_line_split |
devlali.py | import sys
devlali = {}
def sum_number(number):
str_n = str(number)
total = 0
for n in str_n:
total += int(n)
return total + number
def generate_devlali():
for i in range(10001):
total = sum_number(i)
if (total in devlali.keys()):
tmp_list = devlali[total]
... |
for num in range(lines):
n = int(sys.stdin.readline().strip())
print n, get_devlali(n)
main() | def main():
generate_devlali()
lines = int(sys.stdin.readline().strip()) | random_line_split |
devlali.py | import sys
devlali = {}
def sum_number(number):
str_n = str(number)
total = 0
for n in str_n:
total += int(n)
return total + number
def generate_devlali():
for i in range(10001):
total = sum_number(i)
if (total in devlali.keys()):
tmp_list = devlali[total]
... |
main()
| generate_devlali()
lines = int(sys.stdin.readline().strip())
for num in range(lines):
n = int(sys.stdin.readline().strip())
print n, get_devlali(n) | identifier_body |
devlali.py | import sys
devlali = {}
def sum_number(number):
str_n = str(number)
total = 0
for n in str_n:
total += int(n)
return total + number
def generate_devlali():
for i in range(10001):
total = sum_number(i)
if (total in devlali.keys()):
tmp_list = devlali[total]
... |
def get_devlali(number):
if (number in devlali.keys()):
if (len(devlali[number]) > 1):
return 'junction'
else:
return 'generated'
else:
return 'self'
def main():
generate_devlali()
lines = int(sys.stdin.readline().strip())
for num in range(lin... | devlali[total] = [i] | conditional_block |
devlali.py | import sys
devlali = {}
def sum_number(number):
str_n = str(number)
total = 0
for n in str_n:
total += int(n)
return total + number
def | ():
for i in range(10001):
total = sum_number(i)
if (total in devlali.keys()):
tmp_list = devlali[total]
tmp_list.append(i)
devlali[total] = tmp_list
else:
devlali[total] = [i]
def get_devlali(number):
if (number in devlali.keys()):
... | generate_devlali | identifier_name |
random-useragent_vx.x.x.js | // flow-typed signature: ab3901201165dd41c91885812af6b873
// flow-typed version: <<STUB>>/random-useragent_v^0.3.1/flow_v0.38.0
/**
* This is an autogenerated libdef stub for:
*
* 'random-useragent'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your wo... |
// Filename aliases
declare module 'random-useragent/index' {
declare module.exports: $Exports<'random-useragent'>;
}
declare module 'random-useragent/index.js' {
declare module.exports: $Exports<'random-useragent'>;
}
declare module 'random-useragent/scripts/create-data.js' {
declare module.exports: $Exports<'r... | declare module 'random-useragent/test' {
declare module.exports: any;
} | random_line_split |
action.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... |
}
| {
let mut workspace_args = vec!["--raw-workspace-name".to_owned(), workspace];
if let Some(version) = version {
workspace_args.append(&mut vec![
"--workspace-version".to_owned(),
version.to_string(),
]);
}
for i in 0..retries {
... | identifier_body |
action.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... |
} else {
info!("{} Cloud Sync was successful", sid);
return Ok(());
}
}
Ok(())
}
}
| {
return Err(ErrorKind::CommitCloudHgCloudSyncError(format!(
"process exited with: {}, retry later",
output.status
))
.into());
} | conditional_block |
action.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... |
let output = child.wait_with_output()?;
info!(
"{} stdout: \n{}",
sid,
String::from_utf8_lossy(&output.stdout).trim()
);
info!(
"{} stderr: \n{}",
sid,
String::from_utf8_loss... | "{} Fire `hg cloud sync` attempt {}, spawned process id '{}'",
sid,
i,
child.id()
); | random_line_split |
action.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... | <P: AsRef<Path>>(
sid: &String,
path: P,
retries: u32,
version: Option<u64>,
workspace: String,
reason: String,
) -> Result<()> {
let mut workspace_args = vec!["--raw-workspace-name".to_owned(), workspace];
if let Some(version) = version {
... | fire | identifier_name |
hash.rs | // Copyright 2015, 2016 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 la... |
assert_eq!(H128::from(0x1234567890abcdef), H128::from_str("00000000000000001234567890abcdef").unwrap());
assert_eq!(H64::from(0x1234567890abcdef), H64::from_str("1234567890abcdef").unwrap());
assert_eq!(H32::from(0x1234567890abcdef), H32::from_str("90abcdef").unwrap());
}
#[test]
fn from_str() {
assert_eq!... | _u64() { | identifier_name |
hash.rs | // Copyright 2015, 2016 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 la... | impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
known_heap_size!(0, H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048);
// Specialized HashMap and HashSet
/// Hasher that just takes 8 bytes of the provided value.
/// May only be used for keys which are 32 bytes.
pu... | impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33); | random_line_split |
hash.rs | // Copyright 2015, 2016 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 la... |
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&valu... | let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
} | identifier_body |
hash.rs | // Copyright 2015, 2016 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 la... |
}
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $... | {
s
} | conditional_block |
lib.rs | * Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! An async-compatible HTTP client built on top of libcurl.
#![allow(dead_code)]
mod client;
mod driver;
mod errors;
mod event_listeners;
m... | /* | random_line_split | |
echo-udp.rs | //! An UDP echo server that just sends back everything that it receives.
//!
//! If you're on unix you can test this out by in one terminal executing:
//!
//! cargo run --example echo-udp
//!
//! and in another terminal you can run:
//!
//! cargo run --example connect -- --udp 127.0.0.1:8080
//!
//! Each line y... |
// If we're here then `to_send` is `None`, so we take a look for the
// next message we're going to echo back.
self.to_send = Some(try_nb!(self.socket.recv_from(&mut self.buf)));
}
}
}
fn main() {
let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()... | {
let amt = try_nb!(self.socket.send_to(&self.buf[..size], &peer));
println!("Echoed {}/{} bytes to {}", amt, size, peer);
self.to_send = None;
} | conditional_block |
echo-udp.rs | //! An UDP echo server that just sends back everything that it receives.
//!
//! If you're on unix you can test this out by in one terminal executing:
//!
//! cargo run --example echo-udp
//!
//! and in another terminal you can run:
//!
//! cargo run --example connect -- --udp 127.0.0.1:8080
//!
//! Each line y... | (&mut self) -> Poll<(), io::Error> {
loop {
// First we check to see if there's a message we need to echo back.
// If so then we try to send it back to the original source, waiting
// until it's writable and we're able to do so.
if let Some((size, peer)) = self.to... | poll | identifier_name |
echo-udp.rs | //! An UDP echo server that just sends back everything that it receives. | //! cargo run --example echo-udp
//!
//! and in another terminal you can run:
//!
//! cargo run --example connect -- --udp 127.0.0.1:8080
//!
//! Each line you type in to the `nc` terminal should be echo'd back to you!
extern crate futures;
#[macro_use]
extern crate tokio;
#[macro_use]
extern crate tokio_io;
... | //!
//! If you're on unix you can test this out by in one terminal executing:
//! | random_line_split |
index.js | 'use strict';
var path = require('path');
var mergeTrees = require('broccoli-merge-trees');
var SassCompiler = require('../broccoli-sass');
function SASSPlugin() |
SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) {
var options = inputOptions;
var inputTrees = [tree];
if (options.includePaths) {
inputTrees = inputTrees.concat(options.includePaths);
}
var ext = options.extension || 'scss';
var paths = options.outputPaths;
var t... | {
this.name = 'ember-cli-sass';
this.ext = ['scss', 'sass'];
} | identifier_body |
index.js | 'use strict';
var path = require('path');
var mergeTrees = require('broccoli-merge-trees');
var SassCompiler = require('../broccoli-sass');
function SASSPlugin() {
this.name = 'ember-cli-sass';
this.ext = ['scss', 'sass'];
}
SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) {
va... | setupPreprocessorRegistry: function(type, registry) {
registry.add('css', new SASSPlugin());
},
}; | name: 'ember-cli-sass',
| random_line_split |
index.js | 'use strict';
var path = require('path');
var mergeTrees = require('broccoli-merge-trees');
var SassCompiler = require('../broccoli-sass');
function | () {
this.name = 'ember-cli-sass';
this.ext = ['scss', 'sass'];
}
SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) {
var options = inputOptions;
var inputTrees = [tree];
if (options.includePaths) {
inputTrees = inputTrees.concat(options.includePaths);
}
var ext = op... | SASSPlugin | identifier_name |
index.js | 'use strict';
var path = require('path');
var mergeTrees = require('broccoli-merge-trees');
var SassCompiler = require('../broccoli-sass');
function SASSPlugin() {
this.name = 'ember-cli-sass';
this.ext = ['scss', 'sass'];
}
SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) {
va... |
var ext = options.extension || 'scss';
var paths = options.outputPaths;
var trees = Object.keys(paths).map(function(file) {
var input = path.join(inputPath, file + '.' + ext);
var output = paths[file];
return new SassCompiler(inputTrees, input, output, options);
});
return mergeTrees(trees);
};... | {
inputTrees = inputTrees.concat(options.includePaths);
} | conditional_block |
normalizeFiles.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Normalize soundfiles in a folder, and write them to a new folder
# called normalized/
# Import Python modules
import contextlib
import os
import shutil
import sys
import wave
# Import user modules
def normalize():
""" Normalizes a set of sound files to norm-To dB
return ... |
# Check that the input parameters are valid. Get the name of the folder
# that contains the sound files and the sort type from the command-line
# arguments.
argValues = sys.argv
inputCheck(argValues)
folderToSort = argValues[1]
try:
normalizeTo = argValues[2]
except IndexError:
normalizeTo = -3
print 'Normalizi... | """ Check whether the input data is valid. If not print usage
information.
argValues ---> a list of the scripts command-line parameters.
"""
return 1 | identifier_body |
normalizeFiles.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Normalize soundfiles in a folder, and write them to a new folder
# called normalized/
# Import Python modules
import contextlib
import os
import shutil
import sys
import wave
# Import user modules
def normalize():
""" Normalizes a set of sound files to norm-To dB
return ... |
for singleFile in files:
#Only work with .wav files
if singleFile[-4:] == '.wav':
inputFile = folderToSort + singleFile
outfile = dirname + singleFile
command = 'sox --norm={0} {1} {2}'.format(normalizeTo, inputFile,
outfile)
os.system(command)
return 1
def inputCheck(argValues):
""" ... | raise | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.