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 |
|---|---|---|---|---|
tailcut_delta_psi.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... |
def __call__(self, threshold_list):
self.call_number += 1
aggregated_score = float('inf')
try:
high_threshold = float(threshold_list[0])
low_threshold = float(threshold_list[1])
if low_threshold > high_threshold:
# To avoid useless comp... | lf.call_number = 0
# Init the wavelet class
self.cleaning_algorithm = Tailcut()
# Make the image list
self.input_files = input_files
self.max_num_img = max_num_img
self.aggregation_method = aggregation_method # "mean" or "median"
print("aggregation method:", ... | identifier_body |
dataset.py | import string, copy
def joinHeaders(first, second, joined, on):
joined.headers = first.headers[:]
mappedHeaders = {}
for header in second.headers:
if header == on:
continue
i = 0
newHeader = header
while newHeader in first.headers:
newHeader = '{0}_{1}'.format(newHeader, i)
i += 1
if i > 0:
ma... |
def join(self, other, on):
"""Join self dataset with another dataset, creating a new dataset.
The original datasets remain unchanged.
The third argument is the header on which to join"""
# check for correct join
if not (on in self.headers or on in other.headers):
print "Error: header '{0}' not found in both... | outfile.close()
| random_line_split |
dataset.py | import string, copy
def joinHeaders(first, second, joined, on):
joined.headers = first.headers[:]
mappedHeaders = {}
for header in second.headers:
if header == on:
continue
i = 0
newHeader = header
while newHeader in first.headers:
newHeader = '{0}_{1}'.format(newHeader, i)
i += 1
if i > 0:
ma... |
def append(self, other, ensureFilled = True):
"""Append rows of another dataset to this one, leaving the other dataset unchanged"""
self.rows.extend(other.rows)
self.headers.extend([x for x in other.headers if not x in self.headers])
if(ensureFilled):
self.ensureFilled()
return self
| for header in self.headers:
if not header in row:
row[header] = None | conditional_block |
dataset.py | import string, copy
def joinHeaders(first, second, joined, on):
joined.headers = first.headers[:]
mappedHeaders = {}
for header in second.headers:
if header == on:
continue
i = 0
newHeader = header
while newHeader in first.headers:
newHeader = '{0}_{1}'.format(newHeader, i)
i += 1
if i > 0:
ma... | (self, other, on):
"""Join self dataset with another dataset, creating a new dataset.
The original datasets remain unchanged.
The third argument is the header on which to join"""
# check for correct join
if not (on in self.headers or on in other.headers):
print "Error: header '{0}' not found in both collection... | join | identifier_name |
dataset.py | import string, copy
def joinHeaders(first, second, joined, on):
joined.headers = first.headers[:]
mappedHeaders = {}
for header in second.headers:
if header == on:
continue
i = 0
newHeader = header
while newHeader in first.headers:
newHeader = '{0}_{1}'.format(newHeader, i)
i += 1
if i > 0:
ma... |
def export(self, filename):
outfile = file(filename, 'w')
outfile.write(','.join(self.headers))
for row in self.rows:
outfile.write('\n')
outfile.write(','.join([row[x] for x in self.headers]))
outfile.close()
def join(self, other, on):
"""Join self dataset with another dataset, creating a ne... | self.headers = []
self.rows = []
try:
infile = file(filename, 'r')
if header:
self.headers = infile.readline().strip().split(separator)
for line in infile:
row = line.strip().split(separator)
if not header and not self.headers:
self.headers = ["V{0}".format(i) for i in range(len(row))]
... | identifier_body |
BendpointSnapping.js | import {
assign,
forEach,
isArray
} from 'min-dash';
var abs= Math.abs,
round = Math.round;
var TOLERANCE = 10;
export default function BendpointSnapping(eventBus) {
function snapTo(values, value) {
if (isArray(values)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <... |
// snap
sx = snapTo(snapPoints.vertical, x);
sy = snapTo(snapPoints.horizontal, y);
// correction x/y
var cx = (x - sx),
cy = (y - sy);
// update delta
assign(event, {
dx: event.dx - cx,
dy: event.dy - cy,
x: sx,
y: sy
});
});
// bendpoint snapp... | {
return;
} | conditional_block |
BendpointSnapping.js | import {
assign,
forEach,
isArray
} from 'min-dash';
var abs= Math.abs,
round = Math.round;
var TOLERANCE = 10;
export default function BendpointSnapping(eventBus) {
function snapTo(values, value) |
return value;
}
function mid(element) {
if (element.width) {
return {
x: round(element.width / 2 + element.x),
y: round(element.height / 2 + element.y)
};
}
}
// connection segment snapping //////////////////////
function getConnectionSegmentSnaps(context) {
v... | {
if (isArray(values)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <= TOLERANCE) {
return values[i];
}
} else {
values = +values;
var rem = value % values;
if (rem < TOLERANCE) {
return value - rem;
}
if (rem > values - TOLE... | identifier_body |
BendpointSnapping.js | import {
assign,
forEach,
isArray
} from 'min-dash';
var abs= Math.abs,
round = Math.round;
var TOLERANCE = 10;
export default function BendpointSnapping(eventBus) {
function snapTo(values, value) {
if (isArray(values)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <... |
var referenceWaypoints = [
waypoints[segmentStartIndex - 1],
segmentStart,
segmentEnd,
waypoints[segmentEndIndex + 1]
];
if (segmentStartIndex < 2) {
referenceWaypoints.unshift(mid(connection.source));
}
if (segmentEndIndex > waypoints.length - 3) {
referenceWa... | return snapPoints;
} | random_line_split |
BendpointSnapping.js | import {
assign,
forEach,
isArray
} from 'min-dash';
var abs= Math.abs,
round = Math.round;
var TOLERANCE = 10;
export default function BendpointSnapping(eventBus) {
function snapTo(values, value) {
if (isArray(values)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <... | (context) {
var snapPoints = context.snapPoints,
waypoints = context.connection.waypoints,
bendpointIndex = context.bendpointIndex;
if (snapPoints) {
return snapPoints;
}
var referenceWaypoints = [ waypoints[bendpointIndex - 1], waypoints[bendpointIndex + 1] ];
context.snap... | getBendpointSnaps | identifier_name |
setup.py | from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw workaround for _ftime if the msv... | (parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
libs = get_mathlibs()
tc = testcode_wincrypt()... | configuration | identifier_name |
setup.py | from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw workaround for _ftime if the msv... |
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
| return """\
/* check to see if _WIN32 is defined */
int main(int argc, char *argv[])
{
#ifdef _WIN32
return 0;
#else
return 1;
#endif
}
""" | identifier_body |
setup.py | from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw workaround for _ftime if the msv... | from numpy.distutils.core import setup
setup(configuration=configuration) | conditional_block | |
setup.py | from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw workaround for _ftime if the msv... | except ImportError:
have_cffi = False
if have_cffi:
#create the dll/so for the cffi version
if sys.platform == 'win32':
libs.append('Advapi32')
defs.append(('_MTRAND_DLL',None))
config.add_shared_library('_mtrand',
sources=[join('m... | try:
import cffi
have_cffi = True | random_line_split |
16835_H2.rs | 08E+000
| 0.280 4.0103836E+000 2.8828108E+000 2.3853471E+000 1.8648334E+000 1.2753470E+000 1.0055252E+000
0.300 2.8487566E+000 2.2245429E+000 1.9282485E+000 1.5859742E+000 1.0897597E+000 8.9366448E-001
0.320 2.0230498E+000 1.5607424E+000 1.4466788E+000 1.2987298E+000 9.3179417E-001 8.1396568E-001
0.340 1.5434318E+000 1.351621... | 0.200 4.6951294E+000 3.5387561E+000 2.9914527E+000 2.4170172E+000 1.9933550E+000 1.6257334E+000
0.220 5.5433970E+000 3.4664059E+000 2.8443663E+000 2.3755868E+000 1.8310739E+000 1.4639518E+000
0.240 4.2906198E+000 2.8333371E+000 2.5657334E+000 2.2435493E+000 1.6571624E+000 1.3000077E+000
0.260 3.8741798E+000 2.860464... | random_line_split |
map.ts | import $ from 'jquery';
import Vue from "vue";
import { BootstrapVue } from "bootstrap-vue";
import { FacilMap } from "../lib";
import "./bootstrap.scss";
import "bootstrap-vue/dist/bootstrap-vue.css";
import withRender from "./map.vue";
import "./map.scss";
import { decodeQueryString, encodeQueryString } from "facilma... | }
}
new Vue(withRender({
el: "#loading",
data: {
padId: initialPadId,
padName: undefined,
baseUrl,
toolbox: toBoolean(queryParams.toolbox, true),
search: toBoolean(queryParams.search, true),
autofocus: toBoolean(queryParams.autofocus, parent === window),
legend: toBoolean(queryParams.legend, true),
... | const hash = encodeQueryString(hashParams);
history.replaceState(null, "", baseUrl + encodeURIComponent(initialPadId || "") + (query ? "?" + query : "") + "#" + hash); | random_line_split |
archives.py | import logging, os, json
import search.archive
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
logging.info('**** new Singleton instance')
retur... | return
arch = [d for d in os.listdir(self.archives_dir) if os.path.isdir(os.path.join(self.archives_dir, d))]
self.data = {}
for a in arch:
logging.info("loading " + a)
# archive_path = os.path.join(self.archives_dir, a)
self.data[a] = self.load_archive(self.archives_dir, a)
logging.info("done... | logging.error(" -- current cwd is: " + os.getcwd())
| random_line_split |
archives.py | import logging, os, json
import search.archive
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
logging.info('**** new Singleton instance')
retur... |
self.data = {}
self.loaded = False
logging.info('loading archives...')
self.load()
logging.info('done.')
def load(self):
if self.loaded:
return
if not os.path.isdir(self.archives_dir):
logging.error("Archives:: the path - " + self.archives_dir + " - is not a valid directory. Aborting.")
... | self.archives_dir = archives_dir | conditional_block |
archives.py | import logging, os, json
import search.archive
class Singleton(type):
_instances = {}
def | (cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
logging.info('**** new Singleton instance')
return cls._instances[cls]
class Archives(metaclass=Singleton):
def __init__(self, archives_dir=None):
if ... | __call__ | identifier_name |
archives.py | import logging, os, json
import search.archive
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
logging.info('**** new Singleton instance')
retur... |
self.loaded = True
def load_archive(self, archive_dir, archive_name):
if not os.path.isdir(archive_dir):
logging.error("Archives:: the path - " + archive_dir + " - is not a valid directory. Aborting.")
return
archive = search.archive.Archive(archive_dir)
archive.load(archive_name)
return archiv... | if self.loaded:
return
if not os.path.isdir(self.archives_dir):
logging.error("Archives:: the path - " + self.archives_dir + " - is not a valid directory. Aborting.")
logging.error(" -- current cwd is: " + os.getcwd())
return
arch = [d for d in os.listdir(self.archives_dir) if os.path.isdir(os.path.j... | identifier_body |
move_patients_from_data_sets_to_collection.js | db.patients.remove({})
db.getCollection('data_sets').find({}).forEach(function(doc) {
var patientsAdded = 0;
if (!doc["patients"]) return;
for (var i = 0; i < doc["patients"].length; i++) {
var patient = doc["patients"][i];
var samples = [];
for (var s = 0; s < patient["sample_lab... | samples: samples,
collaborations: doc.collaborations
});
patientsAdded++;
}
print(patientsAdded);
})
// db.getCollection("data_sets").update({}, {$unset: {patients: 1, sample_labels: 1}}, {multi: true}) | random_line_split | |
move_patients_from_data_sets_to_collection.js | db.patients.remove({})
db.getCollection('data_sets').find({}).forEach(function(doc) {
var patientsAdded = 0;
if (!doc["patients"]) return;
for (var i = 0; i < doc["patients"].length; i++) |
print(patientsAdded);
})
// db.getCollection("data_sets").update({}, {$unset: {patients: 1, sample_labels: 1}}, {multi: true})
| {
var patient = doc["patients"][i];
var samples = [];
for (var s = 0; s < patient["sample_labels"].length; s++) {
samples.push({
sample_label: patient["sample_labels"][s],
data_set_id: doc._id,
});
}
db.getCollection("patie... | conditional_block |
urls.py | """
Copyright 2008-2009 Serge Matveenko
This file is part of Picket.
Picket 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 later version.
Picket is dist... |
## bug fields updates
(r'^bug/(?P<bug_id>\d+)/update_handler_status/$', 'update_field',
{'form_class': 'AssignStatusForm',},
'picket-bug-update-handler-status',),
(r'^bug/(?P<bug_id>\d+)/move/$', 'update_field',
{'form_class': 'BugMoveForm',},
'picket-bug-move',),
... | 'picket-bug-update',), | random_line_split |
main.rs | // main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | > {
args: clap::ArgMatches<'a>,
textures: SpriteTextures,
window: &'a mut PistonWindow,
drag_ctrl: &'a mut DragController,
scene: &'a mut Scene<Texture<GLResources>>,
sprite_map: &'a mut collections::HashMap<Pos, Uuid>,
game: &'a mut Game,
rng: &'a mut StdRng,
}
struct SpriteTextures {
white_piece: T... | eContext<'a | identifier_name |
main.rs | // main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... |
fn
load_texture(texture_data: &[u8], factory: &mut GLFactory) -> errors::Result<Texture<GLResources>> {
let texture_image = try!(piston_image::load_from_memory_with_format(texture_data,
piston_image::ImageFormat::PNG))
.re... | let mut window: PistonWindow =
try!(WindowSettings::new("kōnane", [TILE_SIZE * 10, TILE_SIZE * 10]).exit_on_esc(true).build());
let textures = SpriteTextures {
white_piece: try!(load_texture(WHITE_PIECE_DATA, &mut window.factory)),
black_piece: try!(load_texture(BLACK_PIECE_DATA, &mut window.factory)),
... | identifier_body |
main.rs | // main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | e {
}
}
}
Ok(cxt)
}
fn run(cxt: GameContext) -> errors::Result<()> {
let mut events = cxt.window.events();
while let Some(event) = events.next(cxt.window) {
cxt.scene.event(&event);
}
Ok(())
}
| } els | conditional_block |
main.rs | // main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | use drag_controller::*;
#[macro_use]
extern crate clap;
extern crate rand;
use rand::{Rng, StdRng};
const TILE_SIZE: u32 = 75;
const WHITE_PIECE_DATA: &'static [u8] = include_bytes!("../resources/white_piece.png");
const BLACK_PIECE_DATA: &'static [u8] = include_bytes!("../resources/black_piece.png");
const EMPTY_PI... | use piston_image::GenericImage;
use gfx_device_gl::{Factory as GLFactory, Resources as GLResources};
use piston_window::*;
use sprite::*; | random_line_split |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib 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 ap... |
// TESTS //
// The function returns a number...
{
mean( 8, 2 ); // $ExpectType number
}
// The function does not compile if provided values other than two numbers...
{
mean( true, 3 ); // $ExpectError
mean( false, 2 ); // $ExpectError
mean( '5', 1 ); // $ExpectError
mean( [], 1 ); // $ExpectError
mean( {}, 2 ... |
import mean = require( './index' ); | random_line_split |
normalizeOptions.js | 'use strict';
// Adapted from https://github.com/tleunen/babel-plugin-module-resolver/blob/master/src/normalizeOptions.js
const path = require('path');
const { createSelector } = require('reselect');
const defaultExtensions = ['.js'];
const normalizeRoots = (optsRoot, cwd) => {
return Object.keys(optsRoot).reduce... | module.exports = normalizeOptions; | }
);
| random_line_split |
L0PublishMandatoryUpdate.ts | import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path'); |
const mockery = require('mockery');
const nock = require('nock');
let taskPath = path.join(__dirname, '..', 'appcenterdistribute.js');
let tmr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
tmr.setInput('serverEndpoint', 'MyTestEndpoint');
tmr.setInput('appSlug', 'testuser/testapp');
tmr.setInput('app', '... | import fs = require('fs');
import azureBlobUploadHelper = require('../azure-blob-upload-helper');
import { basicSetup, mockFs, mockAzure } from './TestHelpers'; | random_line_split |
next-tab-component.ts | import {Directive, Input, Host, HostListener, HostBinding} from "angular2/core";
import {AngularNavTab} from "./tab-directive";
import {AngularNavTabs} from "./tabs-component";
import {TabInterface} from "../core";
@Directive({
selector: "[anNextTab]"
})
export class NextTab {
tab: AngularNavTab;
@HostBind... | else {
tabs = this.anTabs.list.tabs.filter(tab => tab.key === value.id);
}
if (tabs.length > 0) {
this.tab = tabs[0];
}
}
} | {
tabs = this.anTabs.list.tabs.filter(tab => tab.key === value);
} | conditional_block |
next-tab-component.ts | import {Directive, Input, Host, HostListener, HostBinding} from "angular2/core";
import {AngularNavTab} from "./tab-directive";
import {AngularNavTabs} from "./tabs-component";
import {TabInterface} from "../core";
@Directive({
selector: "[anNextTab]"
})
export class NextTab {
tab: AngularNavTab;
@HostBind... | @HostBinding('innerHTML') get html() {
return this.tab.title;
}
constructor(@Host() private anTabs: AngularNavTabs) {}
@HostListener('click', [])
onClick() {
this.anTabs.activateTab(this.tab.key);
}
@Input("anNextTab") set nextTab(value: string | TabInterface) ... | return this.tab.canActivate();
} | random_line_split |
next-tab-component.ts | import {Directive, Input, Host, HostListener, HostBinding} from "angular2/core";
import {AngularNavTab} from "./tab-directive";
import {AngularNavTabs} from "./tabs-component";
import {TabInterface} from "../core";
@Directive({
selector: "[anNextTab]"
})
export class NextTab {
tab: AngularNavTab;
@HostBind... |
constructor(@Host() private anTabs: AngularNavTabs) {}
@HostListener('click', [])
onClick() {
this.anTabs.activateTab(this.tab.key);
}
@Input("anNextTab") set nextTab(value: string | TabInterface) {
let tabs: Array<AngularNavTab> = [];
if (typeof value === 'st... | {
return this.tab.title;
} | identifier_body |
next-tab-component.ts | import {Directive, Input, Host, HostListener, HostBinding} from "angular2/core";
import {AngularNavTab} from "./tab-directive";
import {AngularNavTabs} from "./tabs-component";
import {TabInterface} from "../core";
@Directive({
selector: "[anNextTab]"
})
export class NextTab {
tab: AngularNavTab;
@HostBind... | () {
return !this.tab.canActivate();
}
@HostBinding('class.an-canactivate') get canactivate() {
return this.tab.canActivate();
}
@HostBinding('innerHTML') get html() {
return this.tab.title;
}
constructor(@Host() private anTabs: AngularNavTabs) {}
@HostListe... | cantactivate | identifier_name |
test_locale.py | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2013 OpenStack Foundation
#
# 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 re... | (self):
path = ':'.join(sys.path)
translated_message = check_output(['python', __file__, path])
self.assertEqual(translated_message, 'prova mesaĝo\n')
if __name__ == "__main__":
os.environ['LC_ALL'] = 'eo'
os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__)
sys.path = sys.arg... | test_translations | identifier_name |
test_locale.py | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2013 OpenStack Foundation
#
# 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 re... | if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output
class TestTranslations(unittest.TestCase):
def setUp(self):
self.orig_env = {}
for var in 'LC_ALL', 'SWIFT_LOCALEDIR', 'LANGUAGE':
sel... | random_line_split | |
test_locale.py | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2013 OpenStack Foundation
#
# 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 re... |
def tearDown(self):
for var, val in self.orig_env.items():
if val is not None:
os.environ[var] = val
else:
del os.environ[var]
threading._DummyThread._Thread__stop = self.orig_stop
def test_translations(self):
path = ':'.join(sys... | self.orig_env = {}
for var in 'LC_ALL', 'SWIFT_LOCALEDIR', 'LANGUAGE':
self.orig_env[var] = os.environ.get(var)
os.environ['LC_ALL'] = 'eo'
os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__)
os.environ['LANGUAGE'] = ''
self.orig_stop = threading._DummyThread._T... | identifier_body |
test_locale.py | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2013 OpenStack Foundation
#
# 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 re... |
threading._DummyThread._Thread__stop = self.orig_stop
def test_translations(self):
path = ':'.join(sys.path)
translated_message = check_output(['python', __file__, path])
self.assertEqual(translated_message, 'prova mesaĝo\n')
if __name__ == "__main__":
os.environ['LC_ALL'] = ... | del os.environ[var] | conditional_block |
event.rs | use std::list::*;
use core::cmp::Eq;
use core::option::*;
use transaction::*;
type Listen<A> = @fn(@fn(A)) -> @fn();
struct Event<P,A> {
part : Option<Partition<P>>,
listener : Listen<A>
}
pub impl<P,A : Copy> Event<P,A> {
pub fn never() -> Event<P,A> {
Event {
part : None,
... |
pub fn listen(&self, handler : @fn(A)) -> @fn() {
return (self.listener)(handler);
}
}
fn delete<A: Eq + Copy,B: Copy>(l : &List<(A,B)>, key : &A) -> @List<(A,B)>
{
match l {
&Nil => @Nil,
&Cons((k, v), t) => {
if k == *key { delete(t, key) }
... | {
let state = @mut EventState{ handlers : @Nil, nextIx : 0 };
(
Event {
part : Some(part),
listener : |handler| {
let ix = state.nextIx;
state.handlers = @Cons((ix, handler), state.handlers);
... | identifier_body |
event.rs | use std::list::*;
use core::cmp::Eq;
use core::option::*;
use transaction::*;
type Listen<A> = @fn(@fn(A)) -> @fn();
struct Event<P,A> {
part : Option<Partition<P>>,
listener : Listen<A>
}
pub impl<P,A : Copy> Event<P,A> {
pub fn never() -> Event<P,A> {
Event {
part : None,
... | {
match l {
&Nil => @Nil,
&Cons((k, v), t) => {
if k == *key { delete(t, key) }
else { @Cons((k, v), delete(t, key)) }
}
}
}
struct EventState<A> {
handlers : @List<(int, @fn(A))>,
nextIx : int
} |
fn delete<A: Eq + Copy,B: Copy>(l : &List<(A,B)>, key : &A) -> @List<(A,B)> | random_line_split |
event.rs | use std::list::*;
use core::cmp::Eq;
use core::option::*;
use transaction::*;
type Listen<A> = @fn(@fn(A)) -> @fn();
struct Event<P,A> {
part : Option<Partition<P>>,
listener : Listen<A>
}
pub impl<P,A : Copy> Event<P,A> {
pub fn never() -> Event<P,A> {
Event {
part : None,
... | (&self, handler : @fn(A)) -> @fn() {
return (self.listener)(handler);
}
}
fn delete<A: Eq + Copy,B: Copy>(l : &List<(A,B)>, key : &A) -> @List<(A,B)>
{
match l {
&Nil => @Nil,
&Cons((k, v), t) => {
if k == *key { delete(t, key) }
else { @Cons(... | listen | identifier_name |
iconButtonDropDown.tsx | import mergeClassNames from 'classnames';
import React, {PureComponent} from 'react';
import {PickDefaultProps} from '../../types';
import Button from '../Button';
import {ButtonProps} from '../Button/button';
import Icon from '../Icon';
import DropDownItem from './dropDownItem';
type DropDownId = string;
interface ... | isOpen: false,
};
export default class IconButtonDropDown extends PureComponent<IconButtonDropDownProps, IconButtonDropDownState> {
// tslint:disable:readonly-keyword
private _timeouts: {
hold?: number,
hover?: number
};
// tslint:enable:readonly-keyword
constructor(props: Icon... | }
const initialState: IconButtonDropDownState = { | random_line_split |
iconButtonDropDown.tsx | import mergeClassNames from 'classnames';
import React, {PureComponent} from 'react';
import {PickDefaultProps} from '../../types';
import Button from '../Button';
import {ButtonProps} from '../Button/button';
import Icon from '../Icon';
import DropDownItem from './dropDownItem';
type DropDownId = string;
interface ... | }
private readonly handleMouseLeave = () => {
this.cancelHoldTimeout();
this.cancelHoverTimeout();
this.closeDropDown();
}
private readonly createItemSelectedHandler = (dropDownId: DropDownId) => () => {
this.props.onItemSelect(dropDownId);
this.closeDropDown();... |
this.props.onClick();
}
| conditional_block |
iconButtonDropDown.tsx | import mergeClassNames from 'classnames';
import React, {PureComponent} from 'react';
import {PickDefaultProps} from '../../types';
import Button from '../Button';
import {ButtonProps} from '../Button/button';
import Icon from '../Icon';
import DropDownItem from './dropDownItem';
type DropDownId = string;
interface ... |
return (
<div className={finalClassName} onMouseLeave={this.handleMouseLeave}>
<Button
{...rest}
style="clean"
hoverStyle="clean"
aria-haspopup="true"
className={theme!.wrapper__btn}
... |
const {
className,
disabled,
icon,
modeIcon,
theme,
directButtonProps,
children
} = this.props;
const {isOpen} = this.state;
const finalClassName = mergeClassNames(className, theme!.wrapper);
con... | identifier_body |
iconButtonDropDown.tsx | import mergeClassNames from 'classnames';
import React, {PureComponent} from 'react';
import {PickDefaultProps} from '../../types';
import Button from '../Button';
import {ButtonProps} from '../Button/button';
import Icon from '../Icon';
import DropDownItem from './dropDownItem';
type DropDownId = string;
interface ... | props: IconButtonDropDownProps) {
super(props);
this.state = initialState;
this._timeouts = {
hold: undefined,
hover: undefined
};
}
public static readonly defaultProps = defaultProps;
public render(): JSX.Element {
const {
clas... | onstructor( | identifier_name |
datepicker-hy.js | define('jqueryui/datepicker-hy', ['jquery','jqueryui/datepicker'], function (jQuery) {
/* Armenian(UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Levon Zakaryan (levon.zakaryan@gmail.com)*/
jQuery(function($){
$.datepicker.regional['hy'] = {
| prevText: '<Նախ.',
nextText: 'Հաջ.>',
currentText: 'Այսօր',
monthNames: ['Հունվար','Փետրվար','Մարտ','Ապրիլ','Մայիս','Հունիս',
'Հուլիս','Օգոստոս','Սեպտեմբեր','Հոկտեմբեր','Նոյեմբեր','Դեկտեմբեր'],
monthNamesShort: ['Հունվ','Փետր','Մարտ','Ապր','Մայիս','Հունիս',
'Հուլ','Օգս','Սեպ','Հոկ','Նոյ','... | closeText: 'Փակել',
| random_line_split |
global_asm_include.rs | // ignore-aarch64
// ignore-aarch64_be
// ignore-arm
// ignore-armeb
// ignore-avr
// ignore-bpfel
// ignore-bpfeb
// ignore-hexagon
// ignore-mips
// ignore-mips64
// ignore-msp430
// ignore-powerpc64
// ignore-powerpc64le
// ignore-powerpc
// ignore-r600
// ignore-amdgcn
// ignore-sparc
// ignore-sparcv9
// ignore-sp... | // ignore-xcore
// ignore-nvptx
// ignore-nvptx64
// ignore-le32
// ignore-le64
// ignore-amdil
// ignore-amdil64
// ignore-hsail
// ignore-hsail64
// ignore-spir
// ignore-spir64
// ignore-kalimba
// ignore-shave
// ignore-wasm32
// ignore-wasm64
// ignore-emscripten
// compile-flags: -C no-prepopulate-passes
#![feat... | // ignore-thumb
// ignore-thumbeb | random_line_split |
global_asm_include.rs | // ignore-aarch64
// ignore-aarch64_be
// ignore-arm
// ignore-armeb
// ignore-avr
// ignore-bpfel
// ignore-bpfeb
// ignore-hexagon
// ignore-mips
// ignore-mips64
// ignore-msp430
// ignore-powerpc64
// ignore-powerpc64le
// ignore-powerpc
// ignore-r600
// ignore-amdgcn
// ignore-sparc
// ignore-sparcv9
// ignore-sp... | {} | identifier_body | |
global_asm_include.rs | // ignore-aarch64
// ignore-aarch64_be
// ignore-arm
// ignore-armeb
// ignore-avr
// ignore-bpfel
// ignore-bpfeb
// ignore-hexagon
// ignore-mips
// ignore-mips64
// ignore-msp430
// ignore-powerpc64
// ignore-powerpc64le
// ignore-powerpc
// ignore-r600
// ignore-amdgcn
// ignore-sparc
// ignore-sparcv9
// ignore-sp... | () {}
| baz | identifier_name |
error.rs | use std::error::Error as StdError;
use std::fmt::{self, Display};
/// An error that occurred while attempting to deal with the gateway.
///
/// Note that - from a user standpoint - there should be no situation in which
/// you manually handle these.
#[derive(Clone, Debug)]
pub enum | {
/// There was an error building a URL.
BuildingUrl,
/// The connection closed, potentially uncleanly.
Closed(Option<u16>, String),
/// Expected a Hello during a handshake
ExpectedHello,
/// Expected a Ready or an InvalidateSession
InvalidHandshake,
/// An indicator that an unknown... | Error | identifier_name |
error.rs | use std::error::Error as StdError;
use std::fmt::{self, Display};
/// An error that occurred while attempting to deal with the gateway.
///
/// Note that - from a user standpoint - there should be no situation in which
/// you manually handle these.
#[derive(Clone, Debug)]
pub enum Error {
/// There was an error b... |
}
| {
match *self {
Error::BuildingUrl => "Error building url",
Error::Closed(_, _) => "Connection closed",
Error::ExpectedHello => "Expected a Hello",
Error::InvalidHandshake => "Expected a valid Handshake",
Error::InvalidOpCode => "Invalid OpCode",
... | identifier_body |
error.rs | use std::error::Error as StdError;
use std::fmt::{self, Display};
/// An error that occurred while attempting to deal with the gateway.
///
/// Note that - from a user standpoint - there should be no situation in which
/// you manually handle these.
#[derive(Clone, Debug)]
pub enum Error {
/// There was an error b... | match *self {
Error::BuildingUrl => "Error building url",
Error::Closed(_, _) => "Connection closed",
Error::ExpectedHello => "Expected a Hello",
Error::InvalidHandshake => "Expected a valid Handshake",
Error::InvalidOpCode => "Invalid OpCode",
... | impl StdError for Error {
fn description(&self) -> &str { | random_line_split |
os.rs | // Copyright 2018 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 ... |
pub fn exit(code: i32) -> ! {
unsafe { libc::exit(code as c_int) }
}
| {
// cloudlibc's strerror() is guaranteed to be thread-safe. There is
// thus no need to use strerror_r().
str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes())
.unwrap()
.to_owned()
} | identifier_body |
os.rs | // Copyright 2018 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 ... | (code: i32) -> ! {
unsafe { libc::exit(code as c_int) }
}
| exit | identifier_name |
os.rs | // Copyright 2018 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 ... | use libc::{self, c_int};
use str;
pub use sys::cloudabi::shims::os::*;
pub fn errno() -> i32 {
extern "C" {
#[thread_local]
static errno: c_int;
}
unsafe { errno as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String {
... | random_line_split | |
index.js | module.exports = exports = function(app) {
// The main page of the blog
app.get('/', function(req, res, next){
return res.render('index', {
title: 'Editor homepage'
});
});
/* The main page of the blog, filtered by tag
app.get('/tag/:tag', contentHandler.displayMai... | var ErrorHandler = require('./error').errorHandler;
| random_line_split | |
goodsAdd.component.ts | import { Component, Input, Output, EventEmitter } from "@angular/core";
import { GoodsService } from "../../service/goods.service";
@Component({
moduleId: "goodsAdd",
selector: "goods-add",
templateUrl: "goodsAdd.component.html"
})
export class GoodsAddComponent {
@Input() public cat:any;
@Output() public s... |
} | {
if(!this.cat || !this.cat.id){
return;
}else {
this.goodsInfo = goodsInfoComponent.getGoodsInfo();
if(!this.checkGoodsInfo(this.goodsInfo)){
return;
}
this.goodsService.addGoods(this.goodsInfo).subscribe(res => {
let data = res.json();
if(data.success){
... | identifier_body |
goodsAdd.component.ts | import { Component, Input, Output, EventEmitter } from "@angular/core";
import { GoodsService } from "../../service/goods.service";
@Component({
moduleId: "goodsAdd",
selector: "goods-add",
templateUrl: "goodsAdd.component.html"
})
export class GoodsAddComponent {
@Input() public cat:any;
@Output() public s... | else if(!goodsInfo.recPrice || isNaN(goodsInfo.recPrice)){
return false;
} else if(!goodsInfo.salePrice || isNaN(goodsInfo.salePrice)){
return false;
}
return true;
}
/*
* @Description: Add new goods;
* @Date: 2017-01-10;
*/
public addGoods(goodsInfoComponent):void {
if(!th... | {
return false;
} | conditional_block |
goodsAdd.component.ts | import { Component, Input, Output, EventEmitter } from "@angular/core";
import { GoodsService } from "../../service/goods.service";
@Component({
moduleId: "goodsAdd",
selector: "goods-add",
templateUrl: "goodsAdd.component.html"
})
export class GoodsAddComponent {
@Input() public cat:any;
@Output() public s... | if(!goodsInfo.title){
return false;
} else if(!goodsInfo.goodsSn){
return false;
} else if(!goodsInfo.recPrice || isNaN(goodsInfo.recPrice)){
return false;
} else if(!goodsInfo.salePrice || isNaN(goodsInfo.salePrice)){
return false;
}
return true;
}
/*
* @Descrip... | random_line_split | |
goodsAdd.component.ts | import { Component, Input, Output, EventEmitter } from "@angular/core";
import { GoodsService } from "../../service/goods.service";
@Component({
moduleId: "goodsAdd",
selector: "goods-add",
templateUrl: "goodsAdd.component.html"
})
export class | {
@Input() public cat:any;
@Output() public selectTab = new EventEmitter<string>();
public goodsInfo:any;
constructor(public goodsService: GoodsService){console.log(this.cat)}
/*
* @Description: Check the form data;
* @Date: 2017-01-10;
*/
public checkGoodsInfo(goods):boolean {
let goodsInfo... | GoodsAddComponent | identifier_name |
surface.js | /*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame,
assertDataProperty,
assertBuiltinConstructor,
assertBuiltinPrototype,
} = Assert;
function assertFunctionProperty(obj... |
/* Properties of the Promise Constructor */
assertPrototypeProperty(Promise);
assertCreateFunctionProperty(Promise, Symbol.create);
assertFunctionProperty(Promise, "all");
assertFunctionProperty(Promise, "cast");
assertFunctionProperty(Promise, "race");
assertFunctionProperty(Promise, "reject");
assertFunctionProper... | assertBuiltinConstructor(Promise, "Promise", 1);
assertBuiltinPrototype(Promise.prototype);
assertSame(Promise, Promise.prototype.constructor); | random_line_split |
surface.js | /*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame,
assertDataProperty,
assertBuiltinConstructor,
assertBuiltinPrototype,
} = Assert;
function assertFunctionProperty(obj... | object, name = "constructor", value = object[name]) {
return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true});
}
function assertPrototypeProperty(object, name = "prototype", value = object[name]) {
return assertDataProperty(object, name, {value, writable: false, enum... | ssertConstructorProperty( | identifier_name |
surface.js | /*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame,
assertDataProperty,
assertBuiltinConstructor,
assertBuiltinPrototype,
} = Assert;
function assertFunctionProperty(obj... |
function assertCreateFunctionProperty(object, name, value = object[name]) {
return assertDataProperty(object, name, {value, writable: false, enumerable: false, configurable: true});
}
function assertConstructorProperty(object, name = "constructor", value = object[name]) {
return assertDataProperty(object, name, {... |
return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true});
}
| identifier_body |
main.py | ', 'main' ]
usage="%prog [gem5 options] script.py [script options]"
version="%prog 2.0"
brief_copyright=\
"gem5 is copyrighted software; use the --copyright option for details."
def parse_options():
import config
from options import OptionParser
options = OptionParser(usage=usage, version=version,
... | ():
if defines.TRACING_ON:
return
fatal("Tracing is not enabled. Compile with TRACING_ON")
# Set the main event queue for the main thread.
event.mainq = event.getEventQueue(0)
event.setEventQueue(event.mainq)
if not os.path.isdir(options.outdir):
os.makedirs(optio... | check_tracing | identifier_name |
main.py | ', 'main' ]
usage="%prog [gem5 options] script.py [script options]"
version="%prog 2.0"
brief_copyright=\
"gem5 is copyrighted software; use the --copyright option for details."
def parse_options():
import config
from options import OptionParser
options = OptionParser(usage=usage, version=version,
... |
else:
if options.redirect_stdout:
print "Redirecting stdout to", stdout_file
if options.redirect_stderr:
print "Redirecting stderr to", stderr_file
# Now redirect stdout/stderr as desired
if options.redirect_stdout:
redir_fd = os.open(stdout_file, os. O_WRON... | print "Redirecting stdout and stderr to", stdout_file | conditional_block |
main.py | ', 'main' ]
usage="%prog [gem5 options] script.py [script options]"
version="%prog 2.0"
brief_copyright=\
"gem5 is copyrighted software; use the --copyright option for details."
def parse_options():
import config
from options import OptionParser
options = OptionParser(usage=usage, version=version,
... | banner=banner, user_ns=scope)
except ImportError:
pass
# Is IPython version 0.11 or later available?
if not ipshell:
try:
import IPython
from IPython.config.loader import Config
from IPython.frontend.terminal.embed import In... | try:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed(argv=["-prompt_in1", prompt_in1,
"-prompt_out", prompt_out], | random_line_split |
main.py | ', 'main' ]
usage="%prog [gem5 options] script.py [script options]"
version="%prog 2.0"
brief_copyright=\
"gem5 is copyrighted software; use the --copyright option for details."
def parse_options():
import config
from options import OptionParser
options = OptionParser(usage=usage, version=version,
... |
# Set the main event queue for the main thread.
event.mainq = event.getEventQueue(0)
event.setEventQueue(event.mainq)
if not os.path.isdir(options.outdir):
os.makedirs(options.outdir)
# These filenames are used only if the redirect_std* options are set
stdout_file = os.path.join(opti... | if defines.TRACING_ON:
return
fatal("Tracing is not enabled. Compile with TRACING_ON") | identifier_body |
hub.js | var debug = require('debug')('harmonyhubjs:client:login:hub')
var Client = require('node-xmpp-client')
var Q = require('q')
var util = require('../util')
/** PrivateFunction: getIdentity
* Logs in to a Harmony hub as a guest and uses the userAuthToken from logitech's
* web service to retrieve an identity token. | * this is set to 5222.
*
* Returns:
* (Q.promise) - The resolved promise passes the retrieved identity token.
*/
function getIdentity (hubhost, hubport) {
debug('retrieve identity by logging in as guest')
// guest@x.com / guest
// guest@connect.logitech.com/gatorade
var deferred = ... | *
* Parameters:
* (String) hubhost - Hostname/IP of the Harmony hub to connect.
* (int) hubport - Optional. Port of the Harmony hub to connect. By default, | random_line_split |
hub.js | var debug = require('debug')('harmonyhubjs:client:login:hub')
var Client = require('node-xmpp-client')
var Q = require('q')
var util = require('../util')
/** PrivateFunction: getIdentity
* Logs in to a Harmony hub as a guest and uses the userAuthToken from logitech's
* web service to retrieve an identity token.
*
... |
module.exports = loginToHub
| {
debug('perform hub login')
hubport = hubport || 5222
return getIdentity(hubhost, hubport)
.then(function (identity) {
return loginWithIdentity(identity, hubhost, hubport)
})
} | identifier_body |
hub.js | var debug = require('debug')('harmonyhubjs:client:login:hub')
var Client = require('node-xmpp-client')
var Q = require('q')
var util = require('../util')
/** PrivateFunction: getIdentity
* Logs in to a Harmony hub as a guest and uses the userAuthToken from logitech's
* web service to retrieve an identity token.
*
... |
})
return deferred.promise
}
/** PrivateFunction: loginWithIdentity
* After fetching an identity from the Harmony hub, this function creates an
* XMPP client using that identity. It returns a promise which, when resolved,
* passes that XMPP client.
*
* Parameters:
* (String) identity - Identity token t... | {
var body = stanza.getChildText('oa')
var response = util.decodeColonSeparatedResponse(body)
if (response.identity && response.identity !== undefined) {
debug('received identity token: ' + response.identity)
xmppClient.end()
deferred.resolve(response.identity)
} else {
... | conditional_block |
hub.js | var debug = require('debug')('harmonyhubjs:client:login:hub')
var Client = require('node-xmpp-client')
var Q = require('q')
var util = require('../util')
/** PrivateFunction: getIdentity
* Logs in to a Harmony hub as a guest and uses the userAuthToken from logitech's
* web service to retrieve an identity token.
*
... | (hubhost, hubport) {
debug('retrieve identity by logging in as guest')
// guest@x.com / guest
// guest@connect.logitech.com/gatorade
var deferred = Q.defer()
var iqId
var xmppClient = new Client({
jid: 'guest@x.com/gatorade',
password: 'guest',
host: hubhost,
port: hubport,
disallowTL... | getIdentity | identifier_name |
models.py | from django.db import models
from django.utils.translation import ugettext as _
from common import models as common_models
from hosts import models as hosts_models
class Project(common_models.TimestampedModel):
name = models.CharField(_('Name'), max_length=254)
description = models.TextField(_('Name'), blank... | return self.name
class HostConfig(common_models.TimestampedModel):
stage = models.ForeignKey(Stage, verbose_name=_('Stage'))
host = models.ForeignKey(hosts_models.Host, verbose_name=('Host'))
ssh_config = models.ForeignKey(hosts_models.SSHConfig, verbose_name=_('SSH Config'))
is_active = model... | verbose_name_plural = _('Stages')
def __str__(self): | random_line_split |
models.py | from django.db import models
from django.utils.translation import ugettext as _
from common import models as common_models
from hosts import models as hosts_models
class Project(common_models.TimestampedModel):
name = models.CharField(_('Name'), max_length=254)
description = models.TextField(_('Name'), blank... |
def __str__(self):
return self.name
class HostConfig(common_models.TimestampedModel):
stage = models.ForeignKey(Stage, verbose_name=_('Stage'))
host = models.ForeignKey(hosts_models.Host, verbose_name=('Host'))
ssh_config = models.ForeignKey(hosts_models.SSHConfig, verbose_name=_('SSH Config... | verbose_name = _('Stage')
verbose_name_plural = _('Stages') | identifier_body |
models.py | from django.db import models
from django.utils.translation import ugettext as _
from common import models as common_models
from hosts import models as hosts_models
class Project(common_models.TimestampedModel):
name = models.CharField(_('Name'), max_length=254)
description = models.TextField(_('Name'), blank... | :
verbose_name = _('Stage')
verbose_name_plural = _('Stages')
def __str__(self):
return self.name
class HostConfig(common_models.TimestampedModel):
stage = models.ForeignKey(Stage, verbose_name=_('Stage'))
host = models.ForeignKey(hosts_models.Host, verbose_name=('Host'))
ssh_... | Meta | identifier_name |
error.rs | use crate::codec::{CodecError, Message, ZmtpVersion};
use crate::endpoint::Endpoint;
use crate::endpoint::EndpointError;
use crate::task_handle::TaskError;
use crate::ZmqMessage;
use thiserror::Error;
pub type ZmqResult<T> = Result<T, ZmqError>;
#[derive(Error, Debug)]
pub enum ZmqError {
#[error("Endpoint Error... | Codec(#[from] CodecError),
#[error("Socket Error: {0}")]
Socket(&'static str),
#[error("{0}")]
BufferFull(&'static str),
#[error("Failed to deliver message cause of {reason}")]
ReturnToSender {
reason: &'static str,
message: ZmqMessage,
},
// TODO refactor this.
/... | #[error("Codec Error: {0}")] | random_line_split |
error.rs | use crate::codec::{CodecError, Message, ZmtpVersion};
use crate::endpoint::Endpoint;
use crate::endpoint::EndpointError;
use crate::task_handle::TaskError;
use crate::ZmqMessage;
use thiserror::Error;
pub type ZmqResult<T> = Result<T, ZmqError>;
#[derive(Error, Debug)]
pub enum ZmqError {
#[error("Endpoint Error... | (_: futures::channel::mpsc::SendError) -> Self {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
}
| from | identifier_name |
error.rs | use crate::codec::{CodecError, Message, ZmtpVersion};
use crate::endpoint::Endpoint;
use crate::endpoint::EndpointError;
use crate::task_handle::TaskError;
use crate::ZmqMessage;
use thiserror::Error;
pub type ZmqResult<T> = Result<T, ZmqError>;
#[derive(Error, Debug)]
pub enum ZmqError {
#[error("Endpoint Error... |
}
impl From<futures::channel::mpsc::SendError> for ZmqError {
fn from(_: futures::channel::mpsc::SendError) -> Self {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
}
| {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
} | identifier_body |
mod.rs | // Copyright 2015, 2016 Ethcore (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 later version.... |
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/morden.json"))
}
#[cfg(test)]
mod tests {
use common::*;
use state::*;
use engine::*;
use super::*;
use tests::helpers::*;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &s... | random_line_split | |
mod.rs | // Copyright 2015, 2016 Ethcore (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 later version.... | () -> Spec {
Spec::load(include_bytes!("../../res/ethereum/morden.json"))
}
#[cfg(test)]
mod tests {
use common::*;
use state::*;
use engine::*;
use super::*;
use tests::helpers::*;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &spec.engine;
let genesis_header = spec.genesis_header... | new_morden | identifier_name |
mod.rs | // Copyright 2015, 2016 Ethcore (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 later version.... |
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn new_frontier_test() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier_test.json"))
}
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec {
Spec::load(i... | {
Spec::load(include_bytes!("../../res/ethereum/frontier.json"))
} | identifier_body |
CarouselSlidePicker.tsx | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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... | const CarouselSlidePicker = ({ slides, visibleSlide, onClickEvent }: any) => {
if (!slides || slides.length === 0) return null
const Indicators = slides.map((_: any, i: any) =>
i !== visibleSlide ? (
<CarouselIndicatorInactive
key={i}
aria-label={i + 1}
onClick={() => onClickEvent(... | random_line_split | |
linux.py | #!/usr/bin/env python3
import os
from pathlib import Path
from scripts.build_env import BuildEnv, Platform
from scripts.platform_builder import PlatformBuilder
class pugixmlLinuxBuilder(PlatformBuilder):
def __init__(self,
config_package: dict=None,
config_platform: dict=None):
... | cmd = '{} cmake -DCMAKE_INSTALL_LIBDIR={} -DCMAKE_INSTALL_INCLUDEDIR={} ..; make -j {}; make install'.format(
self.env.BUILD_FLAG,
self.env.install_lib_path,
self.env.install_include_path,
self.env.NJOBS
)
self.env.run_command(cmd, module_name=self... |
self.tag_log("Start building ...")
BuildEnv.mkdir_p(build_path)
os.chdir(build_path) | random_line_split |
linux.py | #!/usr/bin/env python3
import os
from pathlib import Path
from scripts.build_env import BuildEnv, Platform
from scripts.platform_builder import PlatformBuilder
class | (PlatformBuilder):
def __init__(self,
config_package: dict=None,
config_platform: dict=None):
super().__init__(config_package, config_platform)
def build(self):
build_path = '{}/{}/scripts/build'.format(
self.env.source_path,
self.config... | pugixmlLinuxBuilder | identifier_name |
linux.py | #!/usr/bin/env python3
import os
from pathlib import Path
from scripts.build_env import BuildEnv, Platform
from scripts.platform_builder import PlatformBuilder
class pugixmlLinuxBuilder(PlatformBuilder):
def __init__(self,
config_package: dict=None,
config_platform: dict=None):
... |
self.tag_log("Start building ...")
BuildEnv.mkdir_p(build_path)
os.chdir(build_path)
cmd = '{} cmake -DCMAKE_INSTALL_LIBDIR={} -DCMAKE_INSTALL_INCLUDEDIR={} ..; make -j {}; make install'.format(
self.env.BUILD_FLAG,
self.env.install_lib_path,
self.en... | self.tag_log("Already built.")
return | conditional_block |
linux.py | #!/usr/bin/env python3
import os
from pathlib import Path
from scripts.build_env import BuildEnv, Platform
from scripts.platform_builder import PlatformBuilder
class pugixmlLinuxBuilder(PlatformBuilder):
def __init__(self,
config_package: dict=None,
config_platform: dict=None):
... |
def build(self):
build_path = '{}/{}/scripts/build'.format(
self.env.source_path,
self.config['name']
)
# if os.path.exists(self.env.install_lib_path+'/libpugixml.a'):
_check = self.env.install_lib_path / self.config.get("checker")
if os.path.exists... | super().__init__(config_package, config_platform) | identifier_body |
lib.rs | #![feature(lang_items)]
#![feature(const_fn)]
#![feature(unique)]
#![feature(alloc, collections)]
#![no_std]
extern crate rlibc;
extern crate spin;
extern crate multiboot2;
#[macro_use]
extern crate bitflags;
extern crate x86;
extern crate hole_list_allocator;
extern crate alloc;
#[macro_use]
extern crate collections;... |
fn enable_write_protect_bit() {
use x86::controlregs::{cr0, cr0_write};
let wp_bit = 1 << 16;
unsafe { cr0_write(cr0() | wp_bit) };
}
| {
use x86::msr::{IA32_EFER, rdmsr, wrmsr};
let nxe_bit = 1 << 11;
unsafe {
let efer = rdmsr(IA32_EFER);
wrmsr(IA32_EFER, efer | nxe_bit);
}
} | identifier_body |
lib.rs | #![feature(lang_items)]
#![feature(const_fn)]
#![feature(unique)]
#![feature(alloc, collections)]
#![no_std]
extern crate rlibc;
extern crate spin;
extern crate multiboot2;
#[macro_use]
extern crate bitflags;
extern crate x86;
extern crate hole_list_allocator;
extern crate alloc;
#[macro_use]
extern crate collections;... | () {
use x86::controlregs::{cr0, cr0_write};
let wp_bit = 1 << 16;
unsafe { cr0_write(cr0() | wp_bit) };
}
| enable_write_protect_bit | identifier_name |
lib.rs | #![feature(lang_items)]
#![feature(const_fn)]
#![feature(unique)]
#![feature(alloc, collections)]
#![no_std]
extern crate rlibc;
extern crate spin;
extern crate multiboot2;
#[macro_use]
extern crate bitflags;
extern crate x86;
extern crate hole_list_allocator;
extern crate alloc;
#[macro_use]
extern crate collections;... |
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
#[lang = "panic_fmt"]
extern "C" fn panic_fmt(fmt: core::fmt::Arguments, file: &str, line: u32) -> ! {
println!("\n\nPANIC in {} at line {}:", file, line);
println!(" {}", fmt);
loop {}
}
fn enable_nxe_bit() {
use x86::msr::{IA32_EFER, r... | } | random_line_split |
scroller.js | * scroll event. Ideally this should be low, so that once the user stops
* scrolling, things are immediately centered again. Since there can be some
* delay between scroll events, and we do not want to interrupt a scroll with a
* render, it cannot be too small. 200ms seems to be around the lower limit for
* this va... | ,
}),
[advance, advanceCount]
);
const classes = useStyles();
/**
* The dynamic position that the slide at the resting index
* is with respect to its scrolling order. Only needed if loop=true.
*/
const offsetRef = useRef(restingIndex);
/**
* The partial scroll position as a percentage of... | {
return containerRef.current;
} | identifier_body |
scroller.js | * scroll event. Ideally this should be low, so that once the user stops
* scrolling, things are immediately centered again. Since there can be some
* delay between scroll events, and we do not want to interrupt a scroll with a
* render, it cannot be too small. 200ms seems to be around the lower limit for
* this va... |
currentIndex.current = mod(
overlappingIndex - offsetRef.current,
children.length
);
};
const handleScroll = () => {
if (ignoreProgrammaticScrollRef.current) {
ignoreProgrammaticScrollRef.current = false;
return;
}
updateCurrentIndex();
debouncedResetScrollReference... | {
scrollOffset.current = getPercentageOffsetFromAlignment(
axis,
alignment,
container,
container.children[overlappingIndex]
);
} | conditional_block |
scroller.js | * scroll event. Ideally this should be low, so that once the user stops
* scrolling, things are immediately centered again. Since there can be some
* delay between scroll events, and we do not want to interrupt a scroll with a
* render, it cannot be too small. 200ms seems to be around the lower limit for
* this va... | */
const scrollOffset = useRef(0);
const slides = renderSlides(
{
alignment,
children,
loop,
mixedLength,
offsetRef,
lightboxGroup,
pivotIndex,
restingIndex,
snap,
snapBy,
visibleCount,
_thumbnails,
},
classes
);
const curre... | /**
* The partial scroll position as a percentage of the current visible slide.
* Only modified if snap=false. | random_line_split |
scroller.js | * scroll event. Ideally this should be low, so that once the user stops
* scrolling, things are immediately centered again. Since there can be some
* delay between scroll events, and we do not want to interrupt a scroll with a
* render, it cannot be too small. 200ms seems to be around the lower limit for
* this va... | (
{
_thumbnails,
advanceCount,
alignment,
axis,
children,
lightboxGroup,
loop,
mixedLength,
onClick,
restingIndex,
setRestingIndex,
snap,
snapBy = 1,
visibleCount,
},
ref
) {
// We still need our own ref that we can always rely on to be there.
const cont... | ScrollerWithRef | identifier_name |
app.py | #!/usr/bin/python
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJ... |
if amount == 0:
raise Exception("Invalid amount")
# Payment
# A Payment Resource; create one using
# the above types and intent as 'sale'
payment = paypalrestsdk.Payment({
"intent": "sale",
# Payer
# A resource representing a Payer that funds a payment
# Payment Method as 'paypal'
... | amount += float(request.form[key])
if request.form[key] != 0:
items.append({
"name": "Donation to " + value,
"price": "%.2f" % float(request.form[key]),
"currency": "GBP",
"quantity": 1
}) | conditional_block |
app.py | #!/usr/bin/python
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJ... |
if amount == 0:
raise Exception("Invalid amount")
# Payment
# A Payment Resource; create one using
# the above types and intent as 'sale'
payment = paypalrestsdk.Payment({
"intent": "sale",
# Payer
# A resource representing a Payer that funds a payment
# Payment Method as 'paypal'
"... | amount = 0
categories = {
'amount-homeless': 'homeless people',
'amount-refugees': 'refugees people',
'amount-orphans': 'orphans people',
'amount-poverished': 'perverished people'
}
items = []
for key, value in categories.iteritems():
amount += float(request.form[key])
if request.form... | identifier_body |
app.py | #!/usr/bin/python
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJ... | ():
return render_template('index.html')
@app.route('/payment/donation/create', methods=["POST"])
def paypal_process():
amount = 0
categories = {
'amount-homeless': 'homeless people',
'amount-refugees': 'refugees people',
'amount-orphans': 'orphans people',
'amount-poverished': 'perverished peopl... | index | identifier_name |
app.py | #!/usr/bin/python
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJ... |
return "Thank you for your donation of " + payment.transactions[0].amount.total + "!"
# @app.route('/search/tickets')
# def search_tickets():
# p1 = Passenger(age=30)
#
# tp1 = TravelPoint(
# origin="GBQQU",
# destination="GBQQM",
# departure=datetime(2015, 11, 23, 8))
#
# fq = FareSearch(
#... | payment = paypalrestsdk.Payment.find(payment_id)
print(payment.transactions[0].amount.total); | random_line_split |
timeoutWith.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var async_1 = require('../scheduler/async');
var... |
TimeoutWithOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
};
return TimeoutWithOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
... | {
this.waitFor = waitFor;
this.absoluteTimeout = absoluteTimeout;
this.withObservable = withObservable;
this.scheduler = scheduler;
} | identifier_body |
timeoutWith.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var async_1 = require('../scheduler/async');
var... | return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
};
}
exports.timeoutWith = timeoutWith;
var TimeoutWithOperator = (function () {
function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {
this.waitFor = waitFor;
t... | var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); | random_line_split |
timeoutWith.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var async_1 = require('../scheduler/async');
var... | (due, withObservable, scheduler) {
if (scheduler === void 0) { scheduler = async_1.async; }
return function (source) {
var absoluteTimeout = isDate_1.isDate(due);
var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
return source.lift(new TimeoutWithOperator(waitFor,... | timeoutWith | identifier_name |
timeoutWith.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var async_1 = require('../scheduler/async');
var... |
else {
this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
}
};
TimeoutWithSubscriber.prototype._next = function (value) {
if (!this.absoluteTimeout) {
this.scheduleTimeout();
}
_super.protot... | {
// Recycle the action if we've already scheduled one. All the production
// Scheduler Actions mutate their state/delay time and return themeselves.
// VirtualActions are immutable, so they create and return a clone. In this
// case, we need to set the action reference t... | conditional_block |
jquery.slider.js | >' +
'<input type="hidden" class="slider-value">' +
'</div>').insertAfter(target);
var t = $(target);
t.addClass('slider-f').hide();
var name = t.attr('name');
if (name){
slider.find('input.slider-value').attr('name', name);
t.removeAttr('name').attr('sliderName', name);
}
return sli... | span.css({
top: distance,
marginTop: -Math.round(span.outerHeight()/2)
});
}
}
}
}
}
/**
* build the slider and set some properties
*/
function buildSlider(target){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.... | {
var rule = slider.find('div.slider-rule');
var label = slider.find('div.slider-rulelabel');
rule.empty();
label.empty();
for(var i=0; i<aa.length; i++){
var distance = i*100/(aa.length-1)+'%';
var span = $('<span></span>').appendTo(rule);
span.css((opts.mode=='h'?'left':'top'), dist... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.