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 |
|---|---|---|---|---|
fablib.py | }
if env.repo_type == 'cvs':
print "TODO: write CVS status command"
return
if files.exists(path.join(env.vcs_root_dir, "." + env.repo_type)):
with cd(env.vcs_root_dir):
status = sudo_or_run(status_cmd[env.repo_type])
if status:
print 'Found local ... | vcs_config_stub = path.join(env.vcs_root_dir, env.webserver, env.environment)
vcs_config_live = vcs_config_stub + '.conf'
vcs_config_maintenance = vcs_config_stub + '-maintenance.conf' | random_line_split | |
fablib.py |
else:
env.python_bin = path.join('/', 'usr', 'bin', 'python')
return env.python_bin
def _get_tasks_bin():
if 'tasks_bin' not in env:
env.tasks_bin = path.join(env.deploy_dir, 'tasks.py')
return env.tasks_bin
def _tasks(tasks_args, verbose=False):
tasks_cmd = _get_tasks_b... | env.python_bin = python26 | conditional_block | |
styled.ts | import {G, popGlobals, pushGlobals} from '../../lib/browserGlobals';
import {observable} from '../../lib/observable';
import {keyframes, styled} from '../../lib/styled';
import {assert} from 'chai';
import {JSDOM} from 'jsdom';
describe('styles', function() {
let jsdomDoc;
beforeEach(function() {
jsdomDoc = ... |
// It seems that :animation" is only set correctly in jsdom <11.11.0, it doesn't work in
// 11.12.0 through 12.2.0.
const anim1 = G.window.getComputedStyle(elem1).animation!.split(' ')[0];
assert.isTrue(framesMap.has(anim1));
assert.deepEqual(getKeytext(framesMap.get(anim1)!), ["0%", "100%"]);
... | {
return Array.from(rule.cssRules, (r) => (r as CSSKeyframeRule).keyText);
} | identifier_body |
styled.ts | import {G, popGlobals, pushGlobals} from '../../lib/browserGlobals';
import {observable} from '../../lib/observable';
import {keyframes, styled} from '../../lib/styled';
import {assert} from 'chai';
import {JSDOM} from 'jsdom';
describe('styles', function() {
let jsdomDoc;
beforeEach(function() {
jsdomDoc = ... | (): Set<string> {
const selectors = new Set<string>();
for (const s of G.document.head!.querySelectorAll('style')) {
for (const r of Array.from((s.sheet as CSSStyleSheet).cssRules)) {
selectors.add((r as CSSStyleRule).selectorText);
}
}
return selectors;
}
it('should avoid class... | getSelectorsInPage | identifier_name |
styled.ts | import {G, popGlobals, pushGlobals} from '../../lib/browserGlobals';
import {observable} from '../../lib/observable';
import {keyframes, styled} from '../../lib/styled';
import {assert} from 'chai';
import {JSDOM} from 'jsdom';
describe('styles', function() {
let jsdomDoc;
beforeEach(function() {
jsdomDoc = ... | assert.equal(elem.style.color, '');
assert.equal(elem.style.fontSize, '');
});
it('should process nested styles', () => {
const sdiv = styled('div', `
color: red;
font-size: 27px;
&-green { color: green; }
&-blue { color: blue; }
&-highlight { border: 2px solid blue; }
... | assert.equal(style.fontSize, '27px');
// Check that we have a single class set, and that styles are not set directly.
assert.lengthOf(elem.classList, 1); | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(env)]
#![feature(... | pub mod namespace;
pub mod opts;
pub mod persistent_list;
pub mod range;
pub mod resource_files;
pub mod str;
pub mod task;
pub mod tid;
pub mod time;
pub mod taskpool;
pub mod task_state;
pub mod vec;
pub mod workqueue;
pub fn breakpoint() {
unsafe { ::std::intrinsics::breakpoint() };
}
// Workaround for lack of... | random_line_split | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(env)]
#![feature(... |
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| {
unsafe { ::std::intrinsics::breakpoint() };
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(env)]
#![feature(... | <T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| arc_ptr_eq | identifier_name |
tests.py |
@skipUnlessDBFeature("has_transform_method")
def test03_transform_related(self):
"Testing the `transform` GeoQuerySet method on related geographic models."
# All the transformations are to state plane coordinate systems using
# US Survey Feet (thus a tolerance of 0 implies error w/in 1... | "Testing `select_related` on geographic models (see #7126)."
qs1 = City.objects.order_by('id')
qs2 = City.objects.order_by('id').select_related()
qs3 = City.objects.order_by('id').select_related('location')
# Reference data for what's in the fixtures.
cities = (
('Au... | identifier_body | |
tests.py | 484839 7069381.28722222)'),
)
for name, srid, wkt in transformed:
# Doing this implicitly sets `select_related` select the location.
# TODO: Fix why this breaks on Oracle.
qs = list(City.objects.filter(name=name).transform(srid, field_name='location__p... |
# Should return the first Parcel, which has the center point equal
# to the point in the City ForeignKey.
qs = Parcel.objects.filter(center1=F('city__location__point'))
self.assertEqual(1, len(qs))
self.assertEqual('P1', qs[0].name)
if connection.features.supports_tran... | qs = Parcel.objects.filter(center2__within=F('border1'))
self.assertEqual(1, len(qs))
self.assertEqual('P2', qs[0].name) | conditional_block |
tests.py | 484839 7069381.28722222)'),
)
for name, srid, wkt in transformed:
# Doing this implicitly sets `select_related` select the location.
# TODO: Fix why this breaks on Oracle.
qs = list(City.objects.filter(name=name).transform(srid, field_name='location__p... | if connection.features.supports_transform:
# This time the city column should be wrapped in transformation SQL.
qs = Parcel.objects.filter(border2__contains=F('city__location__point'))
self.assertEqual(1, len(qs))
self.assertEqual('P1', qs[0].name)
def test07... | random_line_split | |
tests.py | 484839 7069381.28722222)'),
)
for name, srid, wkt in transformed:
# Doing this implicitly sets `select_related` select the location.
# TODO: Fix why this breaks on Oracle.
qs = list(City.objects.filter(name=name).transform(srid, field_name='location__p... | (self):
"Testing F() expressions on GeometryFields."
# Constructing a dummy parcel border and getting the City instance for
# assigning the FK.
b1 = GEOSGeometry(
'POLYGON((-97.501205 33.052520,-97.501205 33.052576,'
'-97.501150 33.052576,-97.501150 33.052520,-97.... | test06_f_expressions | identifier_name |
init.js | 'use strict';
//使用应用名和依赖定义主模块
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// 启动HTML location模式
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider',
function ($locationProvider, $... | State(state, params) {
// only store this state if it shouldn't be ignored
if (!state.data || !state.data.ignoreState) {
$state.previous = {
state: state,
params: params,
href: $state.href(state, params)
};
}
}
});
//定义启动application的初始化方法
angular.element(document).rea... | e.go('authentication.signin').then(function () {
//保存要去的状态和参数,当登录之后可以继续
storePreviousState(toState, toParams);
});
}
}
}
});
// 监听路由改变事件来保存历史State
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
... | conditional_block |
init.js | 'use strict';
//使用应用名和依赖定义主模块
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// 启动HTML location模式
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider',
function ($locationProvider, $... | ent.title, window.location.pathname);
} else {
// Prevent scrolling by storing the page's current scroll offset
var scroll = {
top: document.body.scrollTop,
left: document.body.scrollLeft
};
window.location.hash = '';
// Restore the scroll offset, should be flicker free... | 化方法
angular.element(document).ready(function () {
//Fixing facebook bug with redirect
if (window.location.hash && window.location.hash === '#_=_') {
if (window.history && history.pushState) {
window.history.pushState('', docum | identifier_body |
init.js | 'use strict';
//使用应用名和依赖定义主模块
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// 启动HTML location模式
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider',
function ($locationProvider, $... | 启动application的初始化方法
angular.element(document).ready(function () {
//Fixing facebook bug with redirect
if (window.location.hash && window.location.hash === '#_=_') {
if (window.history && history.pushState) {
window.history.pushState('', document.title, window.location.pathname);
} else {
// Prev... | }
}
});
//定义 | identifier_name |
init.js | 'use strict';
//使用应用名和依赖定义主模块
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// 启动HTML location模式
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider',
function ($locationProvider, $... | if (!state.data || !state.data.ignoreState) {
$state.previous = {
state: state,
params: params,
href: $state.href(state, params)
};
}
}
});
//定义启动application的初始化方法
angular.element(document).ready(function () {
//Fixing facebook bug with redirect
if (window.location.has... | function storePreviousState(state, params) {
// only store this state if it shouldn't be ignored | random_line_split |
UserHeader.tsx | import React from 'react';
import PropTypes from 'prop-types';
import Avatar from 'components/Avatar/Avatar';
import Icon from 'components/Icon/Icon';
require('./userHeader.scss');
const propTypes = {
userData: PropTypes.object.isRequired,
isUser: PropTypes.bool,
};
const defaultProps = {
isUser: false,
};
const... | </div>
</div>
</div>
);
};
UserHeader.defaultProps = defaultProps;
UserHeader.propTypes = propTypes;
export default UserHeader; | {link.value}
</a>
);
})} | random_line_split |
schematic-test-runner.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
* | import { DelegateTree, Tree } from '@angular-devkit/schematics';
import { Observable } from 'rxjs/Observable';
export declare class UnitTestTree extends DelegateTree {
readonly files: string[];
}
export declare class SchematicTestRunner {
private _collectionName;
private _engineHost;
private _engine;
... | * Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { logging } from '@angular-devkit/core'; | random_line_split |
schematic-test-runner.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { logging } from '@angular-devkit/core';
import { DelegateTree, Tree } from '@angular-devkit/schematics';
impo... | extends DelegateTree {
readonly files: string[];
}
export declare class SchematicTestRunner {
private _collectionName;
private _engineHost;
private _engine;
private _collection;
private _logger;
private _registry;
constructor(_collectionName: string, collectionPath: string);
readonl... | UnitTestTree | identifier_name |
main_server_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
... | General Public License version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from __future__ import absolute_import... | random_line_split | |
main_server_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
... |
# startup the other reactor via popen as it's non-blocking
proc = subprocess.Popen(['subprogram_reactor_string_weblog'], shell=False)
logging.info("Reactor PID: %s", proc.pid)
# fire up uwsgi server
proc_web_app = subprocess.Popen(['uwsgi', '--socket', '0.0.0.0:8081', '--protocol', 'http',
'--chdir=./serve... | logging.critical("Cannot generate SSL certificate. Exiting.....")
sys.exit() | conditional_block |
defaults.js | get the user started
staticFavourites: [
{
id: 0,
name: "Rainbow",
cmds: [
{"id":1,"cmd":"set 000 180064;"},
{"id":2,"cmd":"set 011 0C0032;"},
{"id":3,"cmd":"set 022 060019;"},
{"id":4,"cmd":"set 033 03000C;"},
{"id":5,"cmd":"set 0... | colour: "b7ff00",
}
],
| random_line_split | |
appliance.py | import attr
import pytest
import warnings
from fixtures import terminalreporter
from cfme.utils import conf
from cfme.utils.path import log_path
from cfme.utils.appliance import (
load_appliances_from_config, stack,
DummyAppliance, IPAppliance,
ApplianceSummoningWarning)
warnings.simplefilter('error', Ap... | held_appliance = attr.ib()
appliances = attr.ib(default=attr.Factory(list))
@pytest.fixture(scope="session")
def appliance(self):
return self.held_appliance
def pytest_sessionstart(self):
if isinstance(self.held_appliance, DummyAppliance):
return
if pytest.store.par... | identifier_body | |
appliance.py | import attr
import pytest
import warnings
from fixtures import terminalreporter
from cfme.utils import conf
from cfme.utils.path import log_path
from cfme.utils.appliance import (
load_appliances_from_config, stack,
DummyAppliance, IPAppliance,
ApplianceSummoningWarning)
warnings.simplefilter('error', Ap... |
if not stack.top:
for appliance in appliances:
reporter.write_line('* {!r}'.format(appliance), cyan=True)
appliance = appliances[0]
appliance.set_session_timeout(86400)
stack.push(appliance)
plugin = ApplianceHolderPlugin(appliance, appliances)
config.pluginmanager.register... | appliances = load_appliances_from_config(conf.env)
reporter.write_line('Retrieved these appliances from the conf.env', red=True) | conditional_block |
appliance.py | import attr
import pytest
import warnings
from fixtures import terminalreporter
from cfme.utils import conf
from cfme.utils.path import log_path
from cfme.utils.appliance import (
load_appliances_from_config, stack,
DummyAppliance, IPAppliance,
ApplianceSummoningWarning)
warnings.simplefilter('error', Ap... | (self):
return self.held_appliance
def pytest_sessionstart(self):
if isinstance(self.held_appliance, DummyAppliance):
return
if pytest.store.parallelizer_role != 'slave':
with log_path.join('appliance_version').open('w') as appliance_version:
applianc... | appliance | identifier_name |
appliance.py | import attr
import pytest
import warnings
from fixtures import terminalreporter
from cfme.utils import conf
from cfme.utils.path import log_path
from cfme.utils.appliance import (
load_appliances_from_config, stack,
DummyAppliance, IPAppliance,
ApplianceSummoningWarning)
warnings.simplefilter('error', Ap... | reporter.write_line('Retrieved Dummy Appliance', red=True)
elif config.option.appliances:
appliances = appliances_from_cli(config.option.appliances)
reporter.write_line('Retrieved these appliances from the --appliance parameters', red=True)
elif config.getoption('--use-sprout'):
... | appliances = [stack.top]
elif config.getoption('--dummy-appliance'):
appliances = [DummyAppliance.from_config(config)] | random_line_split |
neural_nets.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | h = tf.nn.relu(h)
scale = tf.nn.tanh(self.scale_layer(h)) * tf.exp(self.coeff_scale)
translation = self.translation_layer(h)
transformation = (
tf.nn.tanh(self.transformation_layer(h)) * tf.exp(
self.coeff_transformation))
return scale, translation, transformation
def _custom_... | random_line_split | |
neural_nets.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (units, factor=1.):
"""Custom dense layer with specified weight initialization."""
return tf.keras.layers.Dense(
units=units,
use_bias=True,
kernel_initializer=tf.contrib.layers.variance_scaling_initializer(
factor=factor * 2., mode='FAN_IN', uniform=False),
bias_initializer=tf.co... | _custom_dense | identifier_name |
neural_nets.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def call(self, inputs):
v, x, t = inputs
h = self.v_layer(v) + self.x_layer(x) + self.t_layer(t)
h = tf.nn.relu(h)
h = self.h_layer(h)
h = tf.nn.relu(h)
scale = tf.nn.tanh(self.scale_layer(h)) * tf.exp(self.coeff_scale)
translation = self.translation_layer(h)
transformation = (
... | super(GenericNet, self).__init__()
self.v_layer = _custom_dense(n_hidden, 1. / 3.)
self.x_layer = _custom_dense(n_hidden, factor / 3.)
self.t_layer = _custom_dense(n_hidden, 1. / 3.)
self.h_layer = _custom_dense(n_hidden)
# Scale
self.scale_layer = _custom_dense(x_dim, .001)
self.coeff_sca... | identifier_body |
cs_matrix.rs | #![cfg_attr(rustfmt, rustfmt_skip)]
use na::{Matrix4x5, Matrix5x4, CsMatrix};
#[test]
fn | () {
let m = Matrix4x5::new(
4.0, 1.0, 4.0, 0.0, 9.0,
5.0, 6.0, 0.0, 8.0, 10.0,
9.0, 10.0, 11.0, 12.0, 0.0,
0.0, 0.0, 1.0, 0.0, 10.0
);
let cs: CsMatrix<_, _, _> = m.into();
assert!(cs.is_sorted());
let cs_transposed = cs.transpose();
assert!(cs_transposed.is_so... | cs_transpose | identifier_name |
cs_matrix.rs | #![cfg_attr(rustfmt, rustfmt_skip)]
use na::{Matrix4x5, Matrix5x4, CsMatrix};
#[test]
fn cs_transpose() {
let m = Matrix4x5::new(
4.0, 1.0, 4.0, 0.0, 9.0,
5.0, 6.0, 0.0, 8.0, 10.0,
9.0, 10.0, 11.0, 12.0, 0.0, | 0.0, 0.0, 1.0, 0.0, 10.0
);
let cs: CsMatrix<_, _, _> = m.into();
assert!(cs.is_sorted());
let cs_transposed = cs.transpose();
assert!(cs_transposed.is_sorted());
let cs_transposed_mat: Matrix5x4<_> = cs_transposed.into();
assert_eq!(cs_transposed_mat, m.transpose())
} | random_line_split | |
cs_matrix.rs | #![cfg_attr(rustfmt, rustfmt_skip)]
use na::{Matrix4x5, Matrix5x4, CsMatrix};
#[test]
fn cs_transpose() | {
let m = Matrix4x5::new(
4.0, 1.0, 4.0, 0.0, 9.0,
5.0, 6.0, 0.0, 8.0, 10.0,
9.0, 10.0, 11.0, 12.0, 0.0,
0.0, 0.0, 1.0, 0.0, 10.0
);
let cs: CsMatrix<_, _, _> = m.into();
assert!(cs.is_sorted());
let cs_transposed = cs.transpose();
assert!(cs_transposed.is_sorte... | identifier_body | |
unit_action_system.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including wi... |
}
}
}
}
| {
attach_action_component!(*action, entity, &mut mtps);
} | conditional_block |
unit_action_system.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including wi... | // The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PU... | // furnished to do so, subject to the following conditions:
// | random_line_split |
unit_action_system.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including wi... | (&mut self, arg: specs::RunArg, time_step: Fixed) {
fetch_components!(arg, entities, [
mut components(action_queues: ActionQueueComponent),
mut components(mtps: MoveToPositionActionComponent),
mut resource(action_batcher: ActionBatcher),
]);
self.turn_accumul... | update | identifier_name |
ol3-layerswitcher.js | /**
* OpenLayers 3 Layer Switcher Control.
* See [the examples](./examples) for usage.
* @constructor
* @extends {ol.control.Control}
* @param {Object} opt_options Control options, extends olx.control.ControlOptions adding:
* **`tipLabel`** `String` - the button tooltip.
*/
ol.contro... |
this.mapListeners.length = 0;
// Wire up listeners etc. and store reference to new map
ol.control.Control.prototype.setMap.call(this, map);
if (map) {
var this_ = this;
this.mapListeners.push(map.on('pointerdown', function() {
this_.hidePanel();
}));
this.ren... | {
this.getMap().unByKey(this.mapListeners[i]);
} | conditional_block |
ol3-layerswitcher.js | /**
* OpenLayers 3 Layer Switcher Control.
* See [the examples](./examples) for usage.
* @constructor
* @extends {ol.control.Control}
* @param {Object} opt_options Control options, extends olx.control.ControlOptions adding:
* **`tipLabel`** `String` - the button tooltip.
*/
ol.contro... | ol.control.Control.call(this, {
element: element,
target: options.target
});
};
ol.inherits(ol.control.LayerSwitcher, ol.control.Control);
/**
* Show the layer panel.
*/
ol.control.LayerSwitcher.prototype.showPanel = function() {
if (this.element.className != this.shownClassName) {
... | }
};
| random_line_split |
wsgi.py | """
WSGI config for server_admin project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | sys.path.append('/home/terrywong/server_admin')
sys.path.append('/home/terrywong/server_admin/server_admin')
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon ... |
"""
import os, sys | random_line_split |
scheduler_bg.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.sh... | print('job: %s trigger: %s nextrun: %s' % (job.name, job.trigger, job.next_run_time.strftime("%Y-%m-%d %H:%M:%S"))) | conditional_block |
scheduler_bg.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
def job_function():
print('Hello! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = BackgroundScheduler()
url = sys.argv[1] if len(sys.argv) > 1 else 'sqlite:///example.sqlite'
scheduler.add_jobstore('sqlalchemy', url=url)
#interval example
scheduler.add_j... | print('Alarm! This alarm was scheduled at %s.' % time) | identifier_body |
scheduler_bg.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | print('job: %s trigger: %s nextrun: %s' % (job.name, job.trigger, job.next_run_time.strftime("%Y-%m-%d %H:%M:%S")))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, Syste... |
jobs = scheduler.get_jobs()
for job in jobs: | random_line_split |
scheduler_bg.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ():
print('Tick! The time is: %s' % datetime.now())
def alarm(time):
print('Alarm! This alarm was scheduled at %s.' % time)
def job_function():
print('Hello! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = BackgroundScheduler()
url = sys.argv[1] if len(sys.argv... | tick | identifier_name |
test_devstack.py | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
def test_construct(self):
self.assertEqual(self.engine.localrc["ADMIN_PASSWORD"], "secret")
@mock.patch("rally.deploy.engines.devstack.open", create=True)
def test_prepare_server(self, m_open):
m_open.return_value = "fake_file"
server = mock.Mock()
server.password = "secre... | self.deployment = SAMPLE_CONFIG.copy()
self.deployment["config"] = {"type": 42}
engine = devstack.DevstackEngine(self.deployment)
self.assertRaises(jsonschema.ValidationError,
engine.validate) | identifier_body |
test_devstack.py | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | SAMPLE_CONFIG = {
"type": "DevstackEngine",
"provider": {
"name": "ExistingServers",
"credentials": [{"user": "root", "host": "example.com"}],
},
"localrc": {
"ADMIN_PASSWORD": "secret",
},
}
DEVSTACK_REPO = "https://git.openstack.org/cgit/openstack-dev/devstack.git"
class... | random_line_split | |
test_devstack.py | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | (self):
self.assertEqual(self.engine.localrc["ADMIN_PASSWORD"], "secret")
@mock.patch("rally.deploy.engines.devstack.open", create=True)
def test_prepare_server(self, m_open):
m_open.return_value = "fake_file"
server = mock.Mock()
server.password = "secret"
self.engine.p... | test_construct | identifier_name |
suggestOvertypingCapturer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
if (!editor.hasModel()) {
return;
}
const selections = editor.getSelections();
const selectionsLength = selections.length;
// Check if it will overtype any selections
let willOvertype = false;
for (let i = 0; i < selectionsLength; i++) {
if (!selections[i].isEmpty()) {
willOvertype ... | {
return;
} | conditional_block |
suggestOvertypingCapturer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
dispose() {
this._disposables.dispose();
}
}
| {
if (!this._empty && idx >= 0 && idx < this._lastOvertyped.length) {
return this._lastOvertyped[idx];
}
return undefined;
} | identifier_body |
suggestOvertypingCapturer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
}));
}
getLastOvertypedInfo(idx: number): { value: string; multiline: boolean } | undefined {
if (!this._empty && idx >= 0 && idx < this._lastOvertyped.length) {
return this._lastOvertyped[idx];
}
return undefined;
}
dispose() {
this._disposables.dispose();
}
} | random_line_split | |
suggestOvertypingCapturer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
this._disposables.dispose();
}
}
| dispose | identifier_name |
hashalgo.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... |
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
... | self.update(data) | conditional_block |
hashalgo.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... | (self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may ... | digest | identifier_name |
hashalgo.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... | #: The size of the resulting hash in bytes.
digest_size = None
#: The internal block size of the hash algorithm in bytes.
block_size = None
def __init__(self, hashFactory, data=None):
"""Initialize the hash object.
:Parameters:
hashFactory : callable
An object ... | :undocumented: block_size
"""
| random_line_split |
hashalgo.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... |
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
... | """Initialize the hash object.
:Parameters:
hashFactory : callable
An object that will generate the actual hash implementation.
*hashFactory* must have a *new()* method, or must be directly
callable.
data : byte string
The very first chunk of th... | identifier_body |
DndSelectLabel.test.tsx | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | onChange: jest.fn(),
options: { string: { column_name: 'Column' } },
};
test('renders with default props', async () => {
render(<DndSelectLabel {...defaultProps} />, { useDnd: true });
expect(await screen.findByText('Drop columns here')).toBeInTheDocument();
});
test('renders ghost button when empty', async (... | valuesRenderer: () => <span />, | random_line_split |
multi_store_password_ui_entry.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview MultiStorePasswordUiEntry is used for showing entries that
* are duplicated across stores as a single item in the UI.
*/
import {a... |
this.setId(otherEntry.id, otherEntry.fromAccountStore);
return true;
}
get urls(): chrome.passwordsPrivate.UrlCollection {
return this.contents_.urls;
}
get username(): string {
return this.contents_.username;
}
get password(): string {
return this.password_;
}
set password(pass... | {
return false;
} | conditional_block |
multi_store_password_ui_entry.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview MultiStorePasswordUiEntry is used for showing entries that
* are duplicated across stores as a single item in the UI.
*/
import {a... |
get urls(): chrome.passwordsPrivate.UrlCollection {
return this.contents_.urls;
}
get username(): string {
return this.contents_.username;
}
get password(): string {
return this.password_;
}
set password(password: string) {
this.password_ = password;
}
get federationText(): (strin... | } | random_line_split |
multi_store_password_ui_entry.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview MultiStorePasswordUiEntry is used for showing entries that
* are duplicated across stores as a single item in the UI.
*/
import {a... |
get username(): string {
return this.contents_.username;
}
get password(): string {
return this.password_;
}
set password(password: string) {
this.password_ = password;
}
get federationText(): (string|undefined) {
return this.contents_.federationText;
}
/**
* Extract all the i... | {
return this.contents_.urls;
} | identifier_body |
multi_store_password_ui_entry.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview MultiStorePasswordUiEntry is used for showing entries that
* are duplicated across stores as a single item in the UI.
*/
import {a... | extends MultiStoreIdHandler {
private contents_: MultiStorePasswordUiEntryContents;
private password_: string = '';
constructor(entry: chrome.passwordsPrivate.PasswordUiEntry) {
super();
this.contents_ = MultiStorePasswordUiEntry.getContents_(entry);
this.setId(entry.id, entry.fromAccountStore);
... | MultiStorePasswordUiEntry | identifier_name |
op.rs | /*
* niepce - engine/library/op.rs
*
* Copyright (C) 2017-2019 Hubert Figuière
*
* 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 option) an... |
pub fn execute(self, lib: &Library) -> bool {
(self.op)(lib)
}
}
|
Op { op: Arc::new(f) }
}
| identifier_body |
op.rs | /*
* niepce - engine/library/op.rs
*
* Copyright (C) 2017-2019 Hubert Figuière
*
* 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 option) an... | F: Fn(&Library) -> bool + Send + Sync + 'static,
{
Op { op: Arc::new(f) }
}
pub fn execute(self, lib: &Library) -> bool {
(self.op)(lib)
}
} | random_line_split | |
op.rs | /*
* niepce - engine/library/op.rs
*
* Copyright (C) 2017-2019 Hubert Figuière
*
* 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 option) an... | self, lib: &Library) -> bool {
(self.op)(lib)
}
}
| xecute( | identifier_name |
kda.js | angular.module('app.controllers.kda', ['app.services.data', 'app.services.options'])
.controller('KdaController', ['$scope', 'Data', 'Options', function ($scope, Data, Options) {
console.log('kda chart controller', $scope)
Data.data.getKdaData($scope);
$scope.$watch('kills + deaths + assists', function()... | },
{
value : $scope.deaths,
color : "rgba(189,16,13,1)"
},
{
value: $scope.assists,
color: "rgba(88,156,173,1)"
}
];
}
})
$scope.options = Options.kdaOptions
}]) | random_line_split | |
kda.js | angular.module('app.controllers.kda', ['app.services.data', 'app.services.options'])
.controller('KdaController', ['$scope', 'Data', 'Options', function ($scope, Data, Options) {
console.log('kda chart controller', $scope)
Data.data.getKdaData($scope);
$scope.$watch('kills + deaths + assists', function()... |
})
$scope.options = Options.kdaOptions
}]) | {
$scope.chart = [
{
value: $scope.kills,
color: "rgba(22,79,16,1)"
},
{
value : $scope.deaths,
color : "rgba(189,16,13,1)"
},
{
value: $scope.assists,
color: "rgba(88,156,173,1)"
... | conditional_block |
octokit.ts | /**
* The following file contains a modified version of the Microsoft implementation of
* communication with GitHub's REST APIs.
*
* The original is available at
* https://github.com/microsoft/vscode-github-triage-actions/blob/eb561150d9bfab77954cfda7ffef149c07e0e079/api/octokit.ts
*/
import {Octokit, RestEndpoi... | else {
await setTimeout.__promisify__(30000);
}
};
const q = `${query.q} repo:${this.params.owner}/${this.params.repo}`;
const response = this.octokit.paginate.iterator(this.octokit.search.issuesAndPullRequests, {
...query,
q,
per_page: 100,
// To access reactions we... | {
await setTimeout.__promisify__(10000);
} | conditional_block |
octokit.ts | /**
* The following file contains a modified version of the Microsoft implementation of
* communication with GitHub's REST APIs.
*
* The original is available at
* https://github.com/microsoft/vscode-github-triage-actions/blob/eb561150d9bfab77954cfda7ffef149c07e0e079/api/octokit.ts
*/
import {Octokit, RestEndpoi... |
log(`Fetching issue #${this.issueData.number}`);
const issue = (
await this.octokit.issues.get({
...this.params,
issue_number: this.issueData.number,
// To access reactions we need a specific media type
// https://docs.github.com/en/rest/reference/repos#list-commit-comment... | random_line_split | |
octokit.ts | /**
* The following file contains a modified version of the Microsoft implementation of
* communication with GitHub's REST APIs.
*
* The original is available at
* https://github.com/microsoft/vscode-github-triage-actions/blob/eb561150d9bfab77954cfda7ffef149c07e0e079/api/octokit.ts
*/
import {Octokit, RestEndpoi... |
async *query(query: Query): AsyncIterableIterator<GitHubIssueAPI> {
let pageNum = 0;
const timeout = async () => {
if (pageNum < 2) {
/* pass */
} else if (pageNum < 4) {
await setTimeout.__promisify__(10000);
} else {
await setTimeout.__promisify__(30000);
}... | {
this._octokit = new Octokit({auth: token});
} | identifier_body |
octokit.ts | /**
* The following file contains a modified version of the Microsoft implementation of
* communication with GitHub's REST APIs.
*
* The original is available at
* https://github.com/microsoft/vscode-github-triage-actions/blob/eb561150d9bfab77954cfda7ffef149c07e0e079/api/octokit.ts
*/
import {Octokit, RestEndpoi... | (
issue: IssuesGetResponse | SearchIssuesAndPullRequestsResponseItemsItem,
): Issue {
return {
author: {name: issue.user!.login, isGitHubApp: issue.user!.type === 'Bot'},
body: issue.body || '',
number: issue.number,
title: issue.title,
labels: issue.labels.map((label) => (typeof... | octokitIssueToIssue | identifier_name |
fullscreen.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // A... | (cm) {
var wrap = cm.getWrapperElement();
cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
width: wrap.style.width, height: wrap.style.height};
wrap.style.width = "";
wrap.style.height = "auto";
wrap.className += " CodeMir... | setFullscreen | identifier_name |
fullscreen.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // A... | cm.refresh();
}
}); | wrap.style.width = info.width; wrap.style.height = info.height;
window.scrollTo(info.scrollLeft, info.scrollTop); | random_line_split |
fullscreen.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // A... |
}); | {
var wrap = cm.getWrapperElement();
wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
document.documentElement.style.overflow = "";
var info = cm.state.fullScreenRestore;
wrap.style.width = info.width; wrap.style.height = info.height;
window.scrollTo(info.scrollLeft, in... | identifier_body |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... |
d.clone_inner().set_source_id(registry.clone()).into_dependency()
});
let mut new_manifest = pkg.manifest().clone();
new_manifest.set_summary(new_summary.override_id(new_pkgid));
let new_pkg = Package::new(new_manifest, &manifest_path);
// Now that we've rewritten all our path dependencies... | { return d } | conditional_block |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... | $(
if $(md.$field.as_ref().map_or(true, |s| s.is_empty()))&&* {
$(missing.push(stringify!($field).replace("_", "-"));)*
}
)*
}}
}
lacking!(description, license || license_file, documentation || homepage || repository);
if !... | ($( $($field: ident)||* ),*) => {{ | random_line_split |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... | (pkg: &Package, config: &Config) -> CargoResult<()> {
let wildcard = VersionReq::parse("*").unwrap();
let mut wildcard_deps = vec![];
for dep in pkg.dependencies() {
if dep.kind() != Kind::Development && dep.version_req() == &wildcard {
wildcard_deps.push(dep.name());
}
}
... | check_dependencies | identifier_name |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... | if &**file == dst { continue }
let relative = util::without_prefix(&file, &root).unwrap();
let relative = try!(relative.to_str().chain_error(|| {
human(format!("non-utf8 path in source directory: {}",
relative.display()))
}));
let mut file = ... | {
if fs::metadata(&dst).is_ok() {
return Err(human(format!("destination already exists: {}",
dst.display())))
}
try!(fs::create_dir_all(dst.parent().unwrap()));
let tmpfile = try!(File::create(dst));
// Prepare the encoder and its header
let filename ... | identifier_body |
__init__.py |
class ConnectionError (StandardError):
def __init__(self, msg="", error=None):
StandardError.__init__(self, msg)
self.error = error
def repr(self):
if self.error is not None:
return StandardError.repr(self) + ": " + repr(self.error)
else:
return Standa... | get_file | identifier_name | |
__init__.py | class NodeExists (ConnectionError):
def __init__(self, msg="node exists"):
ConnectionError.__init__(self, msg)
class FileError (ConnectionError):
def __init__(self, msg="file error", error=None):
ConnectionError.__init__(self, msg, error)
class UnknownFile (FileError):
def __init__(self, m... | return conn_class() | conditional_block | |
__init__.py | but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation,... |
def read_node(self, nodeid):
"""Read a node attr"""
raise NotImplementedError("read_node")
def update_node(self, nodeid, attr):
"""Write node attr"""
raise NotImplementedError("update_node")
def delete_node(self, nodeid):
"""Delete node"""
rais... | """Create a node"""
# TODO: document root creation
# proposal 1: if rootid is not set yet, then this node is root
# proposal 2: if parentids is [], then this node is root
# proposal 3: try to remove root concept from connection
raise NotImplementedError("create_node") | identifier_body |
__init__.py | but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation,... | """Create directory within node"""
raise NotImplementedError("create_dir")
def list_dir(self, nodeid, filename="/"):
"""
List data files in node
"""
raise NotImplementedError("list_dir")
def has_file(self, nodeid, filename):
raise NotImplementedError... | def create_dir(self, nodeid, filename): | random_line_split |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... | (&self, color: Color) {
unsafe {
fast_set(self.offscreen, color.data, self.size);
}
}
/// Scroll the display
pub fn scroll(&self, rows: usize, color: Color) {
if rows > 0 && rows < self.height {
let offset = rows * self.width;
unsafe {
... | set | identifier_name |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... |
}
/// Set the color
pub fn set(&self, color: Color) {
unsafe {
fast_set(self.offscreen, color.data, self.size);
}
}
/// Scroll the display
pub fn scroll(&self, rows: usize, color: Color) {
if rows > 0 && rows < self.height {
let offset = rows * ... | {
None
} | conditional_block |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... | }
}
/// A display
pub struct Display {
pub offscreen: *mut u32,
pub onscreen: *mut u32,
pub size: usize,
pub width: usize,
pub height: usize,
}
impl Display {
pub fn root() -> Option<Box<Self>> {
if let Some(mode_info) = unsafe { VBEMODEINFO } {
let ret = box Display {
... | VBEMODEINFO = None; | random_line_split |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... |
/// Scroll the display
pub fn scroll(&self, rows: usize, color: Color) {
if rows > 0 && rows < self.height {
let offset = rows * self.width;
unsafe {
fast_copy(self.offscreen, self.offscreen.offset(offset as isize), self.size - offset);
fast_set(... | {
unsafe {
fast_set(self.offscreen, color.data, self.size);
}
} | identifier_body |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct ButtonData {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// ... |
}
else {
self.set_focused(false);
}
false
}
fn on_click_dev(&self, c: Context, mouse_x: f64, mouse_y: f64) -> bool {
self.rect.on_click_dev(c, mouse_x, mouse_y)
}
fn mouse_relative(&self, c: Context, mouse_x: f64, mouse_y: f64,
... | {
(*cb.borrow())(self);
} | conditional_block |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct ButtonData {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// ... | }
fn get_data_mut<'a>(&'a self) -> RefMut<'a, ButtonData> {
self.data.borrow_mut()
}
}
macro_rules! impl_buttoni {
($t:ty, $id:ident) => (
impl ButtonI for $t {
fn get_data<'a>(&'a self) -> Ref<'a, ButtonData> {
self.$id.get_data()
}
... | self.data.borrow() | random_line_split |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct | {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// A button is a combination of text and a rect
#[derive(Clone)]
pub struct Button {
data: Rc<RefCell<ButtonData>>,
rect: Rect,
text: Text,
}
impl Button {
pub fn new<S: Into<String>>(name:... | ButtonData | identifier_name |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct ButtonData {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// ... |
fn get_local_data_mut<'a>(&'a self) -> RefMut<'a, ButtonData> {
self.data.borrow_mut()
}
pub fn set_on_click_fn(&mut self, cb: Box<Fn(&Button)>) {
self.get_local_data_mut().on_click_fn =
Some(Rc::new(RefCell::new(cb)));
}
pub fn set_on_drag_fn(&mut self, cb: Box<F... | {
self.data.borrow()
} | identifier_body |
games2csv.ts | import * as fs from 'fs'
import { ExportToCsv } from 'export-to-csv'
const gamesDir = process.argv[2]
const csvFilename = `${gamesDir}/games.csv`
const csvExporter = new ExportToCsv({
fieldSeparator: ',',
quoteStrings: '"',
showLabels: true,
useKeysAsHeaders: true,
});
const lineRegex = /\[([^"]+) "(.+)"\]/
c... |
})
allGameData.push(gameData)
})
const csvData = csvExporter.generateCsv(allGameData, true)
fs.writeFileSync(csvFilename, csvData)
| {
const match = line.match(lineRegex)
if (match) {
const [name, value] = match.slice(1, 3)
gameData[name] = value
}
} | conditional_block |
games2csv.ts | import * as fs from 'fs'
import { ExportToCsv } from 'export-to-csv'
| const csvExporter = new ExportToCsv({
fieldSeparator: ',',
quoteStrings: '"',
showLabels: true,
useKeysAsHeaders: true,
});
const lineRegex = /\[([^"]+) "(.+)"\]/
const allGameData = []
fs.readdirSync(gamesDir).sort().forEach(filename => {
const lines = fs.readFileSync(`${gamesDir}/${filename}`).toString().s... | const gamesDir = process.argv[2]
const csvFilename = `${gamesDir}/games.csv` | random_line_split |
Range.js | /* @flow */
import {
InputTypeComposer,
type ObjectTypeComposerFieldConfigAsObjectDefinition,
} from 'graphql-compose';
import { getTypeName, type CommonOpts, desc } from '../../../utils';
import { getAllAsFieldConfigMap } from '../../Commons/FieldNames';
export function getRangeITC<TContext>(
opts: CommonOpts<... | };
} | description, | random_line_split |
for.specs.js | const Promise = require('../../src');
const assert = require('chai').assert;
const sinon = require('sinon');
describe('flow control - #for', () => {
context('instance', () => {
it('when called 0 to 10, i variable must be from 0 to 10', done => {
let val = 0;
Promise.resolve()
.for(0, 10, (i) => assert.equ... | });
});
context('static', () => {
it('when called 0 to 10, i variable must be from 0 to 10', done => {
let val = 0;
Promise.for(0, 10, (i) => assert.equal(i, val++))
.then(() => done());
});
});
}); | Promise.resolve(val)
.for(0, 10, (i, v) => assert.equal(v, val))
.then(() => done()); | random_line_split |
config.rs | use rustc_serialize::*;
use std::path::Path;
use std::fs::File;
use toml::{Value};
use std::io::{Read};
#[derive(Debug, Clone)]
pub struct ServiceConfig {
pub name : String,
pub description : String,
pub group : String,
pub secret : String,
pub id : i32
}
impl Decodable ... | try!(s.emit_struct_field("name", 0, |s| {
s.emit_str(&self.name)
}));
try!(s.emit_struct_field("description", 1, |s| {
s.emit_str(&self.description)
}));
try!(s.emit_struct_field("id", 2, |s| {
s.emit_i32(self.id... |
impl Encodable for ServiceConfig {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("ServiceConfig", 4, |s| { | random_line_split |
config.rs | use rustc_serialize::*;
use std::path::Path;
use std::fs::File;
use toml::{Value};
use std::io::{Read};
#[derive(Debug, Clone)]
pub struct | {
pub name : String,
pub description : String,
pub group : String,
pub secret : String,
pub id : i32
}
impl Decodable for ServiceConfig {
fn decode<D: Decoder>(d: &mut D) -> Result<ServiceConfig, D::Error> {
d.read_struct("ServiceConfig", 4, |d| {
... | ServiceConfig | identifier_name |
get_room_visibility.rs | //! [GET /_matrix/client/r0/directory/list/room/{roomId}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-directory-list-room-roomid)
use ruma_api::ruma_api;
use ruma_identifiers::RoomId;
use crate::r0::room::Visibility;
ruma_api! {
metadata { | requires_authentication: false,
}
request {
/// The ID of the room of which to request the visibility.
#[ruma_api(path)]
pub room_id: RoomId,
}
response {
/// Visibility of the room.
pub visibility: Visibility,
}
error: crate::Error
} | description: "Get the visibility of a public room on a directory.",
name: "get_room_visibility",
method: GET,
path: "/_matrix/client/r0/directory/list/room/:room_id",
rate_limited: false, | random_line_split |
glm.py | """Interface to rpy2.glm
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import rpy2.robjects as robjects
r = robjects.r
def | (model, print_flag=True):
"""Submits model to r.lm and returns the result."""
model = r(model)
res = r.lm(model)
if print_flag:
print_summary(res)
return res
def logit_model(model,
family=robjects.r.binomial(),
weights=None,
print_flag=True):... | linear_model | identifier_name |
glm.py | """Interface to rpy2.glm
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import rpy2.robjects as robjects
r = robjects.r
def linear_model(model, print_flag=True):
"""Submits model to r.lm and returns the result."""
model = r(model)
res = r.lm(model)
if print... | var = t[0]
est = float(t[1])
error = float(t[2])
z = float(t[3])
res.append((var, est, error, z))
if line.startswith('Estimate'):
#print "startswith('Estimate')"
flag = True
return res, aic
def inject_col_dict(col_dict, pr... | #print "flag"
t = line.split()
#print "t: " + str(t) | random_line_split |
glm.py | """Interface to rpy2.glm
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import rpy2.robjects as robjects
r = robjects.r
def linear_model(model, print_flag=True):
"""Submits model to r.lm and returns the result."""
model = r(model)
res = r.lm(model)
if print... | """Copies data columns into the R global environment.
col_dict: map from attribute name to column of data
prefix: string prepended to the attribute names
"""
for name, col in col_dict.iteritems():
robjects.globalenv[prefix+name] = robjects.FloatVector(col) | identifier_body | |
glm.py | """Interface to rpy2.glm
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import rpy2.robjects as robjects
r = robjects.r
def linear_model(model, print_flag=True):
"""Submits model to r.lm and returns the result."""
model = r(model)
res = r.lm(model)
if print... |
return res
def logit_model(model,
family=robjects.r.binomial(),
weights=None,
print_flag=True):
"""Submits model to r.glm and returns the result."""
model = r(model)
if weights is None:
res = r.glm(model, family=family)
else:
weight_... | print_summary(res) | conditional_block |
preinstallprovprofile.ts | import path = require('path');
import sign = require('ios-signing-common/ios-signing-common');
import secureFilesCommon = require('securefiles-common/securefiles-common');
import tl = require('azure-pipelines-task-lib/task');
import os = require('os');
async function run() {
let secureFileId: string;
let secur... | try {
tl.setResourcePath(path.join(__dirname, 'task.json'));
// Check platform is macOS since demands are not evaluated on Hosted pools
if (os.platform() !== 'darwin') {
throw new Error(tl.loc('InstallRequiresMac'));
}
if (tl.getInput('provisioningProfileLocatio... | random_line_split | |
preinstallprovprofile.ts | import path = require('path');
import sign = require('ios-signing-common/ios-signing-common');
import secureFilesCommon = require('securefiles-common/securefiles-common');
import tl = require('azure-pipelines-task-lib/task');
import os = require('os');
async function run() | tl.setTaskVariable('APPLE_PROV_PROFILE_UUID', info.provProfileUUID);
// set the provisioning profile output variable.
tl.setVariable('provisioningProfileUuid', info.provProfileUUID);
tl.setVariable('provisioningProfileName', info.provProfileName);
... | {
let secureFileId: string;
let secureFileHelpers: secureFilesCommon.SecureFileHelpers;
try {
tl.setResourcePath(path.join(__dirname, 'task.json'));
// Check platform is macOS since demands are not evaluated on Hosted pools
if (os.platform() !== 'darwin') {
throw new Er... | identifier_body |
preinstallprovprofile.ts | import path = require('path');
import sign = require('ios-signing-common/ios-signing-common');
import secureFilesCommon = require('securefiles-common/securefiles-common');
import tl = require('azure-pipelines-task-lib/task');
import os = require('os');
async function | () {
let secureFileId: string;
let secureFileHelpers: secureFilesCommon.SecureFileHelpers;
try {
tl.setResourcePath(path.join(__dirname, 'task.json'));
// Check platform is macOS since demands are not evaluated on Hosted pools
if (os.platform() !== 'darwin') {
throw new... | run | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.