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 |
|---|---|---|---|---|
build.rs | build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
mark_dir_as_rerun_trigger(&thirdpartyprotobuf);
let grpcio_output_dir = PathBuf::from("src/gen");
replace_if_changed(&grpcio_output_dir, |path| {
generate_for_grpcio(&thirdpartyprotobuf, path);
form... | (thirdpartyprotobuf: &Path, out_dir: &Path) {
tower_grpc_build::Config::new()
.enable_server(true)
.enable_client(true)
.build(
&[PathBuf::from(
"build/bazel/remote/execution/v2/remote_execution.proto",
)],
&std::fs::read_dir(&thirdpartyprotobuf)
.unwrap()
.map(|d... | generate_for_tower | identifier_name |
build.rs | _for_tower(&thirdpartyprotobuf, path);
format(path);
});
// Re-gen if, say, someone does a git clean on the gen dir but not the target dir. This ensures
// generated sources are available for reading by programmers and tools like rustfmt alike.
mark_dir_as_rerun_trigger(&grpcio_output_dir);
mark_dir_as_r... | {
let mut rustfmt = PathBuf::from(env!("CARGO"));
rustfmt.pop();
rustfmt.push("rustfmt");
let mut rustfmt_config = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
rustfmt_config.pop(); // bazel_protos
rustfmt_config.pop(); // process_execution
rustfmt_config.push("rustfmt.toml");
if !rustfmt_config.exists()... | identifier_body | |
build.rs | build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
mark_dir_as_rerun_trigger(&thirdpartyprotobuf);
let grpcio_output_dir = PathBuf::from("src/gen");
replace_if_changed(&grpcio_output_dir, |path| {
generate_for_grpcio(&thirdpartyprotobuf, path);
form... |
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
copy_dir::copy_dir(tempdir.path(), path).unwrap();
}
fn format(path: &Path) {
let mut rustfmt = PathBuf::from(env!("CARGO"));
rustfmt.pop();
rustfmt.push("rustfmt");
let mut rustfmt_config = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
rustfmt_conf... | {
std::fs::remove_dir_all(path).unwrap();
} | conditional_block |
build.rs | let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
mark_dir_as_rerun_trigger(&thirdpartyprotobuf);
let grpcio_output_dir = PathBuf::from("src/gen");
replace_if_changed(&grpcio_output_dir, |path| {
generate_for_grpcio(&thirdpartyprotobuf, path);
... | ///
fn disable_clippy_in_generated_code(dir: &Path) -> Result<(), String> {
for file in walkdir::WalkDir::new(&dir)
.into_iter()
.filter_map(|entry| entry.ok())
.filter(|entry| {
entry.file_type().is_file() && entry.file_name().to_string_lossy().ends_with(".rs")
})
{
let lines: Vec<_> = st... | /// warnings/errors from generated code not meeting our standards. | random_line_split |
all_10.js | var searchData= | ['translate',['Translate',['../class_oxy_1_1_framework_1_1_graphics.html#ac854767976984446279c8cfbc04f2099',1,'Oxy::Framework::Graphics']]]
]; | [
['textobject',['TextObject',['../class_oxy_1_1_framework_1_1_objects_1_1_text_object.html',1,'Oxy::Framework::Objects']]],
['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.html',1,'Oxy::Framework']]],
['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.ht... | random_line_split |
heroe-list.component.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... | var HeroeList = (function () {
function HeroeList(router, heroService) {
this.router = router;
this.heroService = heroService;
this.title = "Tour of Heroes";
}
HeroeList.prototype.ngOnInit = function () {
this.getHeroes();
};
HeroeList.prototype.getHeroes = function (... | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var hero_service_1 = require('../../services/hero.service'); | random_line_split |
heroe-list.component.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... |
HeroeList.prototype.ngOnInit = function () {
this.getHeroes();
};
HeroeList.prototype.getHeroes = function () {
var _this = this;
this.heroService.getHeroes().then(function (heroes) { return _this.heroes = heroes; });
};
HeroeList.prototype.add = function (name) {
va... | {
this.router = router;
this.heroService = heroService;
this.title = "Tour of Heroes";
} | identifier_body |
heroe-list.component.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... | (router, heroService) {
this.router = router;
this.heroService = heroService;
this.title = "Tour of Heroes";
}
HeroeList.prototype.ngOnInit = function () {
this.getHeroes();
};
HeroeList.prototype.getHeroes = function () {
var _this = this;
this.heroServic... | HeroeList | identifier_name |
img.js | /**
* IMG
* preFlash
*
* All functions related to img files
* management.
*/
// PACKAGES
const gulp = require("gulp");
const g = {
cached: require("gulp-cached"),
favicon: require("gulp-real-favicon"),
if: require("gulp-if"),
imagemin: require("gulp-imagemin"),
plumber: require("gulp-plumber"),
rena... |
});
done();
});
| {
throw err;
} | conditional_block |
img.js | /**
* IMG
* preFlash
*
* All functions related to img files
* management.
*/
// PACKAGES
const gulp = require("gulp");
const g = {
cached: require("gulp-cached"),
favicon: require("gulp-real-favicon"),
if: require("gulp-if"),
imagemin: require("gulp-imagemin"),
plumber: require("gulp-plumber"),
rena... | g.imagemin.gifsicle(CONFIG.packages.img.plugins.gifsicle),
g.imagemin.jpegtran(CONFIG.packages.img.plugins.jpegtran),
g.imagemin.optipng(CONFIG.packages.img.plugins.optipng),
g.imagemin.svgo(CONFIG.packages.img.plugins.svgo)
],
CONFIG.packages.img.options
))
.pipe(g.i... | return gulp.src(CONFIG.paths.sources.img)
.pipe(g.plumber({errorHandler: HELPERS.alert}))
.pipe(g.cached('img'))
.pipe(g.imagemin(
[ | random_line_split |
index.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.push = push;
exports.unshift = unshift;
exports.pop = pop;
exports.shift = shift;
exports.sort = sort;
exports.reverse = reverse;
exports.removeAt = removeAt;
exports.setKey = setKey;
exports.setAt = setAt;
exports.assign = assign;
... | (arr, index) {
if (isNaN(index) || index < 0 || index % 1 !== 0) {
debug('Was given a non-integer value ' + index);
return arr.slice();
}
return arr.slice(0, index).concat(arr.slice(index + 1, arr.length));
}
/**
* Returns a copy of the `obj` object, with the element associated with the
* specified `ke... | removeAt | identifier_name |
index.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.push = push;
exports.unshift = unshift;
exports.pop = pop;
exports.shift = shift;
exports.sort = sort;
exports.reverse = reverse;
exports.removeAt = removeAt;
exports.setKey = setKey;
exports.setAt = setAt;
exports.assign = assign;
... |
/**
* Assigns all properties from the source objects, to the specified destination
* object.
*
* @param {Object} destination
* @param {Object} source in sources
* @return {Object}
*/
function assign(destination) {
for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _... | {
if (arr.length <= index) {
return arr.concat(Array(index - arr.length)).concat([value]);
}
return arr.slice(0, index).concat([value]).concat(arr.slice(index + 1, arr.length));
} | identifier_body |
index.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.push = push;
exports.unshift = unshift;
exports.pop = pop;
exports.shift = shift;
exports.sort = sort;
exports.reverse = reverse;
exports.removeAt = removeAt;
exports.setKey = setKey;
exports.setAt = setAt;
exports.assign = assign;
... |
return _objectAssign2['default'].apply(undefined, [{}, destination].concat(sources));
}
| {
sources[_key - 1] = arguments[_key];
} | conditional_block |
index.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.push = push;
exports.unshift = unshift;
exports.pop = pop;
exports.shift = shift;
exports.sort = sort;
exports.reverse = reverse;
exports.removeAt = removeAt;
exports.setKey = setKey;
exports.setAt = setAt;
exports.assign = assign;
... | */
function shift(arr) {
return arr.slice(1, arr.length);
}
/**
* Returns a copy of the `arr` array, with all the elements sorted. Optionally,
* you can supply a function that
*
* @param {Array[Anything]} arr
* @param {Function : (Anything, Anything) -> Number}
* @return {Array[Anything]}
*/
function sort(... | *
* @param {Array[Anything]} arr
* @return {Array[Anything]} | random_line_split |
constant.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rest = require('./internal/rest');
var _rest2 = _interopRequireDefault(_rest);
var _initialParams = require('./internal/initialParams');
var _initialParams2 = _interopRequireDefault(_initialParams);
function _interopRequireDefau... |
/**
* Returns a function that when called, calls-back with the values provided.
* Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
* [`auto`]{@link module:ControlFlow.auto}.
*
* @name constant
* @static
* @memberOf module:Utils
* @method
* @cat... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
constant.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rest = require('./internal/rest');
var _rest2 = _interopRequireDefault(_rest);
var _initialParams = require('./internal/initialParams');
var _initialParams2 = _interopRequireDefault(_initialParams);
function _interopRequireDefau... | });
});
module.exports = exports['default']; | return callback.apply(this, args); | random_line_split |
constant.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rest = require('./internal/rest');
var _rest2 = _interopRequireDefault(_rest);
var _initialParams = require('./internal/initialParams');
var _initialParams2 = _interopRequireDefault(_initialParams);
function | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Returns a function that when called, calls-back with the values provided.
* Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
* [`auto`]{@link module:ControlFlow.auto}.
*
* @name ... | _interopRequireDefault | identifier_name |
05-delegator.js | var EXPORT = ['Delegator'];
/*
* メソッドの委譲を行う
*/
let Delegator = function(obj, propertyDelegate) {
this.__target__obj = obj;
if (typeof propertyDelegate == 'undefined')
propertyDelegate = true;
if (propertyDelegate) {
this.__propertyDelegate__();
}
};
Delegator.prototype = {
get... | }; | random_line_split | |
config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'frey.maxim@gmail.com'
... | (Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp'
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.comput... | TestingConfig | identifier_name |
config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'frey.maxim@gmail.com'
... |
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp'
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2... | DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp' | identifier_body |
config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'frey.maxim@gmail.com'
... | pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp'
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:... | random_line_split | |
extensionproperties.component.ts | import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { ExtensionProperties } from './../models/extensionproperties';
@Component({
moduleId: module.id,
selector: 'extension-properties', | availableKeys = ExtensionProperties.availableKeys;
selectModel: string;
@Input('Model')
model: ExtensionProperties;
@Output()
onDelete = new EventEmitter<ExtensionProperties>();
@ViewChild('nameInput')
input: any;
constructor() { }
ngOnInit() {
if (typeof this.model.Name... | templateUrl: 'extensionproperties.component.html'
})
export class ExtensionPropertiesComponent implements OnInit, AfterViewInit { | random_line_split |
extensionproperties.component.ts | import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { ExtensionProperties } from './../models/extensionproperties';
@Component({
moduleId: module.id,
selector: 'extension-properties',
templateUrl: 'extensionproperties.component.html'
})
export cl... |
onChangeExtensionKeys(type: any): void {
console.log(type);
if (type === 'custom') {
this.model.Name = '';
this.input.nativeElement.style.visibility = 'visible';
} else {
this.model.Name = type;
this.input.nativeElement.style.visibility = 'hi... | {
if (this.selectModel !== 'custom') {
this.input.nativeElement.style.visibility = 'hidden';
}
} | identifier_body |
extensionproperties.component.ts | import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { ExtensionProperties } from './../models/extensionproperties';
@Component({
moduleId: module.id,
selector: 'extension-properties',
templateUrl: 'extensionproperties.component.html'
})
export cl... |
}
ngAfterViewInit() {
if (this.selectModel !== 'custom') {
this.input.nativeElement.style.visibility = 'hidden';
}
}
onChangeExtensionKeys(type: any): void {
console.log(type);
if (type === 'custom') {
this.model.Name = '';
this.inp... | {
this.selectModel = this.availableKeys.find(e => e === this.model.Name);
if (typeof this.selectModel === 'undefined') {
this.selectModel = 'custom';
}
} | conditional_block |
extensionproperties.component.ts | import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { ExtensionProperties } from './../models/extensionproperties';
@Component({
moduleId: module.id,
selector: 'extension-properties',
templateUrl: 'extensionproperties.component.html'
})
export cl... | () {
if (typeof this.model.Name !== 'undefined') {
this.selectModel = this.availableKeys.find(e => e === this.model.Name);
if (typeof this.selectModel === 'undefined') {
this.selectModel = 'custom';
}
}
}
ngAfterViewInit() {
if (this.... | ngOnInit | identifier_name |
asyncload.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Shows how to use BitmapManager to asynchronously load a Bitmap from a file.
Run this snippet providing a list of filenames of (high resolution) pictures:
$ ./asyncload.py /path/to/mypics/*.jpg anotherpic.png nonexistent.png
Press space to sequentially load the pictur... |
def __setBitmapAndResize(self, bmp):
originalSize = bmp.getSize()
if originalSize.x > originalSize.y:
ratio = (APP_RESOLUTION[0] - 20) / originalSize.x
else:
ratio = (APP_RESOLUTION[1] - 40) / originalSize.y
self.__imageNode.setBitmap(b... | self.__infoNode.text = ('Loaded %s, '
'press space for the next one' % self.__pics[self.__currentPic])
self.__setBitmapAndResize(bmp) | conditional_block |
asyncload.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Shows how to use BitmapManager to asynchronously load a Bitmap from a file.
Run this snippet providing a list of filenames of (high resolution) pictures:
$ ./asyncload.py /path/to/mypics/*.jpg anotherpic.png nonexistent.png
Press space to sequentially load the pictur... |
if len(sys.argv) == 1:
print 'Usage: %s <filename> [<filename> [<filename> [..]]]' % sys.argv[0]
sys.exit(1)
AsyncLoadApp.start(resolution=APP_RESOLUTION)
| if self.__spinner.active:
self.__spinner.angle += 0.05 | identifier_body |
asyncload.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Shows how to use BitmapManager to asynchronously load a Bitmap from a file.
Run this snippet providing a list of filenames of (high resolution) pictures:
$ ./asyncload.py /path/to/mypics/*.jpg anotherpic.png nonexistent.png
Press space to sequentially load the pictur... | (self, event):
'''
Intercept a space keypress and trigger the request.
'''
if event.keystring == 'space':
self.__requestNextBitmap()
def __requestNextBitmap(self):
'''
Ask the BitmapManager to load a new file. loadBitmap() call returns immediately.
... | onKeyDown | identifier_name |
asyncload.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Shows how to use BitmapManager to asynchronously load a Bitmap from a file.
Run this snippet providing a list of filenames of (high resolution) pictures:
$ ./asyncload.py /path/to/mypics/*.jpg anotherpic.png nonexistent.png
Press space to sequentially load the pictur... | from libavg import player
APP_RESOLUTION = (640, 480)
class AsyncLoadApp(libavg.AVGApp):
def init(self):
'''
Create placeholders for the example. A single ImageNode is used to show
the pictures.
'''
self.__imageNode = libavg.avg.ImageNode(pos=(10, 20), parent=self._parentN... | random_line_split | |
shakeout_menu.spec.js | // The following will make sure the team_leader does not have access to certain menu items
// All menu items have been tested at the administration level
describe("Shakeout Menu", () => {
// Before running tests - we have to make sure the admin user is logged in
before(() => {
cy.login('team_leader','Test1234$... | //Make sure the administration drop down does not exist
cy.get('#administrationDropdown')
.should('not.exist');
})
}) | //Go to dashboard
cy.visit('http://localhost:8000/');
| random_line_split |
0022_anexoexpediente.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-14 17:41
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import posgradmin.models
class Migration(migrations.Migration):
dependencies = [
mi... | ('fecha', models.DateTimeField(auto_now_add=True)),
('archivo', models.FileField(upload_to=posgradmin.models.anexo_expediente_path)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
] | fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | random_line_split |
0022_anexoexpediente.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-14 17:41
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import posgradmin.models
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posgradmin', '0021_auto_20181109_2042'),
]
operations = [
migrations.CreateModel(
name='AnexoExpediente',
fields=[
('id', models.AutoField(a... | Migration | identifier_name |
0022_anexoexpediente.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-14 17:41
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import posgradmin.models
class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posgradmin', '0021_auto_20181109_2042'),
]
operations = [
migrations.CreateModel(
name='AnexoExpediente',
fields=[
('id', models.AutoField(auto_created=True, primary_key... | identifier_body | |
operation.rs | use std::collections::HashMap;
use soap::{ Fault, Part, Request, Response };
pub struct | {
pub doc: String,
pub name: String,
pub inputs: HashMap<String, Part>,
pub outputs: HashMap<String, Part>,
pub closure: Box<FnMut(Request) -> Response>
}
impl Operation {
pub fn not_found() -> Operation {
Operation {
doc: String::from("Handler for unknown opera... | Operation | identifier_name |
operation.rs | use std::collections::HashMap;
use soap::{ Fault, Part, Request, Response };
pub struct Operation {
pub doc: String,
pub name: String,
pub inputs: HashMap<String, Part>,
pub outputs: HashMap<String, Part>,
pub closure: Box<FnMut(Request) -> Response>
}
impl Operation {
pub fn not_foun... |
unsafe impl Send for Operation {} | } | random_line_split |
architecture.rs | /*
* Panopticon - A libre disassembler
* Copyright (C) 2015, 2017 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your opti... |
fn decode(reg: &Region, start: u64, cfg: &Self::Configuration) -> Result<Match<Self>> {
let data = reg.iter();
let mut buf: Vec<u8> = vec![];
let mut i = data.seek(start);
let p = start;
while let Some(Some(b)) = i.next() {
buf.push(b);
if buf.len()... | {
Ok(vec![])
} | identifier_body |
architecture.rs | /*
* Panopticon - A libre disassembler
* Copyright (C) 2015, 2017 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your opti... |
#[derive(Clone,PartialEq,Copy,Debug)]
pub enum Mode {
Real, // Real mode / Virtual 8086 mode
Protected, // Protected mode / Long compatibility mode
Long, // Long 64-bit mode
}
impl Mode {
pub fn alt_bits(&self) -> usize {
match self {
&Mode::Real => 32,
&Mode::Protected... | pub enum Amd64 {} | random_line_split |
architecture.rs | /*
* Panopticon - A libre disassembler
* Copyright (C) 2015, 2017 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your opti... | (_: &Region, _: &Self::Configuration) -> Result<Vec<(&'static str, u64, &'static str)>> {
Ok(vec![])
}
fn decode(reg: &Region, start: u64, cfg: &Self::Configuration) -> Result<Match<Self>> {
let data = reg.iter();
let mut buf: Vec<u8> = vec![];
let mut i = data.seek(start);
... | prepare | identifier_name |
ConditionType.ts | import * as $ from 'jquery'
import ConditionTypeConfig from "@enhavo/form/Type/ConditionTypeConfig";
import ConditionObserver from "@enhavo/form/Type/ConditionObserver";
export default class ConditionType
{
public static subjects: ConditionType[] = [];
private $element: JQuery;
private config: ConditionT... |
public notify()
{
for (let observer of this.observers) {
observer.wakeUp(this);
}
}
public static apply(element:HTMLElement)
{
$(element).find('[data-condition-type]').each(function(index, element:HTMLElement) {
new ConditionType(element);
}... | {
this.observers.push(observer);
observer.wakeUp(this);
} | identifier_body |
ConditionType.ts | import * as $ from 'jquery'
import ConditionTypeConfig from "@enhavo/form/Type/ConditionTypeConfig";
import ConditionObserver from "@enhavo/form/Type/ConditionObserver";
export default class ConditionType
{
public static subjects: ConditionType[] = [];
private $element: JQuery;
private config: ConditionT... |
this.$input.on('change ifChecked', function(event) {
self.notify();
});
}
public register(observer: ConditionObserver)
{
this.observers.push(observer);
observer.wakeUp(this);
}
public notify()
{
for (let observer of this.observers) {
... | {
this.$input = this.$element.find('input');
} | conditional_block |
ConditionType.ts | import * as $ from 'jquery'
import ConditionTypeConfig from "@enhavo/form/Type/ConditionTypeConfig";
import ConditionObserver from "@enhavo/form/Type/ConditionObserver";
export default class ConditionType
{
public static subjects: ConditionType[] = [];
private $element: JQuery;
private config: ConditionT... |
return this.$input.val();
}
} | random_line_split | |
ConditionType.ts | import * as $ from 'jquery'
import ConditionTypeConfig from "@enhavo/form/Type/ConditionTypeConfig";
import ConditionObserver from "@enhavo/form/Type/ConditionObserver";
export default class ConditionType
{
public static subjects: ConditionType[] = [];
private $element: JQuery;
private config: ConditionT... | ()
{
for (let observer of this.observers) {
observer.wakeUp(this);
}
}
public static apply(element:HTMLElement)
{
$(element).find('[data-condition-type]').each(function(index, element:HTMLElement) {
new ConditionType(element);
});
$(eleme... | notify | identifier_name |
coverers.py | """
Coverers of the filtrated space
"""
from __future__ import print_function
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class HyperRectangleCoverer(BaseEstimator, TransformerMixin):
""" Covers the space using overlapping hyperectangles
Parameters | ----------
intervals: integer or list of integers
number of intervals in each filtered space dimension, if an integer
is specified the same number is used in all dimensions.
overlap: float or list of floats
fraction of overlap between hyperectangles in each space dimension,
if a si... | random_line_split | |
coverers.py | """
Coverers of the filtrated space
"""
from __future__ import print_function
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class HyperRectangleCoverer(BaseEstimator, TransformerMixin):
""" Covers the space using overlapping hyperectangles
Parameters
----------
interv... |
else:
overlap = np.full((X.shape[1]), self.overlap, dtype=float)
# partition each dimension, incluiding last point
bbs, ws = zip(*[np.linspace(*min_max_num, endpoint=True, retstep=True)
for min_max_num in
zip(np.min(X, axis=0),
... | overlap = np.array(self.overlap, dtype=float) | conditional_block |
coverers.py | """
Coverers of the filtrated space
"""
from __future__ import print_function
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class HyperRectangleCoverer(BaseEstimator, TransformerMixin):
| def __init__(self, intervals=10, overlap=0.5):
self.intervals = intervals
self.overlap = overlap
def fit(self, X, y=None):
""" Creates the space covering for the input data
It creates a hyperectangle covering of the multidimensional space of X.
Parameters
-----... | """ Covers the space using overlapping hyperectangles
Parameters
----------
intervals: integer or list of integers
number of intervals in each filtered space dimension, if an integer
is specified the same number is used in all dimensions.
overlap: float or list of floats
fraction of... | identifier_body |
coverers.py | """
Coverers of the filtrated space
"""
from __future__ import print_function
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class HyperRectangleCoverer(BaseEstimator, TransformerMixin):
""" Covers the space using overlapping hyperectangles
Parameters
----------
interv... | (self):
""" Returns a boolean array with the overlaps between space partitions
Returns a (n_partitions, n_partitions) boolean array whose elements
are true when there is overlap between the i and j partitions, only
upper triangle is filled (rest is False).
Returns
-----... | overlap_matrix | identifier_name |
rules.js | 'use strict';
/* jshint -W098 */
angular.module('mean.rules').controller('RulesController', ['$scope', '$stateParams', '$location', '$http','Global', 'Rules', 'MeanUser','Circles','Groups',
function($scope, $stateParams, $location, $http, Global, Rules, MeanUser,Circles,Groups) {
$scope.global = Global;
$sco... | else {
$scope.rules.$remove(function(response) {
$location.path('rules');
});
}
};
$scope.update = function(isValid) {
if (isValid) {
var rule = $scope.rule;
if (!rule.updated) {
rule.updated = [];
}
rule.updated.push(new Date().g... | {
rule.$remove(function(response) {
for (var i in $scope.rules) {
if ($scope.rules[i] === rule) {
$scope.rules.splice(i, 1);
}
}
$location.path('rules');
});
} | conditional_block |
rules.js | 'use strict';
/* jshint -W098 */
angular.module('mean.rules').controller('RulesController', ['$scope', '$stateParams', '$location', '$http','Global', 'Rules', 'MeanUser','Circles','Groups',
function($scope, $stateParams, $location, $http, Global, Rules, MeanUser,Circles,Groups) {
$scope.global = Global;
$sco... | };
$scope.findOne = function() {
Rules.get({
ruleId: $stateParams.ruleId
}, function(rule) {
$scope.rule = rule;
});
};
$scope.documentupdate = function(testdata) {
$scope.testdataerror=false;
try{
testdata = JSON.parse(testdata);
... | }); | random_line_split |
models.py | from django.db import models
# Create your models here.
from djangotoolbox.fields import ListField, EmbeddedModelField
from django_mongodb_engine.storage import GridFSStorage
gridfs_storage = GridFSStorage()
class Cordinates(models.Model):
lat = models.FloatField(null=False, blank=False)
lng = models.FloatFi... | :
verbose_name_plural = 'Categories'
class Location(models.Model):
user = models.CharField(max_length=255)
name = models.CharField(max_length=255)
description = models.TextField()
category = models.IntegerField(null=True, blank=True)
tags = ListField(models.CharField(max_length=15), null=Tr... | Meta | identifier_name |
models.py | from django.db import models
# Create your models here.
from djangotoolbox.fields import ListField, EmbeddedModelField
from django_mongodb_engine.storage import GridFSStorage
gridfs_storage = GridFSStorage()
class Cordinates(models.Model):
lat = models.FloatField(null=False, blank=False)
lng = models.FloatFi... | #coordinates = EmbeddedModelField('Coordinates')
email = models.EmailField()
phone_number = models.CharField(max_length=15, null=True, blank=True)
rating = models.PositiveSmallIntegerField(blank=True, null=True)
photo = models.FileField(storage=gridfs_storage, upload_to='/media/locations/',
... | description = models.TextField()
category = models.IntegerField(null=True, blank=True)
tags = ListField(models.CharField(max_length=15), null=True, blank=True) | random_line_split |
models.py | from django.db import models
# Create your models here.
from djangotoolbox.fields import ListField, EmbeddedModelField
from django_mongodb_engine.storage import GridFSStorage
gridfs_storage = GridFSStorage()
class Cordinates(models.Model):
lat = models.FloatField(null=False, blank=False)
lng = models.FloatFi... |
class Category(models.Model):
name = models.CharField(max_length=255)
photo = models.FileField(storage=gridfs_storage, upload_to='/media/categories/')
class Meta:
verbose_name_plural = 'Categories'
class Location(models.Model):
user = models.CharField(max_length=255)
name = models.CharFi... | value = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Tags' | identifier_body |
status_position.py | # -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
from GMATE import i18n as i
from GMATE.status_widget import StatusWidget
class StatusPosition(StatusWidget):
""... |
def on_disconnect(self):
if self.buffer:
if self.__changed_id:
self.buff.disconnect(self.__changed_id)
self.__changed_id = None
if self.__mark_set_id:
self.buff.disconnect(self.__mark_set_id)
self.__mark_set_id = None
... | elf.buffer = None
self.document = None
self.__changed_id = None
self.__mark_set_id = None
self.line_title_label = gtk.Label(i.status_line)
self.line_position_number = gtk.Label('0')
self.line_position_number.set_size_request(40, -1)
self.line_position_number.set_a... | identifier_body |
status_position.py | # -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
from GMATE import i18n as i
from GMATE.status_widget import StatusWidget
class StatusPosition(StatusWidget): | """
This box holds the current line number
"""
def initialize(self):
self.buffer = None
self.document = None
self.__changed_id = None
self.__mark_set_id = None
self.line_title_label = gtk.Label(i.status_line)
self.line_position_number = gtk.Label('0')
... | random_line_split | |
status_position.py | # -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
from GMATE import i18n as i
from GMATE.status_widget import StatusWidget
class StatusPosition(StatusWidget):
""... |
def on_set_document(self, doc):
self.on_disconnect()
self.buff = doc.View.get_buffer()
self.document = doc.View
self.__changed_id = self.buff.connect("changed", self.__changed_cb)
self.__mark_set_id = self.buff.connect("mark-set", self.__mark_set_cb)
self.__changed_... | f self.__changed_id:
self.buff.disconnect(self.__changed_id)
self.__changed_id = None
if self.__mark_set_id:
self.buff.disconnect(self.__mark_set_id)
self.__mark_set_id = None
| conditional_block |
status_position.py | # -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
from GMATE import i18n as i
from GMATE.status_widget import StatusWidget
class StatusPosition(StatusWidget):
""... | self, buff):
tabwidth = self.document.get_tab_width()
iter = buff.get_iter_at_mark(buff.get_insert())
row = iter.get_line() + 1
col_offset = iter.get_line_offset()
iter.set_line_offset(0)
col = 0
while not col_offset == iter.get_line_offset():
if iter.... | _changed_cb( | identifier_name |
test_plugin_utils.py | import sys
import unittest
from streamlink.plugin.api.utils import itertags
def unsupported_versions_1979():
"""Unsupported python versions for itertags
3.7.0 - 3.7.2 and 3.8.0a1
- https://github.com/streamlink/streamlink/issues/1979
- https://bugs.python.org/issue34294
"""
v = sys.v... |
def test_itertags_attrs_text(self):
script = list(itertags(self.test_html, "script"))
self.assertTrue(len(script), 2)
self.assertEqual(script[0].tag, "script")
self.assertEqual(script[0].text, "")
self.assertEqual(script[0].attributes, {"src": "https://test.se/test.js"})
... | title = list(itertags(self.test_html, "title"))
self.assertTrue(len(title), 1)
self.assertEqual(title[0].tag, "title")
self.assertEqual(title[0].text, "Title")
self.assertEqual(title[0].attributes, {}) | identifier_body |
test_plugin_utils.py | import sys
import unittest
from streamlink.plugin.api.utils import itertags
def unsupported_versions_1979():
"""Unsupported python versions for itertags
3.7.0 - 3.7.2 and 3.8.0a1
- https://github.com/streamlink/streamlink/issues/1979
- https://bugs.python.org/issue34294
"""
v = sys.v... | (self):
script = list(itertags(self.test_html, "script"))
self.assertTrue(len(script), 2)
self.assertEqual(script[0].tag, "script")
self.assertEqual(script[0].text, "")
self.assertEqual(script[0].attributes, {"src": "https://test.se/test.js"})
self.assertEqual(script[1].... | test_itertags_attrs_text | identifier_name |
test_plugin_utils.py | import sys
import unittest
from streamlink.plugin.api.utils import itertags
def unsupported_versions_1979():
"""Unsupported python versions for itertags
3.7.0 - 3.7.2 and 3.8.0a1
- https://github.com/streamlink/streamlink/issues/1979
- https://bugs.python.org/issue34294
"""
v = sys.v... |
else:
return False
class TestPluginUtil(unittest.TestCase):
test_html = """
<!doctype html>
<html lang="en" class="no-js">
<title>Title</title>
<meta property="og:type" content= "website" />
<meta property="og:url" content="http://test.se/"/>
<meta property="og:site_name" content="Test" />
<script sr... | return True | conditional_block |
test_plugin_utils.py | import sys
import unittest
from streamlink.plugin.api.utils import itertags
def unsupported_versions_1979():
"""Unsupported python versions for itertags
3.7.0 - 3.7.2 and 3.8.0a1
- https://github.com/streamlink/streamlink/issues/1979
- https://bugs.python.org/issue34294
"""
v = sys.v... | return False
class TestPluginUtil(unittest.TestCase):
test_html = """
<!doctype html>
<html lang="en" class="no-js">
<title>Title</title>
<meta property="og:type" content= "website" />
<meta property="og:url" content="http://test.se/"/>
<meta property="og:site_name" content="Test" />
<script src="https://... | random_line_split | |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | pub use unicode::tables::property::Pattern_White_Space;
} | pub mod property { | random_line_split |
test_unit.py | # This doesn't work- not updated with eventmaster.py updates
# TODO: Fix This :)
# Import Libraries
import eventmaster
import time
import random
import sys
import unittest
import sys
class InputsTestCase(unittest.TestCase):
def setUp(self):
self.s3 = E2S3.E2S3Switcher()
self.s3.set_verbose(0)
... |
def test_set_valid_name_on_invalid_input(self):
test_str = "PYTEST-{0!s}".format(random.randint(1,10))
self.assertRaises(ValueError, lambda: self.s3.get_input(99).set_Name(test_str))
def test_set_valid_name_on_valid_input(self):
test_str = "PYTEST-{0!s}".format(random.randint(1,10))
... | time.sleep(1) | conditional_block |
test_unit.py | # This doesn't work- not updated with eventmaster.py updates
# TODO: Fix This :)
# Import Libraries
import eventmaster
import time
import random
import sys
import unittest
import sys
class InputsTestCase(unittest.TestCase):
def | (self):
self.s3 = E2S3.E2S3Switcher()
self.s3.set_verbose(0)
self.s3.set_CommsXML_IP("127.0.0.1")
self.s3.set_CommsXML_Port(9876)
if not self.s3.connect(): return -1
while self.s3.is_ready() != 1: time.sleep(1)
def test_set_valid_name_on_invalid_input(self):
... | setUp | identifier_name |
test_unit.py | # This doesn't work- not updated with eventmaster.py updates
# TODO: Fix This :)
# Import Libraries
import eventmaster
import time
import random
import sys
import unittest
import sys
class InputsTestCase(unittest.TestCase):
def setUp(self):
self.s3 = E2S3.E2S3Switcher()
self.s3.set_verbose(0)
... |
print unittest.main()
sys.exit()
| MyObject = type('MyObject', (object,), {})
self.assertEqual(self.s3.get_input(0).set_Name(MyObject), None) | identifier_body |
test_unit.py | # This doesn't work- not updated with eventmaster.py updates
# TODO: Fix This :)
# Import Libraries
import eventmaster
import time
import random
import sys
import unittest
import sys
class InputsTestCase(unittest.TestCase):
def setUp(self):
self.s3 = E2S3.E2S3Switcher()
self.s3.set_verbose(0)
... | while self.s3.is_ready() != 1: time.sleep(1)
def test_set_valid_name_on_invalid_input(self):
test_str = "PYTEST-{0!s}".format(random.randint(1,10))
self.assertRaises(ValueError, lambda: self.s3.get_input(99).set_Name(test_str))
def test_set_valid_name_on_valid_input(self):
test... | self.s3.set_CommsXML_Port(9876)
if not self.s3.connect(): return -1 | random_line_split |
certificatesController.js | angular.module("admin-app").controller("CertificatesController", CertificatesController);
CertificatesController.$inject = ['$scope', '$state', 'urls', 'HttpRequest', 'toastr', 'validators', 'SweetAlert'];
function CertificatesController($scope, $state, urls, HttpRequest, toastr, validators, SweetAlert) {
$scope.up... | });
}
} | SweetAlert.swal("Cancelado", "Se canceló la acción", "error");
}
| conditional_block |
certificatesController.js | angular.module("admin-app").controller("CertificatesController", CertificatesController);
CertificatesController.$inject = ['$scope', '$state', 'urls', 'HttpRequest', 'toastr', 'validators', 'SweetAlert'];
function | ($scope, $state, urls, HttpRequest, toastr, validators, SweetAlert) {
$scope.updateCertificate = updateCertificate;
var url = urls.BASE_API + '/enrollments/certificates_requested';
var promise = HttpRequest.send("GET", url);
promise.then(function (response) {
$scope.enrollments = response;
var $conte... | CertificatesController | identifier_name |
certificatesController.js | angular.module("admin-app").controller("CertificatesController", CertificatesController); |
function CertificatesController($scope, $state, urls, HttpRequest, toastr, validators, SweetAlert) {
$scope.updateCertificate = updateCertificate;
var url = urls.BASE_API + '/enrollments/certificates_requested';
var promise = HttpRequest.send("GET", url);
promise.then(function (response) {
$scope.enrollm... |
CertificatesController.$inject = ['$scope', '$state', 'urls', 'HttpRequest', 'toastr', 'validators', 'SweetAlert']; | random_line_split |
certificatesController.js | angular.module("admin-app").controller("CertificatesController", CertificatesController);
CertificatesController.$inject = ['$scope', '$state', 'urls', 'HttpRequest', 'toastr', 'validators', 'SweetAlert'];
function CertificatesController($scope, $state, urls, HttpRequest, toastr, validators, SweetAlert) {
$scope.up... | toastr.error("Hubo un error");
});
} else {
SweetAlert.swal("Cancelado", "Se canceló la acción", "error");
}
});
}
} | {
SweetAlert.swal({
title: "Estás seguro?",
text: "Esta acción es irreversible!",
type: "warning",
showCancelButton: true,
cancelButtonClass: "button-ln",
confirmButtonClass: "button-bg primary",
confirmButtonText: "Si",
cancelButtonText: "No",
closeOnConfirm: f... | identifier_body |
SiteTools.tsx | import * as React from "react"
import * as ReactDOM from "react-dom"
import { FeedbackPrompt } from "./Feedback"
import { ScrollDirection, useScrollDirection } from "./hooks"
import {
NewsletterSubscription,
NewsletterSubscriptionForm,
NewsletterSubscriptionContext,
} from "./NewsletterSubscription"
const ... | }`}
>
<NewsletterSubscription
context={NewsletterSubscriptionContext.Floating}
/>
<FeedbackPrompt />
</div>
)
}
export const runSiteTools = () => {
ReactDOM.render(
<SiteTools />,
document.querySelector(`.${SITE_TOO... | className={`hide-wrapper${
(scrollDirection === ScrollDirection.Down && " hide") || "" | random_line_split |
gyptest.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__doc__ = """
gyptest.py -- test runner for GYP tests.
"""
import os
import optparse
import shlex
import subprocess
import sys
class Comma... | (self, dictionary={}):
self.subst_dictionary(dictionary)
def subst_dictionary(self, dictionary):
self._subst_dictionary = dictionary
def subst(self, string, dictionary=None):
"""
Substitutes (via the format operator) the values in the specified
dictionary into the specified command.
The c... | __init__ | identifier_name |
gyptest.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__doc__ = """
gyptest.py -- test runner for GYP tests.
"""
import os
import optparse
import shlex
import subprocess
import sys
class Comma... | a string. (It's probably a Python function to be executed.)
"""
if dictionary is None:
dictionary = self._subst_dictionary
if dictionary:
try:
string = string % dictionary
except TypeError:
pass
return string
def display(self, command, stdout=None, stderr=None):... | """
Executor class for commands, including "commands" implemented by
Python functions.
"""
verbose = True
active = True
def __init__(self, dictionary={}):
self.subst_dictionary(dictionary)
def subst_dictionary(self, dictionary):
self._subst_dictionary = dictionary
def subst(self, string, dict... | identifier_body |
gyptest.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__doc__ = """
gyptest.py -- test runner for GYP tests.
"""
import os
import optparse
import shlex
import subprocess
import sys
class Comma... |
else:
passed.append(test)
if not opts.quiet:
def report(description, tests):
if tests:
if len(tests) == 1:
sys.stdout.write("\n%s the following test:\n" % description)
else:
fmt = "\n%s the following %d tests:\n"
sys.stdout.write(fmt % (descripti... | failed.append(test) | conditional_block |
gyptest.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__doc__ = """
gyptest.py -- test runner for GYP tests.
"""
import os
import optparse
import shlex
import subprocess
import sys
class Comma... | self.fp = fp
def write(self, arg):
self.fp.write(arg)
self.fp.flush()
def __getattr__(self, attr):
return getattr(self.fp, attr)
sys.stdout = Unbuffered(sys.stdout)
sys.stderr = Unbuffered(sys.stderr)
def is_test_name(f):
return f.startswith('gyptest') and f.endswith('.py')
def find_all_gypte... |
class Unbuffered(object):
def __init__(self, fp): | random_line_split |
atom.ts | // Here we collect our atom-related logic
const parseAtomFeedWithFeedParser = require('node-feedparser');
const xml2js = require('xml2js').parseString;
import { wrapRawFeedInfo, ArticleList } from '../data/wrappers';
const enrichFeed = require('./atom-enrichment');
export interface Article {
getAuthor(): string;... | (input:string,
callback:(error:string,ret)=>void
) {
// We are going to do three things:
// 1. Parse the XML feed with node-feedparser
// 2. Also convert the XML feed into a JSON object
// 3. Pick and choose some fields from the JSON
// to enrich the data extracted by the primary parser
t... | parseAtomFeed | identifier_name |
atom.ts | // Here we collect our atom-related logic
const parseAtomFeedWithFeedParser = require('node-feedparser');
const xml2js = require('xml2js').parseString;
import { wrapRawFeedInfo, ArticleList } from '../data/wrappers';
const enrichFeed = require('./atom-enrichment');
export interface Article { | getSummary(): string;
getImage(): string;
}
export interface FeedInfo {
getSite(): Article;
getItems(): ArticleList;
}
// This is the entry point for parsing an atom feed.
export function parseAtomFeed(input:string,
callback:(error:string,ret)=>void
) {
// We are going to do three things:
... | getAuthor(): string;
getDate(): Date;
getDescription(): string;
getLink(): string;
getTitle(): string | random_line_split |
atom.ts | // Here we collect our atom-related logic
const parseAtomFeedWithFeedParser = require('node-feedparser');
const xml2js = require('xml2js').parseString;
import { wrapRawFeedInfo, ArticleList } from '../data/wrappers';
const enrichFeed = require('./atom-enrichment');
export interface Article {
getAuthor(): string;... | else {
enrichFeed(feed, json);
callback(null, wrapRawFeedInfo(feed));
}
})
}
});
} catch (e) {
callback(e.toString(), null);
}
};
| {
callback(error, null);
} | conditional_block |
atom.ts | // Here we collect our atom-related logic
const parseAtomFeedWithFeedParser = require('node-feedparser');
const xml2js = require('xml2js').parseString;
import { wrapRawFeedInfo, ArticleList } from '../data/wrappers';
const enrichFeed = require('./atom-enrichment');
export interface Article {
getAuthor(): string;... | });
} catch (e) {
callback(e.toString(), null);
}
}
;
| {
// We are going to do three things:
// 1. Parse the XML feed with node-feedparser
// 2. Also convert the XML feed into a JSON object
// 3. Pick and choose some fields from the JSON
// to enrich the data extracted by the primary parser
try {
parseAtomFeedWithFeedParser(input, (error,... | identifier_body |
aptpreferences.py | import os
from twisted.python.compat import iteritems
from landscape.lib.fs import read_text_file
from landscape.constants import APT_PREFERENCES_SIZE_LIMIT
from landscape.client.monitor.plugin import DataWatcher
class AptPreferences(DataWatcher):
"""
Report the system APT preferences configuration.
""... | return self.exchange(urgent=True) | identifier_body | |
aptpreferences.py | import os
from twisted.python.compat import iteritems
from landscape.lib.fs import read_text_file
from landscape.constants import APT_PREFERENCES_SIZE_LIMIT
from landscape.client.monitor.plugin import DataWatcher
class AptPreferences(DataWatcher):
"""
Report the system APT preferences configuration.
""... |
if data == {}:
return None
item_size_limit = self.size_limit // len(data.keys())
for filename, contents in iteritems(data):
if len(filename) + len(contents) > item_size_limit:
truncated_contents_size = item_size_limit - len(filename)
dat... | for entry in os.listdir(preferences_directory):
filename = os.path.join(preferences_directory, entry)
if os.path.isfile(filename):
data[filename] = read_text_file(filename) | conditional_block |
aptpreferences.py | import os
from twisted.python.compat import iteritems
from landscape.lib.fs import read_text_file
from landscape.constants import APT_PREFERENCES_SIZE_LIMIT
from landscape.client.monitor.plugin import DataWatcher
class AptPreferences(DataWatcher):
"""
Report the system APT preferences configuration.
""... | message_key = "data"
run_interval = 900 # 15 minutes
scope = "package"
size_limit = APT_PREFERENCES_SIZE_LIMIT
def __init__(self, etc_apt_directory="/etc/apt"):
self._etc_apt_directory = etc_apt_directory
def get_data(self):
"""Return a C{dict} mapping APT preferences files to... |
persist_name = "apt-preferences"
message_type = "apt-preferences" | random_line_split |
aptpreferences.py | import os
from twisted.python.compat import iteritems
from landscape.lib.fs import read_text_file
from landscape.constants import APT_PREFERENCES_SIZE_LIMIT
from landscape.client.monitor.plugin import DataWatcher
class AptPreferences(DataWatcher):
"""
Report the system APT preferences configuration.
""... | (self):
"""Return a C{dict} mapping APT preferences files to their contents.
If no APT preferences configuration is set at all on the system, then
simply return C{None}
"""
data = {}
preferences_filename = os.path.join(self._etc_apt_directory,
... | get_data | identifier_name |
lib.rs | extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_proto;
extern crate tokio_service;
use futures::{future, Future};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_core::net::TcpStream;
use tokio_core::reactor::... | impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> for CollatzProto {
type Request = String;
type Response = String;
type Transport = Framed<T, CollatzCodec>;
type BindTransport = Result<Self::Transport, io::Error>;
fn bind_transport(&self, io: T) -> Self::BindTransport {
... | }
| random_line_split |
lib.rs | extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_proto;
extern crate tokio_service;
use futures::{future, Future};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_core::net::TcpStream;
use tokio_core::reactor::... |
let newline = buf[4..].iter().position(|b| *b==b'\n');
if let Some(n) = newline {
let line = buf.split_to(n + 4);
buf.split_to(1);
let request_id = io::Cursor::new(&line[0..4]).get_u32::<BigEndian> ();
return match str::from_utf8(&line.as_ref()[4..]) {
... | {
return Ok(None);
} | conditional_block |
lib.rs | extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_proto;
extern crate tokio_service;
use futures::{future, Future};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_core::net::TcpStream;
use tokio_core::reactor::... | (&self, io: T) -> Self::BindTransport {
Ok(io.framed(CollatzCodec))
}
}
impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> for CollatzProto {
type Request = String;
type Response = String;
type Transport = Framed<T, CollatzCodec>;
type BindTransport = Result<Self::Tran... | bind_transport | identifier_name |
AlertTitle.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefaul... | /**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object
} : void 0;
var _default = AlertTitle;
exports.default = _default; | random_line_split | |
index.test.js | 'use strict';
var job = require('../index.js'),
File = require('vinyl');
describe('gulp-job', sandbox(function () {
describe('pre', function () {
var buffer;
beforeEach(function () {
buffer = job.prototype.pre();
});
it('returns a buffer', function () {
buffer.should.be.an.instanc... |
file = new File({
path: '/test/file.js',
contents: new Buffer('-middle-')
});
job.prototype.wrap(file);
});
it('wraps the file', function () {
file.contents.toString().should.equal('foo-middle-bar');
});
});
describe('funnel', function () {
var callback,
... | var file;
beforeEach(function () {
sandbox.stub(job.prototype, 'pre').returns(new Buffer('foo'));
sandbox.stub(job.prototype, 'post').returns(new Buffer('bar')); | random_line_split |
check_rec_stream.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import time
__author__ = 'mah'
__email__ = 'andrew.makhotin@gmail.com'
import MySQLdb as mdb
import sys
import ConfigParser
import logging
import logging.handlers
import re
import os
from ffprobe import FFProbe
#### LOG ###
logger = logging.getLogger('Logging for check_s... | return False
logger.debug('status: %s, %s', status, pls)
return status #status
def restartchid(ch):
'''
Restart ch i
:param ch: (89L, 326L, u'/var/lastxdays/326/5a9f3bad8adba3a5')
:return:
'''
logger.warning('to do restart ch:%s', ch[1])
try:
con = md... | '''
Check sound in ffprobe class and return status sound restart ch pid if needed
:param src: pls.m3u8
:return: status sound in ch
'''
status = {}
meta = False
try:
meta = FFProbe(pls)
except IOError, e:
logger.error('====Error:%s', e)
return 'nofile'
if met... | identifier_body |
check_rec_stream.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import time
__author__ = 'mah'
__email__ = 'andrew.makhotin@gmail.com'
import MySQLdb as mdb
import sys
import ConfigParser
import logging
import logging.handlers
import re
import os
from ffprobe import FFProbe
#### LOG ###
logger = logging.getLogger('Logging for check_s... |
logger.debug('status: %s, %s', status, pls)
return status #status
def restartchid(ch):
'''
Restart ch i
:param ch: (89L, 326L, u'/var/lastxdays/326/5a9f3bad8adba3a5')
:return:
'''
logger.warning('to do restart ch:%s', ch[1])
try:
con = mdb.connect(dbcon['dbhost'], dbcon[... | return False | conditional_block |
check_rec_stream.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import time
__author__ = 'mah'
__email__ = 'andrew.makhotin@gmail.com'
import MySQLdb as mdb
import sys
import ConfigParser
import logging
import logging.handlers
import re
import os
from ffprobe import FFProbe
#### LOG ###
logger = logging.getLogger('Logging for check_s... | if checksound(ch[2], ch[1]) != 'nofile':
restartchid(ch)
if __name__ == '__main__':
while 1:
try:
main()
except KeyboardInterrupt:
sys.exit(0)
#logger.info('waiting...')
time.sleep(30) | logger.warning('not audio in %s, %s', checksound(ch[2], ch[1]), ch[1])
#TODO if not video do not restart ch | random_line_split |
check_rec_stream.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import time
__author__ = 'mah'
__email__ = 'andrew.makhotin@gmail.com'
import MySQLdb as mdb
import sys
import ConfigParser
import logging
import logging.handlers
import re
import os
from ffprobe import FFProbe
#### LOG ###
logger = logging.getLogger('Logging for check_s... | ():
if not os.path.isdir('/run/sound'):
os.mkdir('/run/sound')
for id in dbcon['service_id'].split(','):
chids = channelsinsrv(id)
logger.info('service: %s', id)
'''
chid is:[0] [1] [2]
(service_id, btv_channel_id, file_name)
... | main | identifier_name |
neurons_layer.rs | uronsLayer {
pub fn | (dim_neurons: uint, nb_neurons: uint) -> NeuronsLayer{
let mut neurons: Vec<Neuron> = Vec::new();
for _ in range(0u, nb_neurons)
{
let n: Neuron = Neuron::new(dim_neurons);
neurons.push(n);
}
return NeuronsLayer {
dim_neurons:... | new | identifier_name |
neurons_layer.rs | Layer {
pub fn new(dim_neurons: uint, nb_neurons: uint) -> NeuronsLayer{
let mut neurons: Vec<Neuron> = Vec::new();
for _ in range(0u, nb_neurons)
{
let n: Neuron = Neuron::new(dim_neurons);
neurons.push(n);
}
return NeuronsLayer {
... |
pub fn get_weights(&mut self) -> Vec<Vec<f64>> {
let mut weights: Vec<Vec<f64>> = Vec::new();
let mut it = self.neurons.iter_mut();
loop {
match it.next() {
Some(ref mut n) => {
weights.push(n.get_weights().clone());
}
... | {
let mut activations: Vec<f64> = Vec::new();
let mut it = self.neurons.iter_mut();
loop {
match it.next() {
Some(ref mut n) => {
activations.push(n.get_activation());
}
None => { break }
}
}
... | identifier_body |
neurons_layer.rs | uronsLayer {
pub fn new(dim_neurons: uint, nb_neurons: uint) -> NeuronsLayer{
let mut neurons: Vec<Neuron> = Vec::new();
for _ in range(0u, nb_neurons)
{
let n: Neuron = Neuron::new(dim_neurons);
neurons.push(n);
}
return NeuronsLayer... |
// propagation
pub fn propagate(&mut self, input: &[f64]) {
let mut it = self.neurons.iter_mut();
loop {
match it.next() {
Some(ref mut n) => {
n.propagate(input);
}
None => { break }
}
... | random_line_split | |
lib.rs |
extern crate pcd8544_sys;
extern crate wiringpi;
use wiringpi::WiringPi;
use wiringpi::pin::Pin;
// We take a WiringPi as a parameter to ensure that wiringpi was setup prior to this function call
#[allow(unused_variables)]
pub fn init<P: Pin>(pi: &WiringPi<P>, sclk: u8, din: u8, dc: u8, cs: u8, rst: u8, contrast: u8... | {
unsafe {
pcd8544_sys::LCDclear();
}
} | identifier_body | |
lib.rs |
extern crate pcd8544_sys;
extern crate wiringpi;
use wiringpi::WiringPi;
use wiringpi::pin::Pin;
// We take a WiringPi as a parameter to ensure that wiringpi was setup prior to this function call
#[allow(unused_variables)]
pub fn init<P: Pin>(pi: &WiringPi<P>, sclk: u8, din: u8, dc: u8, cs: u8, rst: u8, contrast: u8... | else { pcd8544_sys::BLACK } );
}
}
pub fn display() {
unsafe {
pcd8544_sys::LCDdisplay();
}
}
pub fn clear() {
unsafe {
pcd8544_sys::LCDclear();
}
}
| { pcd8544_sys::WHITE } | conditional_block |
lib.rs |
extern crate pcd8544_sys;
extern crate wiringpi;
use wiringpi::WiringPi;
use wiringpi::pin::Pin;
// We take a WiringPi as a parameter to ensure that wiringpi was setup prior to this function call
#[allow(unused_variables)]
pub fn init<P: Pin>(pi: &WiringPi<P>, sclk: u8, din: u8, dc: u8, cs: u8, rst: u8, contrast: u8... | () {
unsafe {
pcd8544_sys::LCDdisplay();
}
}
pub fn clear() {
unsafe {
pcd8544_sys::LCDclear();
}
}
| display | identifier_name |
lib.rs | extern crate pcd8544_sys;
extern crate wiringpi;
use wiringpi::WiringPi; | // We take a WiringPi as a parameter to ensure that wiringpi was setup prior to this function call
#[allow(unused_variables)]
pub fn init<P: Pin>(pi: &WiringPi<P>, sclk: u8, din: u8, dc: u8, cs: u8, rst: u8, contrast: u8) {
unsafe {
pcd8544_sys::LCDInit(sclk, din, dc, cs, rst, contrast);
}
}
pub fn set... | use wiringpi::pin::Pin;
| random_line_split |
gdt.rs | use core::ptr::RawPtr;
use core::mem::{size_of, transmute};
use core;
use cpu::DtReg;
use kernel::heap;
define_flags!(GdtAccess: u8 {
ACCESSED = 1 << 0,
EXTEND = 1 << 1,
CONFORM = 1 << 2,
CODE = 1 << 3,
STORAGE = 1 << 4, // not TSS
DPL0 = 0 << 5,
DPL1 = 1 << 5,
DPL2 = 2 << 5,
... | (&self) {
unsafe {
asm!("lgdt [$0]" :: "r"(self) :: "intel");
}
}
}
| load | identifier_name |
gdt.rs | use core::ptr::RawPtr;
use core::mem::{size_of, transmute};
use core;
use cpu::DtReg;
use kernel::heap;
define_flags!(GdtAccess: u8 {
ACCESSED = 1 << 0,
EXTEND = 1 << 1,
CONFORM = 1 << 2,
CODE = 1 << 3,
STORAGE = 1 << 4, // not TSS
DPL0 = 0 << 5,
DPL1 = 1 << 5,
DPL2 = 2 << 5,
... | unsafe {
entry.access |= PRESENT.get();
*self.table.offset(n as int) = entry;
}
}
pub unsafe fn disable(&self, n: uint) {
(*self.table.offset(n as int)).access &= !PRESENT.get();
}
pub fn load(&self, code: u16, data: u16, local: u16) {
unsafe {
... | pub fn enable(&self, n: uint, mut entry: GdtEntry) { | random_line_split |
gui_charts.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from multiprocessing import pool
import numpy as np
import stat_functions as stat
from scipy import stats as scstats
from gui import gui_functions as guif
import os
import functions as fu
class process_charts(ttk.Frame):
de... | N,k=x.shape
grid_n=int(2*grid_range/grid_step)
grid=np.array([i*grid_step-grid_range for i in range(grid_n)]).reshape((1,grid_n))
ones=np.ones((N,1))
x_u=np.concatenate((ones,x>=grid),1)
x_l=np.concatenate((x<grid,ones),1)
grid=np.concatenate((grid.flatten(),[grid[0,-1]+grid_step]))
histogram=np.sum((x_u*x_l),0)... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.