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
output7off.py
# THIS IS THE PYTHON CODE FOR PiFACE OUTPUT OFF # # Copyright (C) 2014 Tim Massey # # 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) any later version. # # This program is distributed in the hope that it will be useful, # 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 ...
random_line_split
stokes.py
# 24.05.2007, c # last revision: 25.02.2008 from sfepy import data_dir from sfepy.fem.periodic import * filename_mesh = data_dir + '/meshes/2d/special/channels_symm944t.mesh' if filename_mesh.find( 'symm' ): region_1 = { 'name' : 'Y1', 'select' : """elements of group 3""", } region_2 = { ...
'region' : ['Left', 'Right'], 'dofs' : {'u.all' : 'u.all', 'p.0' : 'p.0'}, 'match' : 'match_y_line', } functions = { 'match_y_line' : (match_y_line,), } ## # FE assembling parameters. fe = { 'chunk_size' : 100, 'cache_override' : True, } solver_0 = { 'name' : 'ls', 'kind' : 'ls.scipy_...
epbc_1 = { 'name' : 'u_rl',
random_line_split
stokes.py
# 24.05.2007, c # last revision: 25.02.2008 from sfepy import data_dir from sfepy.fem.periodic import * filename_mesh = data_dir + '/meshes/2d/special/channels_symm944t.mesh' if filename_mesh.find( 'symm' ):
+n (elements of group 2 *n elements of group 3) """, } region_320 = { 'name' : 'EBCGamma2', 'select' : """(elements of group 5 *n elements of group 4) +n (elements of group 1 *n elements...
region_1 = { 'name' : 'Y1', 'select' : """elements of group 3""", } region_2 = { 'name' : 'Y2', 'select' : """elements of group 4 +e elements of group 6 +e elements of group 8""", } region_4 = { 'name' : 'Y1Y2', 'select' : """r.Y1 +e ...
conditional_block
Rangoon.py
'''tzinfo timezone information for Asia/Rangoon.''' from pytz.tzinfo import DstTzInfo
class Rangoon(DstTzInfo): '''Asia/Rangoon timezone definition. See datetime.tzinfo for details''' zone = 'Asia/Rangoon' _utc_transition_times = [ d(1,1,1,0,0,0), d(1919,12,31,17,35,24), d(1942,4,30,17,30,0), d(1945,5,2,15,0,0), ] _transition_info = [ i(23100,0,'RMT'), i(23400,0,'BURT'), i(32...
from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i
random_line_split
Rangoon.py
'''tzinfo timezone information for Asia/Rangoon.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class
(DstTzInfo): '''Asia/Rangoon timezone definition. See datetime.tzinfo for details''' zone = 'Asia/Rangoon' _utc_transition_times = [ d(1,1,1,0,0,0), d(1919,12,31,17,35,24), d(1942,4,30,17,30,0), d(1945,5,2,15,0,0), ] _transition_info = [ i(23100,0,'RMT'), i(23400,0,'BURT'), i(32400,0,'JST'), ...
Rangoon
identifier_name
Rangoon.py
'''tzinfo timezone information for Asia/Rangoon.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Rangoon(DstTzInfo):
Rangoon = Rangoon()
'''Asia/Rangoon timezone definition. See datetime.tzinfo for details''' zone = 'Asia/Rangoon' _utc_transition_times = [ d(1,1,1,0,0,0), d(1919,12,31,17,35,24), d(1942,4,30,17,30,0), d(1945,5,2,15,0,0), ] _transition_info = [ i(23100,0,'RMT'), i(23400,0,'BURT'), i(32400,0,'JST'), i(23400,0,'MMT'),...
identifier_body
test_compare_components.py
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals import os import json from flexmock import flexmock from atomic_reactor.constants ...
(x, y): yield "some\u2018".encode('utf-8') flexmock(self.tasker, build_image_from_path=simplegen) def get_built_image_info(self): return {'Id': 'some'} def inspect_built_image(self): return None def ensure_not_built(self): pass def mock_workflow(tmpdir): ...
simplegen
identifier_name
test_compare_components.py
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals
from flexmock import flexmock from atomic_reactor.constants import (PLUGIN_FETCH_WORKER_METADATA_KEY, PLUGIN_COMPARE_COMPONENTS_KEY) from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.plugin import PostBuildPlugin...
import os import json
random_line_split
test_compare_components.py
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals import os import json from flexmock import flexmock from atomic_reactor.constants ...
def test_no_components(tmpdir): workflow = mock_workflow(tmpdir) worker_metadatas = mock_metadatas() # example data has 2 log items before component item hence output[2] del worker_metadatas['x86_64']['output'][2]['components'] del worker_metadatas['ppc64le']['output'][2]['components'] work...
runner.run()
conditional_block
test_compare_components.py
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals import os import json from flexmock import flexmock from atomic_reactor.constants ...
def get_dockerfile_path(self): return self.dockerfile_path, self.path class MockInsideBuilder(object): def __init__(self): mock_docker() self.tasker = DockerTasker() self.base_image = ImageName(repo='fedora', tag='25') self.image_id = 'image_id' self.image = ...
tmpdir = str(tmpdir) self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile') self.path = tmpdir
identifier_body
color.ts
import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color' import { FlowerSlot, Flower } from '../types/flower' export const percentageIndex = [ 0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32, 35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67, 70, 74, 77, 80, 83, 87, 90, 93, 96, 100 ] export con...
(value: number, bleach: number): number { if (bleach == 0){ return value } const bleached = value + (bleach * 16) return bleached > 87 ? 87 : bleached } function bleachStain(color: ColorPercentage, bleach: number): ColorPercentage { return [ bleachValue(color[Red], bleach), bleachValue(color[Green], bleac...
bleachValue
identifier_name
color.ts
import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color' import { FlowerSlot, Flower } from '../types/flower' export const percentageIndex = [ 0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32, 35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67, 70, 74, 77, 80, 83, 87, 90, 93, 96, 100 ] export con...
} export function hsvToRgb(hsv: Hsv): Rgb { const [hue, saturation, value] = hsv const max = (value * 2.55) | 0 const min = (max - ((saturation / 100) * max)) | 0 if (hue < 60){ return [max, ((hue / 60) * (max - min) + min) | 0, min] } else if (hue < 120){ return [(((120 - hue) / 60) * (max - min) + min) ...
{ const [red, green, blue] = rgb const max = Math.max(red, green, blue) const min = Math.min(red, green, blue) const hue = (min == max) ? 0 : (min == blue) ? (60 * ((green - red) / (max - min)) + 60) : (min == red) ? (60 * ((blue - green) / (max - min)) + 180) : (60 * ((red - blue) / (max - min))...
identifier_body
color.ts
import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color' import { FlowerSlot, Flower } from '../types/flower' export const percentageIndex = [ 0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32, 35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67, 70, 74, 77, 80, 83, 87, 90, 93, 96, 100 ] export con...
}
{ return [max, min, (((360 - hue) / 60) * (max - min) + min) | 0] }
conditional_block
color.ts
import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color' import { FlowerSlot, Flower } from '../types/flower' export const percentageIndex = [ 0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32, 35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67, 70, 74, 77, 80, 83, 87, 90, 93, 96, 100 ] export con...
if (hue < 60){ return [max, ((hue / 60) * (max - min) + min) | 0, min] } else if (hue < 120){ return [(((120 - hue) / 60) * (max - min) + min) | 0, max, min] } else if (hue < 180){ return [min, max, (((hue - 120) / 60) * (max - min) + min) | 0] } else if (hue < 240){ return [min, (((240 - hue) / 60) * (max ...
const max = (value * 2.55) | 0 const min = (max - ((saturation / 100) * max)) | 0
random_line_split
test_dms.py
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) #...
(self): return mda.Universe(DMS) @pytest.fixture() def ts(self, universe): return universe.trajectory.ts def test_global_cell(self, ts): assert ts.dimensions is None def test_velocities(self, ts): assert_equal(hasattr(ts, "_velocities"), False) def test_number_of_...
universe
identifier_name
test_dms.py
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) #...
"(0-based, should be 0 for single frame readers)") def test_frame_index_0(self, universe): universe.trajectory[0] assert_equal(universe.trajectory.ts.frame, 0, "frame number for frame index 0 should be 0") def test_frame_i...
def test_frame(self, universe): assert_equal(universe.trajectory.frame, 0, "wrong frame number "
random_line_split
test_dms.py
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) #...
def test_coords_atom_0(self, universe): # Desired coordinates taken directly from the SQLite file. Check unit # conversion coords_0 = np.array([-11.0530004501343, 26.6800003051758, 12.7419996261597, ], dt...
assert_equal(len(universe.atoms), 3341)
identifier_body
fixedaspectsvgwidget.py
# -*- coding: utf-8 -*- """ *************************************************************************** fixedaspectsvgwidget.py --------------------- Date : August 2016 Copyright : (C) 2016 Boundless, http://boundlessgeo.com ***************************************************...
(self, event): painter = QPainter(self) painter.setViewport(self.centeredViewport(self.size())) self.renderer().render(painter) def centeredViewport(self, size): width = size.width() height = size.height() aspectRatio = float(self.renderer().defaultSize().width()) ...
paintEvent
identifier_name
fixedaspectsvgwidget.py
# -*- coding: utf-8 -*- """ *************************************************************************** fixedaspectsvgwidget.py --------------------- Date : August 2016 Copyright : (C) 2016 Boundless, http://boundlessgeo.com ***************************************************...
def centeredViewport(self, size): width = size.width() height = size.height() aspectRatio = float(self.renderer().defaultSize().width()) / float(self.renderer().defaultSize().height()) heightFromWidth = int(width / aspectRatio) widthFromHeight = int(height * aspectRatio) ...
painter = QPainter(self) painter.setViewport(self.centeredViewport(self.size())) self.renderer().render(painter)
identifier_body
fixedaspectsvgwidget.py
# -*- coding: utf-8 -*- """ *************************************************************************** fixedaspectsvgwidget.py --------------------- Date : August 2016 Copyright : (C) 2016 Boundless, http://boundlessgeo.com ***************************************************...
__author__ = 'Alexander Bruy' __date__ = 'August 2016' __copyright__ = '(C) 2016 Boundless, http://boundlessgeo.com' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.PyQt.QtCore import QRect from qgis.PyQt.QtGui import QPainter from qgis.PyQt.QtSvg import QSvg...
* (at your option) any later version. * * * *************************************************************************** """
random_line_split
fixedaspectsvgwidget.py
# -*- coding: utf-8 -*- """ *************************************************************************** fixedaspectsvgwidget.py --------------------- Date : August 2016 Copyright : (C) 2016 Boundless, http://boundlessgeo.com ***************************************************...
else: return QRect((width - widthFromHeight) / 2, 0, widthFromHeight, height)
return QRect(0, (height - heightFromWidth) / 2, width, heightFromWidth)
conditional_block
downloadAsImage.ts
/** * 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...
}); }; }
{ return (event: SyntheticEvent) => { const elementToPrint = event.currentTarget.closest(selector); if (!elementToPrint) return addWarningToast( t('Image download failed, please refresh and try again.'), ); return domToImage .toJpeg(elementToPrint, { quality: 0.95, ...
identifier_body
downloadAsImage.ts
* 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 use this file except in compliance * with the License. ...
/** * Licensed to the Apache Software Foundation (ASF) under one
random_line_split
downloadAsImage.ts
/** * 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...
( selector: string, description: string, domToImageOptions: Options = {}, ) { return (event: SyntheticEvent) => { const elementToPrint = event.currentTarget.closest(selector); if (!elementToPrint) return addWarningToast( t('Image download failed, please refresh and try again.'), ); ...
downloadAsImage
identifier_name
scroll-tofixed-view.js
var $ = require('jquery'); var CoreView = require('backbone/core-view'); var checkAndBuildOpts = require('builder/helpers/required-opts'); var REQUIRED_OPTS = [ 'el' ]; module.exports = CoreView.extend({ events: { 'click .js-foo': '_fooHandler' }, initialize: function (opts) { checkAndBuildOpts(opts...
this._onWindowScroll = this._onWindowScroll.bind(this); this._topBoundary = this.$el.offset().top; this._initBinds(); }, _initBinds: function () { this._bindScroll(); }, _onWindowScroll: function () { this.$el.toggleClass('is-fixed', $(window).scrollTop() > this._topBoundary); }, _un...
random_line_split
jquery.loadHtml.js
/*! * ------------------------------ * jQuery.loadHtmlComponents.js v0.1.0 * http://anasnakawa.github.com/jquery.loadHtmlComponents * license: MIT license (http://opensource.org/licenses/MIT) * ------------------------------ */ // ------------------------------ // table of content // ----------------------------...
return $self.loadHtml(options); } }); }); }; $.fn.loadHtml = loadHtml; $.fn.loadHtml.defaults = defaults; })(jQuery);
// set state to ready $self.attr(state, done) if( $self.attr(options.attr + '-skip') !== 'true' ) {
random_line_split
jquery.loadHtml.js
/*! * ------------------------------ * jQuery.loadHtmlComponents.js v0.1.0 * http://anasnakawa.github.com/jquery.loadHtmlComponents * license: MIT license (http://opensource.org/licenses/MIT) * ------------------------------ */ // ------------------------------ // table of content // ----------------------------...
}); }); }; $.fn.loadHtml = loadHtml; $.fn.loadHtml.defaults = defaults; })(jQuery);
{ return $self.loadHtml(options); }
conditional_block
operation_display.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
super(OperationDisplay, self).__init__() self.provider = provider self.resource = resource self.operation = operation self.description = description
"""Display metadata associated with the operation. :param provider: Service provider: Microsoft Network. :type provider: str :param resource: Resource on which the operation is performed. :type resource: str :param operation: Type of the operation: get, read, delete, etc. :type operation: str ...
identifier_body
operation_display.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.provider = provider self.resource = resource self.operation = operation self.description = description
random_line_split
operation_display.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(self, provider=None, resource=None, operation=None, description=None): super(OperationDisplay, self).__init__() self.provider = provider self.resource = resource self.operation = operation self.description = description
__init__
identifier_name
devlinks.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::collections::HashSet; use std::io::ErrorKind; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}...
(pool_name: &str, fs_name: &str, devnode: &Path) { let p = filesystem_mount_path(pool_name, fs_name); // Remove existing and recreate to ensure it points to the correct devnode let _ = fs::remove_file(&p); if let Err(e) = symlink(devnode, &p) { warn!( "unable to create symlink for {...
filesystem_added
identifier_name
devlinks.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::collections::HashSet; use std::io::ErrorKind; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}...
if err.kind() != ErrorKind::AlreadyExists { return Err(From::from(err)); } } Ok(()) } /// Setup the pool directory and the symlinks in /stratis for the specified pool and filesystems /// it contains. // Don't just remove and recreate everything in case there are processes // (e.g. ...
pub fn setup_dev_path() -> StratisResult<()> { if let Err(err) = fs::create_dir(DEV_PATH) {
random_line_split
devlinks.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::collections::HashSet; use std::io::ErrorKind; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}...
} /// Create a directory when a pool is added. pub fn pool_added(pool: &str) { let p = pool_directory(pool); if let Err(e) = fs::create_dir(&p) { warn!("unable to create pool directory {:?}, reason {:?}", p, e); } } /// Remove the directory and its contents when the pool is removed. pub fn pool_r...
{ warn!("cleanup_devlinks failed, reason {:?}", err); }
conditional_block
devlinks.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::collections::HashSet; use std::io::ErrorKind; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}...
/// Remove the directory and its contents when the pool is removed. pub fn pool_removed(pool: &str) { let p = pool_directory(pool); if let Err(e) = fs::remove_dir_all(&p) { warn!("unable to remove pool directory {:?}, reason {:?}", p, e); } } /// Rename the directory to match the pool's new name....
{ let p = pool_directory(pool); if let Err(e) = fs::create_dir(&p) { warn!("unable to create pool directory {:?}, reason {:?}", p, e); } }
identifier_body
engageya.js
/** * Copyright 2021 The AMP HTML 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 require...
register('engageya', engageya); window.draw3p = draw3p;
random_line_split
fence_rmw.rs
//! This mod provides orderings to use with RMW operations //! that optimally handle the case when all loads and stores //! after an RMW operation must be ordered after the operation. //! # Example: //! ``` //! use std::sync::atomic::{AtomicUsize, fence, Ordering}; //! use atomic_utilities::fence_rmw::{RMWOrder, fence_...
} /// The ordering to be used for RMW operations in this fencing scheme #[allow(non_upper_case_globals)] pub const RMWOrder: Ordering = internal_ordering::RMW_O; /// The fence to be used after the RMW #[inline(always)] pub fn fence_rmw() { internal_ordering::the_fence() }
{ fence(Ordering::SeqCst) }
identifier_body
fence_rmw.rs
//! This mod provides orderings to use with RMW operations //! that optimally handle the case when all loads and stores //! after an RMW operation must be ordered after the operation. //! # Example: //! ``` //! use std::sync::atomic::{AtomicUsize, fence, Ordering}; //! use atomic_utilities::fence_rmw::{RMWOrder, fence_...
mod internal_ordering { use std::sync::atomic::{Ordering, fence}; pub const RMW_O: Ordering = Ordering::Relaxed; pub fn the_fence() { fence(Ordering::SeqCst) } } /// The ordering to be used for RMW operations in this fencing scheme #[allow(non_upper_case_globals)] pub const RMWOrder: Ordering =...
random_line_split
fence_rmw.rs
//! This mod provides orderings to use with RMW operations //! that optimally handle the case when all loads and stores //! after an RMW operation must be ordered after the operation. //! # Example: //! ``` //! use std::sync::atomic::{AtomicUsize, fence, Ordering}; //! use atomic_utilities::fence_rmw::{RMWOrder, fence_...
() { internal_ordering::the_fence() }
fence_rmw
identifier_name
admin-projects.js
'use strict'; angular.module('projects', ['ui.router']) .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('projects', { url: '/projects', controller: 'ProjectsCtrl' }) .state('projects.project', { url: '/:project', controller: 'P...
} self.submitProject = function() { var projectFields = self.projectFormData["_"+sref]; var newProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content}; console.log("Submitting: ", newProject); }...
{ console.log("Deleted: \n", delProject); }
conditional_block
admin-projects.js
'use strict'; angular.module('projects', ['ui.router']) .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('projects', { url: '/projects', controller: 'ProjectsCtrl' }) .state('projects.project', { url: '/:project', controller: 'P...
name: 'TileTraveler', placecard: 'composition-01.jpg', date: (new Date(2013, 11)).getTime(); sref: 'TileTraveler', content: '' }; var project2 = { name: 'GIS Lookup System', placecard: 'photoshoot-09.jpg', date: (new Date(2015, 5)).getTime(), sref: 'GIS', content: '' }; var project3 = { name:...
var project4 = {
random_line_split
poland.ts
import { Country } from '../jsvat'; export const poland: Country = { name: 'Poland', codes: ['PL', 'POL', '616'], calcFn: (vat: string): boolean => { let total = 0; // Extract the next digit and multiply by the counter. for (let i = 0; i < 9; i++) { total += Number(vat.charAt(i)) * poland.rule...
common: [6, 5, 7, 2, 3, 4, 5, 6, 7] }, regex: [/^(PL)(\d{10})$/] } };
random_line_split
poland.ts
import { Country } from '../jsvat'; export const poland: Country = { name: 'Poland', codes: ['PL', 'POL', '616'], calcFn: (vat: string): boolean => { let total = 0; // Extract the next digit and multiply by the counter. for (let i = 0; i < 9; i++) { total += Number(vat.charAt(i)) * poland.rule...
// Compare it with the last character of the VAT number. If it's the same, then it's valid. const expect = Number(vat.slice(9, 10)); return total === expect; }, rules: { multipliers: { common: [6, 5, 7, 2, 3, 4, 5, 6, 7] }, regex: [/^(PL)(\d{10})$/] } };
{ total = 0; }
conditional_block
lock.py
"""Locks on Zigbee Home Automation networks.""" import functools import voluptuous as vol from zigpy.zcl.foundation import Status from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform from homeas...
async def async_clear_lock_user_code(self, code_slot: int) -> None: """Clear the user_code at index X on the lock.""" if self._doorlock_channel: await self._doorlock_channel.async_clear_user_code(code_slot) self.debug("User code at slot %s cleared", code_slot)
await self._doorlock_channel.async_disable_user_code(code_slot) self.debug("User code at slot %s disabled", code_slot)
conditional_block
lock.py
"""Locks on Zigbee Home Automation networks.""" import functools import voluptuous as vol from zigpy.zcl.foundation import Status from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform from homeas...
(self, code_slot: int) -> None: """Disable user_code at index X on the lock.""" if self._doorlock_channel: await self._doorlock_channel.async_disable_user_code(code_slot) self.debug("User code at slot %s disabled", code_slot) async def async_clear_lock_user_code(self, code_s...
async_disable_lock_user_code
identifier_name
lock.py
"""Locks on Zigbee Home Automation networks.""" import functools import voluptuous as vol from zigpy.zcl.foundation import Status from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform from homeas...
async def async_disable_lock_user_code(self, code_slot: int) -> None: """Disable user_code at index X on the lock.""" if self._doorlock_channel: await self._doorlock_channel.async_disable_user_code(code_slot) self.debug("User code at slot %s disabled", code_slot) async...
"""Enable user_code at index X on the lock.""" if self._doorlock_channel: await self._doorlock_channel.async_enable_user_code(code_slot) self.debug("User code at slot %s enabled", code_slot)
identifier_body
lock.py
"""Locks on Zigbee Home Automation networks.""" import functools import voluptuous as vol from zigpy.zcl.foundation import Status from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform from homeas...
def __init__(self, unique_id, zha_device, channels, **kwargs): """Init this sensor.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._doorlock_channel = self.cluster_channels.get(CHANNEL_DOORLOCK) async def async_added_to_hass(self): """Run when about to be ad...
class ZhaDoorLock(ZhaEntity, LockEntity): """Representation of a ZHA lock."""
random_line_split
mock_executor.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use tipb::FieldType; use crate::interface::*; use tidb_query_common::storage::IntervalRange; use tidb_query_datatype::codec::batch::LazyBatchColumnVec; use tidb_query_datatype::codec::data_type::VectorValue; use tidb_query_datatype::expr::EvalWarnings...
(&mut self, _dest: &mut Self::StorageStats) { // Do nothing } fn take_scanned_range(&mut self) -> IntervalRange { // Do nothing unreachable!() } fn can_be_cached(&self) -> bool { false } }
collect_storage_stats
identifier_name
mock_executor.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use tipb::FieldType; use crate::interface::*; use tidb_query_common::storage::IntervalRange; use tidb_query_datatype::codec::batch::LazyBatchColumnVec; use tidb_query_datatype::codec::data_type::VectorValue; use tidb_query_datatype::expr::EvalWarnings...
fn can_be_cached(&self) -> bool { false } } pub struct MockScanExecutor { pub rows: Vec<i64>, pub pos: usize, schema: Vec<FieldType>, } impl MockScanExecutor { pub fn new(rows: Vec<i64>, schema: Vec<FieldType>) -> Self { MockScanExecutor { rows, pos: 0,...
unreachable!() }
random_line_split
win32.py
0], '@' + native_tmp + '\n' + rm, native_tmp ] # The upshot of all this is that, if you are using Python 1.5.2, # you had better have cmd or command.com in your PATH when you run # scons. def piped_spawn(sh, escape, cmd, args, env, stdout, stderr): # There is no direct way to do that in python. What we do # h...
random_line_split
win32.py
import string import sys import tempfile from SCons.Platform.posix import exitvalmap # XXX See note below about why importing SCons.Action should be # eventually refactored. import SCons.Action import SCons.Util class TempFileMunge: """A callable class. You can set an Environment variable to this, then call...
else: # one temporary file for stdout and stderr tmpFileStdout = os.path.normpath(tempfile.mktemp()) tmpFileStderr = os.path.normpath(tempfile.mktemp()) # check if output is redirected stdoutRedirected = 0 stderrRedirected = 0 for arg in args: # ...
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127
conditional_block
win32.py
import string import sys import tempfile from SCons.Platform.posix import exitvalmap # XXX See note below about why importing SCons.Action should be # eventually refactored. import SCons.Action import SCons.Util class TempFileMunge: """A callable class. You can set an Environment variable to this, then call ...
if env['SHELL'] and env['SHELL'] == 'sh': # The sh shell will try to escape the backslashes in the # path, so unescape them. native_tmp = string.replace(native_tmp, '\\', r'\\\\') # In Cygwin, we want to use rm to delete the temporary ...
if for_signature: return self.cmd cmd = env.subst_list(self.cmd, 0, target, source)[0] try: maxline = int(env.subst('$MAXLINELENGTH')) except ValueError: maxline = 2048 if (reduce(lambda x, y: x + len(y), cmd, 0) + len(cmd)) <= maxline: ret...
identifier_body
win32.py
import string import sys import tempfile from SCons.Platform.posix import exitvalmap # XXX See note below about why importing SCons.Action should be # eventually refactored. import SCons.Action import SCons.Util class TempFileMunge: """A callable class. You can set an Environment variable to this, then call ...
(sh, escape, cmd, args, env): if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 else: try: args = [sh, '/C', escape(string.join(args)) ] ret = os.spawnve(os.P_WAIT, sh, args, env) except OSError, e: ...
spawn
identifier_name
items.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { Observable, of } from 'rxjs'; import { delay } from 'rxjs/operators'; export class Item { constructor(public id: number, public name: string) { } } const ITEMS: Item[] = [ new Item(1, 'Sticky notes'), new Item(2, 'Dry erase markers'), new I...
() { console.log('ItemService instance created.'); } ngOnDestroy() { console.log('ItemService instance destroyed.'); } getItems(): Observable<Item[]> { return of(ITEMS).pipe(delay(FETCH_LATENCY)); } getItem(id: number | string): Observable<Item> { const item$ = of(ITEMS.find(item => item.id === +id))...
constructor
identifier_name
items.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { Observable, of } from 'rxjs'; import { delay } from 'rxjs/operators'; export class Item { constructor(public id: number, public name: string) { } } const ITEMS: Item[] = [ new Item(1, 'Sticky notes'), new Item(2, 'Dry erase markers'), new I...
constructor() { console.log('ItemService instance created.'); } ngOnDestroy() { console.log('ItemService instance destroyed.'); } getItems(): Observable<Item[]> { return of(ITEMS).pipe(delay(FETCH_LATENCY)); } getItem(id: number | string): Observable<Item> { const item$ = of(ITEMS.find(item => ite...
/** Simulate a data service that retrieves crises from a server */ @Injectable() export class ItemService implements OnDestroy {
random_line_split
group.rs
extern crate kiss3d; extern crate nalgebra as na; use na::Vec3; use kiss3d::window::Window; use kiss3d::light::Light; fn main()
while window.render() { g1.prepend_to_local_rotation(&Vec3::new(0.0f32, 0.014, 0.0)); g2.prepend_to_local_rotation(&Vec3::new(0.014f32, 0.0, 0.0)); } }
{ let mut window = Window::new("Kiss3d: cube"); let mut g1 = window.add_group(); let mut g2 = window.add_group(); g1.append_translation(&Vec3::new(2.0f32, 0.0, 0.0)); g2.append_translation(&Vec3::new(-2.0f32, 0.0, 0.0)); g1.add_cube(1.0, 5.0, 1.0); g1.add_cube(5.0, 1.0, 1.0); g2.add_...
identifier_body
group.rs
use kiss3d::window::Window; use kiss3d::light::Light; fn main() { let mut window = Window::new("Kiss3d: cube"); let mut g1 = window.add_group(); let mut g2 = window.add_group(); g1.append_translation(&Vec3::new(2.0f32, 0.0, 0.0)); g2.append_translation(&Vec3::new(-2.0f32, 0.0, 0.0)); g1.add_...
extern crate kiss3d; extern crate nalgebra as na; use na::Vec3;
random_line_split
group.rs
extern crate kiss3d; extern crate nalgebra as na; use na::Vec3; use kiss3d::window::Window; use kiss3d::light::Light; fn
() { let mut window = Window::new("Kiss3d: cube"); let mut g1 = window.add_group(); let mut g2 = window.add_group(); g1.append_translation(&Vec3::new(2.0f32, 0.0, 0.0)); g2.append_translation(&Vec3::new(-2.0f32, 0.0, 0.0)); g1.add_cube(1.0, 5.0, 1.0); g1.add_cube(5.0, 1.0, 1.0); g2.a...
main
identifier_name
springyui.js
// auto adjusting bounding box Springy.requestAnimationFrame(function adjust() { targetBB = layout.getBoundingBox(); // current gets 20% closer to target every iteration currentBB = { bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft) .divide(10)), topright: curre...
var stroke = (edge.data.color !== undefined) ? edge.data.color : '#000000'; var arrowWidth; var arrowLength; var weight = (edge.data.weight !== undefined) ? edge.data.weight : 1.0; ctx.lineWidth = Math.max(weight * 2, 0.1); arrowWidth = 1 + ctx.lineWidth; arrowLength = 8; var directional ...
{ intersection = s2; }
conditional_block
springyui.js
// auto adjusting bounding box Springy.requestAnimationFrame(function adjust() { targetBB = layout.getBoundingBox(); // current gets 20% closer to target every iteration currentBB = { bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft) .divide(10)), topright: curre...
ctx.translate(intersection.x, intersection.y); ctx.rotate(Math.atan2(y2 - y1, x2 - x1)); ctx.beginPath(); ctx.moveTo(-arrowLength, arrowWidth); ctx.lineTo(0, 0); ctx.lineTo(-arrowLength, -arrowWidth); ctx.lineTo(-arrowLength * 0.8, -0); ctx.closePath(); ctx.fill(); ctx.restore();...
ctx.fillStyle = stroke;
random_line_split
springyui.js
.image.src].loaded) { width = getImageWidth(this); } else {width = 10;} } return width; } var renderer = this.renderer = new Springy.Renderer(layout, function clear() { ctx.clearRect(0,0,canvas.width,canvas.height); }, function drawEdge(edge, p1, p2) { var x1 = toScreen(p1).x; var y1 = toSc...
{ var tl = {x: p3.x, y: p3.y}; var tr = {x: p3.x + w, y: p3.y}; var bl = {x: p3.x, y: p3.y + h}; var br = {x: p3.x + w, y: p3.y + h}; var result; if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right if ...
identifier_body
springyui.js
ragged.point.p.x = p.x; dragged.point.p.y = p.y; } renderer.start(); }); jQuery(window).bind('mouseup',function(e) { dragged = null; }); var getTextWidth = function(node) { var text = (node.data.label !== undefined) ? node.data.label : node.id; if (node._width && node._width[text]) return node._w...
intersect_line_line
identifier_name
record_backend.rs
extern crate chrono; extern crate mysql; use self::chrono::UTC; use self::chrono::offset::TimeZone; use self::mysql::conn::MyOpts; use self::mysql::conn::pool::MyPool; use self::mysql::error::MyResult; use self::mysql::value::from_row; use self::mysql::value::Value; use std::clone::Clone; use std::default::Default; us...
finished_at: finished_at } } } #[derive(Clone, Debug)] pub struct MysqlOptimizedUuid { uuid: String } impl MysqlOptimizedUuid { pub fn from_uuid (uuid: String) -> MysqlOptimizedUuid { // the optimized way https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/ let mut ordered_uuid...
started_at: started_at,
random_line_split
record_backend.rs
extern crate chrono; extern crate mysql; use self::chrono::UTC; use self::chrono::offset::TimeZone; use self::mysql::conn::MyOpts; use self::mysql::conn::pool::MyPool; use self::mysql::error::MyResult; use self::mysql::value::from_row; use self::mysql::value::Value; use std::clone::Clone; use std::default::Default; us...
{ CannotStoreRecord, CannotFetchRecord, CannotDenormalizeRecord, RecordNotFound } #[derive(Debug, Clone, RustcDecodable, RustcEncodable)] pub struct MysqlConfig { address: String, username: String, password: String, database: String } impl MysqlConfig { pub fn to_connection (&self) -> MysqlReposit...
RecordRepositoryError
identifier_name
record_backend.rs
extern crate chrono; extern crate mysql; use self::chrono::UTC; use self::chrono::offset::TimeZone; use self::mysql::conn::MyOpts; use self::mysql::conn::pool::MyPool; use self::mysql::error::MyResult; use self::mysql::value::from_row; use self::mysql::value::Value; use std::clone::Clone; use std::default::Default; us...
}; results } fn fetch_record (&self, id: String) -> Result<(Record), RecordRepositoryError> { let uuid_optimized = MysqlOptimizedUuid::from_uuid(id.clone()); let query = r"SELECT HEX(id) AS id, command, cwd, status, stderr, stdout, CAST(started_at AS char) AS started_at, CAST(finished_at AS char)...
{ error!("error fetching from mysql {:?}", err); return Err(RecordRepositoryError::CannotDenormalizeRecord) }
conditional_block
events.js
'use strict'; var SERVER_ROOT = 'http://localhost:3000'; servicesModule .factory('Events', function($http){ // helper function to extract data from response var getData = function(res) { return res.data; }; // ---- Export functions ---- var addOne = function(friendId, eventObj){ return $http.post(...
var hours = (dateObj.getHours() + 4) % 24; // 24 hour clock, but then plus 4 for timezone var minutes = dateObj.getMinutes(); var monthString = month; var dateString = date; var yearString = year; var hoursString = (hours % 12 === 0 ? 12 : hours % 12).toString(); var minutesString = ((minu...
var year = dateObj.getUTCFullYear();
random_line_split
BlockedAfDUserExtraction.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @author: Michael Ruster Extract the timestamp and user of contributions which were authored before the respecitve user had been blocked. The result can be further processed by TimeframeCalculations.py. Requirements: MediaWiki Utilities, WikiWho DiscussionParser Usage: py...
with open(output, 'a') as output: writer = csv.writer(output, delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL) for fileName in WikiWho.extractFileNamesFromPath(path): print('[I] Now processing the file "%s".' % fileName) # Access the file. dumpIterator = m...
raise IOError('[E] File "%s" already exists. Aborting.' % output)
conditional_block
BlockedAfDUserExtraction.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @author: Michael Ruster Extract the timestamp and user of contributions which were authored before the respecitve user had been blocked. The result can be further processed by TimeframeCalculations.py. Requirements: MediaWiki Utilities, WikiWho DiscussionParser Usage: py...
blocks = BlockTimeCalculation.createBlockedUsersDict(args.blockLog) extract(args.pageDumpPath, users, blocks)
with open(usersFile, 'rb') as inputFile: users = pickle.load(inputFile) os.remove(usersFile)
random_line_split
BlockedAfDUserExtraction.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @author: Michael Ruster Extract the timestamp and user of contributions which were authored before the respecitve user had been blocked. The result can be further processed by TimeframeCalculations.py. Requirements: MediaWiki Utilities, WikiWho DiscussionParser Usage: py...
# If secondsToBlock is -1, the user was once blocked but this post # belongs to the time after, when she was never blocked again. if secondsToBlock != -1: writer.writerow([revision.timestamp, revision.contributor.id, ...
output = '../data/blockedAfDUsers.csv' if os.path.isfile(output): raise IOError('[E] File "%s" already exists. Aborting.' % output) with open(output, 'a') as output: writer = csv.writer(output, delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL) for fileName in WikiWho.e...
identifier_body
BlockedAfDUserExtraction.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @author: Michael Ruster Extract the timestamp and user of contributions which were authored before the respecitve user had been blocked. The result can be further processed by TimeframeCalculations.py. Requirements: MediaWiki Utilities, WikiWho DiscussionParser Usage: py...
(path, users, blocks): output = '../data/blockedAfDUsers.csv' if os.path.isfile(output): raise IOError('[E] File "%s" already exists. Aborting.' % output) with open(output, 'a') as output: writer = csv.writer(output, delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL) ...
extract
identifier_name
factories.py
''' Created on 22/02/2015 @author: Ismail Faizi ''' import models class ModelFactory(object): """ Factory for creating entities of models """ @classmethod def create_user(cls, name, email, training_journal): """ Factory method for creating User entity. NOTE: you must ex...
@classmethod def create_workout_set(cls, repetitions, weight, workout_session, workout): """ Factory method for creating WorkoutSet entity. NOTE: you must explicitly call the put() method """ workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY) worko...
""" Factory method for creating WorkoutSession entity. NOTE: you must explicitly call the put() method """ workout_session = models.WorkoutSession(parent=models.WORKOUT_SESSION_KEY) workout_session.started_at = started_at workout_session.ended_at = ended_at worko...
identifier_body
factories.py
''' Created on 22/02/2015 @author: Ismail Faizi ''' import models class ModelFactory(object): """ Factory for creating entities of models """ @classmethod def create_user(cls, name, email, training_journal): """ Factory method for creating User entity. NOTE: you must ex...
Factory method for creating WorkoutSet entity. NOTE: you must explicitly call the put() method """ workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY) workout_set.repetitions = repetitions workout_set.weight = weight workout_set.workout_session = worko...
"""
random_line_split
factories.py
''' Created on 22/02/2015 @author: Ismail Faizi ''' import models class ModelFactory(object): """ Factory for creating entities of models """ @classmethod def create_user(cls, name, email, training_journal): """ Factory method for creating User entity. NOTE: you must ex...
(cls): """ Factory method for creating TrainingJournal entity. NOTE: you must explicitly call the put() method """ return models.TrainingJournal(parent=models.TRAINING_JOURNAL_KEY) @classmethod def create_workout_session(cls, started_at, ended_at, training_journal): ...
create_training_journal
identifier_name
verifyCode-validator.directive.ts
import { Directive, forwardRef, Attribute, Input } from '@angular/core'; import { Validator, FormControl, AbstractControl, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms'; import { Observable } from "rxjs"; import { VerifyCodeService } from '../services/verify-code.service'; // 登录服务 @Directive({ select...
@Input('validateVcode') mobile: string; validateVcodeObservable(mobile: string, vcode: string) { return new Observable(observer => { this.vCodeService.validateVerifyCode(mobile, vcode).subscribe(responseData => { console.log(responseData); // if (responseData.e...
identifier_body
verifyCode-validator.directive.ts
import { Directive, forwardRef, Attribute, Input } from '@angular/core'; import { Validator, FormControl, AbstractControl, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms'; import { Observable } from "rxjs"; import { VerifyCodeService } from '../services/verify-code.service'; // 登录服务 @Directive({ selecto...
validate(c: AbstractControl): Observable<{[key : string] : any}> { return this.validateVcodeObservable(this.mobile, c.value).first(); } }
random_line_split
verifyCode-validator.directive.ts
import { Directive, forwardRef, Attribute, Input } from '@angular/core'; import { Validator, FormControl, AbstractControl, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms'; import { Observable } from "rxjs"; import { VerifyCodeService } from '../services/verify-code.service'; // 登录服务 @Directive({ select...
string, vcode: string) { return new Observable(observer => { this.vCodeService.validateVerifyCode(mobile, vcode).subscribe(responseData => { console.log(responseData); // if (responseData.errorCode === 1) { // // verify error. // ...
VcodeObservable(mobile:
identifier_name
mozmap.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The `MozMap` (open-ended dictionary) type. use dom::bindings::conversions::jsid_to_string; use dom::bindings:...
ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)), }; let key = jsid_to_string(cx, id.handle()).unwrap(); map.insert(key, property); } Ok(ConversionResult::Success(MozMap { map: map, })) } } ...
{ if !value.is_object() { return Ok(ConversionResult::Failure("MozMap value was not an object".into())); } rooted!(in(cx) let object = value.to_object()); let ids = IdVector::new(cx); assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.get())); ...
identifier_body
mozmap.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The `MozMap` (open-ended dictionary) type. use dom::bindings::conversions::jsid_to_string; use dom::bindings:...
where T: FromJSValConvertible<Config=C>, C: Clone, { type Config = C; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C) -> Result<ConversionResult<Self>, ()> { if !value.is_object() { return Ok(ConversionResult::Failure("MozMap val...
impl<T, C> FromJSValConvertible for MozMap<T>
random_line_split
mozmap.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The `MozMap` (open-ended dictionary) type. use dom::bindings::conversions::jsid_to_string; use dom::bindings:...
() -> Self { MozMap { map: HashMap::new(), } } } impl<T> Deref for MozMap<T> { type Target = HashMap<DOMString, T>; fn deref(&self) -> &HashMap<DOMString, T> { &self.map } } impl<T, C> FromJSValConvertible for MozMap<T> where T: FromJSValConvertible<Config=C>, ...
new
identifier_name
testThread.py
from PyQt4 import QtCore import numpy from ilastik.core import dataImpex import shlex from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray from ilastik.core.overlays.selectionOverlay import SelectionAccessor from subprocess import Popen, PIPE import h5py # this is the core replacement of the guiThr...
(overlay1, overlay2, tolerance = 0): # overlay1._data._data can be a listOfNDArraysAsNDArray instance, overlay2._data._data is loaded from file, so it should be an NDArray if isinstance(overlay1._data._data, ListOfNDArraysAsNDArray): datatemp1 = overlay1._data._data.ndarrays elif isi...
compareOverlayData
identifier_name
testThread.py
from PyQt4 import QtCore import numpy from ilastik.core import dataImpex import shlex from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray from ilastik.core.overlays.selectionOverlay import SelectionAccessor from subprocess import Popen, PIPE import h5py # this is the core replacement of the guiThr...
def start(self, input): self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.updateProgress) # call core function self.myTestThread = self.baseMgr.computeResults(input) self.timer.start(200) def updateProgress(self):...
__pyqtSignals__ = ( "done()") #QtCore.QThread.__init__(self, parent) QtCore.QObject.__init__(self) self.baseMgr = baseMgr self.listOfResultOverlays = listOfResultOverlays self.listOfFilenames = listOfFilenames self.tolerance = tolerance self.passedTest = False
identifier_body
testThread.py
from PyQt4 import QtCore import numpy from ilastik.core import dataImpex import shlex from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray from ilastik.core.overlays.selectionOverlay import SelectionAccessor from subprocess import Popen, PIPE import h5py # this is the core replacement of the guiThr...
return False return True @staticmethod def compareH5Files(file1, file2): print "files to compare: ", file1, file2 #have to spawn a subprocess, because h5diff has no wrapper in python cl = "h5diff -cv '" + file1 + "' '" + file2 + "'" args = s...
for z in range(a.shape[2]): if a[x,y,z] != b[x,y,z]: print x,y,z, "a=", a[x,y,z], "b=", b[x,y,z]
conditional_block
testThread.py
from PyQt4 import QtCore import numpy from ilastik.core import dataImpex import shlex from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray from ilastik.core.overlays.selectionOverlay import SelectionAccessor from subprocess import Popen, PIPE import h5py # this is the core replacement of the guiThr...
def compareResultsWithFile(baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0): equalOverlays = True for i in range(len(listOfResultOverlays)): obtained = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[listOfResultOverlays[i]] prefix = "Ground_Truth...
class TestHelperFunctions(): @staticmethod
random_line_split
15.4.4.16-7-b-11.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
() { var accessed = false; function callbackfn(val, idx, obj) { accessed = true; return idx !== 1; } var arr = [0, , 2]; Object.defineProperty(arr, "0", { get: function () { delete Array.prototype[1]; return 0; ...
testcase
identifier_name
15.4.4.16-7-b-11.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
var arr = [0, , 2]; Object.defineProperty(arr, "0", { get: function () { delete Array.prototype[1]; return 0; }, configurable: true }); try { Array.prototype[1] = 1; return arr.every(callbackfn)...
var accessed = false; function callbackfn(val, idx, obj) { accessed = true; return idx !== 1; }
random_line_split
15.4.4.16-7-b-11.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
delete Array.prototype[1]; } } runTestCase(testcase);
{ var accessed = false; function callbackfn(val, idx, obj) { accessed = true; return idx !== 1; } var arr = [0, , 2]; Object.defineProperty(arr, "0", { get: function () { delete Array.prototype[1]; return 0; ...
identifier_body
control.js
'use strict'; var hp = require('../modules/hyperpin');
exports.actions = function(req, res, ss) { req.use('session'); require('../modules/announce').registerSocketStream(ss); return { /** * Inserts a coin into the pinball machine. * @param slot Which slot, 1 or 2 */ insertCoin: function(slot) { // access control if (!req.session.user...
var error = require('../modules/error'); var logger = require('winston');
random_line_split
test_strings.py
# Copyright (c) 2010-2015 openpyxl # package imports from openpyxl.reader.strings import read_string_table from openpyxl.tests.helper import compare_xml def test_read_string_table(datadir): datadir.join('reader').chdir() src = 'sharedStrings.xml' with open(src) as content: assert read_string_ta...
def test_write_string_table(datadir): from openpyxl.writer.strings import write_string_table datadir.join("reader").chdir() table = ['This is cell A1 in Sheet 1', 'This is cell G5'] content = write_string_table(table) with open('sharedStrings.xml') as expected: diff = compare_xml(content...
datadir.join('reader').chdir() src = 'shared-strings-rich.xml' with open(src) as content: assert read_string_table(content.read()) == [ 'Welcome', 'to the best shop in town', " let's play "]
identifier_body
test_strings.py
# Copyright (c) 2010-2015 openpyxl # package imports from openpyxl.reader.strings import read_string_table from openpyxl.tests.helper import compare_xml def test_read_string_table(datadir): datadir.join('reader').chdir() src = 'sharedStrings.xml' with open(src) as content: assert read_string_ta...
(datadir): from openpyxl.writer.strings import write_string_table datadir.join("reader").chdir() table = ['This is cell A1 in Sheet 1', 'This is cell G5'] content = write_string_table(table) with open('sharedStrings.xml') as expected: diff = compare_xml(content, expected.read()) ass...
test_write_string_table
identifier_name
test_strings.py
# Copyright (c) 2010-2015 openpyxl # package imports from openpyxl.reader.strings import read_string_table from openpyxl.tests.helper import compare_xml def test_read_string_table(datadir): datadir.join('reader').chdir() src = 'sharedStrings.xml' with open(src) as content: assert read_string_ta...
assert read_string_table(content.read()) == [ 'Welcome', 'to the best shop in town', " let's play "] def test_write_string_table(datadir): from openpyxl.writer.strings import write_string_table datadir.join("reader").chdir() table = ['This is cell A1 in Sheet 1', 'This is cell G5'...
src = 'shared-strings-rich.xml' with open(src) as content:
random_line_split
recipe-576734.py
import ctypes class C_struct: """Decorator to convert the given class into a C struct.""" # contains a dict of all known translatable types types = ctypes.__dict__ @classmethod def register_type(cls, typename, obj): """Adds the new class to the dict of understood types.""" cls.types[typename] = obj def __...
will be read in. """ # build the field mapping (names -> types) fields = [] for k, v in vars(cls).items(): # don't wrap private variables if not k.startswith("_"): # if its a pointer if v.startswith("*"): field_type = ctypes.POINTER(self.types[v[1:]]) else: field_type = self.typ...
"""Converts the given class into a C struct. Usage: >>> @C_struct() ... class Account: ... first_name = "c_char_p" ... last_name = "c_char_p" ... balance = "c_float" ... >>> a = Account() >>> a <cstruct.Account object at 0xb7c0ee84> A very important note: while it *is* possible to ...
identifier_body
recipe-576734.py
import ctypes class C_struct: """Decorator to convert the given class into a C struct.""" # contains a dict of all known translatable types types = ctypes.__dict__ @classmethod def register_type(cls, typename, obj): """Adds the new class to the dict of understood types.""" cls.types[typename] = obj def __...
# make our bases tuple bases = (ctypes.Structure,) + tuple((base for base in cls.__bases__)) # finish up our wrapping dict class_attrs = {"_fields_": fields, "__doc__": cls.__doc__} # now create our class return type(cls.__name__, bases, class_attrs)
if not k.startswith("_"): # if its a pointer if v.startswith("*"): field_type = ctypes.POINTER(self.types[v[1:]]) else: field_type = self.types[v] new_field = (k, field_type) fields.append(new_field)
conditional_block
recipe-576734.py
import ctypes class C_struct: """Decorator to convert the given class into a C struct.""" # contains a dict of all known translatable types types = ctypes.__dict__ @classmethod def register_type(cls, typename, obj): """Adds the new class to the dict of understood types.""" cls.types[typename] = obj def __...
# don't wrap private variables if not k.startswith("_"): # if its a pointer if v.startswith("*"): field_type = ctypes.POINTER(self.types[v[1:]]) else: field_type = self.types[v] new_field = (k, field_type) fields.append(new_field) # make our bases tuple bases = (ctypes.Structure...
""" # build the field mapping (names -> types) fields = [] for k, v in vars(cls).items():
random_line_split
recipe-576734.py
import ctypes class C_struct: """Decorator to convert the given class into a C struct.""" # contains a dict of all known translatable types types = ctypes.__dict__ @classmethod def register_type(cls, typename, obj): """Adds the new class to the dict of understood types.""" cls.types[typename] = obj def
(self, cls): """Converts the given class into a C struct. Usage: >>> @C_struct() ... class Account: ... first_name = "c_char_p" ... last_name = "c_char_p" ... balance = "c_float" ... >>> a = Account() >>> a <cstruct.Account object at 0xb7c0ee84> A very important note: while it *is...
__call__
identifier_name
__init__.py
"""Support for Roku API emulation.""" import voluptuous as vol from homeassistant import config_entries, util from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from .binding import EmulatedRoku from .config_flow import configured_servers from .const import ( CONF_ADVER...
host_ip = config.get(CONF_HOST_IP) or util.get_local_ip() advertise_ip = config.get(CONF_ADVERTISE_IP) advertise_port = config.get(CONF_ADVERTISE_PORT) upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST) server = EmulatedRoku(hass, name, host_ip, listen_port, advert...
name = config[CONF_NAME] listen_port = config[CONF_LISTEN_PORT]
random_line_split
__init__.py
"""Support for Roku API emulation.""" import voluptuous as vol from homeassistant import config_entries, util from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from .binding import EmulatedRoku from .config_flow import configured_servers from .const import ( CONF_ADVER...
(hass, config_entry): """Set up an emulated roku server from a config entry.""" config = config_entry.data if DOMAIN not in hass.data: hass.data[DOMAIN] = {} name = config[CONF_NAME] listen_port = config[CONF_LISTEN_PORT] host_ip = config.get(CONF_HOST_IP) or util.get_local_ip() ad...
async_setup_entry
identifier_name
__init__.py
"""Support for Roku API emulation.""" import voluptuous as vol from homeassistant import config_entries, util from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from .binding import EmulatedRoku from .config_flow import configured_servers from .const import ( CONF_ADVER...
async def async_unload_entry(hass, entry): """Unload a config entry.""" name = entry.data[CONF_NAME] server = hass.data[DOMAIN].pop(name) return await server.unload()
"""Set up an emulated roku server from a config entry.""" config = config_entry.data if DOMAIN not in hass.data: hass.data[DOMAIN] = {} name = config[CONF_NAME] listen_port = config[CONF_LISTEN_PORT] host_ip = config.get(CONF_HOST_IP) or util.get_local_ip() advertise_ip = config.get(CO...
identifier_body
__init__.py
"""Support for Roku API emulation.""" import voluptuous as vol from homeassistant import config_entries, util from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from .binding import EmulatedRoku from .config_flow import configured_servers from .const import ( CONF_ADVER...
return True async def async_setup_entry(hass, config_entry): """Set up an emulated roku server from a config entry.""" config = config_entry.data if DOMAIN not in hass.data: hass.data[DOMAIN] = {} name = config[CONF_NAME] listen_port = config[CONF_LISTEN_PORT] host_ip = config....
hass.async_create_task(hass.config_entries.flow.async_init( DOMAIN, context={'source': config_entries.SOURCE_IMPORT}, data=entry ))
conditional_block
Layout.js
// Generated by CoffeeScript 1.9.3 var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth; Block = require('./layout/Block'); object = require('utila').object; SpecialString = require('./layout/SpecialString'); terminalWidth = require('./tools').getCols(); module.exports = Layout = (functio...
Layout.prototype.getRootBlock = function() { return this._root; }; Layout.prototype._append = function(text) { return this._written.push(text); }; Layout.prototype._appendLine = function(text) { var s; this._append(text); s = SpecialString(text); if (s.length < this._config.termina...
{ var rootConfig; if (config == null) { config = {}; } if (rootBlockConfig == null) { rootBlockConfig = {}; } this._written = []; this._activeBlock = null; this._config = object.append(self._defaultConfig, config); rootConfig = object.append(self._rootBlockDefaultConfig, ...
identifier_body
Layout.js
// Generated by CoffeeScript 1.9.3 var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth; Block = require('./layout/Block'); object = require('utila').object; SpecialString = require('./layout/SpecialString'); terminalWidth = require('./tools').getCols(); module.exports = Layout = (functio...
(config, rootBlockConfig) { var rootConfig; if (config == null) { config = {}; } if (rootBlockConfig == null) { rootBlockConfig = {}; } this._written = []; this._activeBlock = null; this._config = object.append(self._defaultConfig, config); rootConfig = object.append(self...
Layout
identifier_name
Layout.js
// Generated by CoffeeScript 1.9.3 var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth;
object = require('utila').object; SpecialString = require('./layout/SpecialString'); terminalWidth = require('./tools').getCols(); module.exports = Layout = (function() { var self; self = Layout; Layout._rootBlockDefaultConfig = { linePrependor: { options: { amount: 0 } }, li...
Block = require('./layout/Block');
random_line_split