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
climate.py
=%s [%s], name=%s (location_idx=%s)", tcs_obj_ref.systemId, tcs_obj_ref.modelType, tcs_obj_ref.location.name, loc_idx) controller = EvoController(evo_data, client, tcs_obj_ref) zones = [] for zone_idx in tcs_obj_ref.zones: zone_obj_ref = tcs_obj_ref.zones[zone_idx] _LOGGER....
(EvoClimateDevice): """Base for a Honeywell evohome Zone device.""" def __init__(self, evo_data, client, obj_ref): """Initialize the evohome Zone.""" super().__init__(evo_data, client, obj_ref) self._id = obj_ref.zoneId self._name = obj_ref.name self._icon = "mdi:radiat...
EvoZone
identifier_name
climate.py
id=%s [%s], name=%s (location_idx=%s)", tcs_obj_ref.systemId, tcs_obj_ref.modelType, tcs_obj_ref.location.name, loc_idx) controller = EvoController(evo_data, client, tcs_obj_ref) zones = [] for zone_idx in tcs_obj_ref.zones: zone_obj_ref = tcs_obj_ref.zones[zone_idx] _LOGG...
def _handle_exception(self, err): try: import evohomeclient2 raise err except evohomeclient2.AuthenticationError: _LOGGER.error( "Failed to (re)authenticate with the vendor's server. " "This may be a temporary error. Message is: ...
self.async_schedule_update_ha_state(force_refresh=True)
conditional_block
climate.py
return self._config['setpointCapabilities']['minHeatSetpoint'] @property def max_temp(self): """Return the minimum target temperature of a evohome Zone. The default is 35 (in Celsius), but it is configurable within 5-35. """ return self._config['setpointCapabilities']['maxHeat...
"""Return True if away mode is on.""" return self._status['systemModeStatus']['mode'] == EVO_AWAY
identifier_body
signature.rs
//! Kernel-provided signatures. //! We expose a new submodule for each use case, so arguments //! can be typed correctly and given separate context. use crate::random; use spin::Once; use ed25519_dalek::Keypair; static KEYPAIR: Once<Keypair> = Once::new(); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct In...
.sign_prehashed(prehashed, Some(SIGNATURE_CONTEXT)) .expect("Signing failed") } pub fn verify(pid: u64, cap: u64, signature: &Signature) -> Result<(), InvalidSignature> { let mut prehashed: Sha512 = Sha512::new(); prehashed.update(&pid.to_le_bytes()); prehashed.u...
prehashed.update(&pid.to_le_bytes()); prehashed.update(&cap.to_le_bytes()); get_keypair()
random_line_split
signature.rs
//! Kernel-provided signatures. //! We expose a new submodule for each use case, so arguments //! can be typed correctly and given separate context. use crate::random; use spin::Once; use ed25519_dalek::Keypair; static KEYPAIR: Once<Keypair> = Once::new(); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct In...
} #[cfg(test)] mod tests { use ed25519_dalek::Signature; use super::capability; #[test] fn test_signature() { let s = capability::sign(5, 10); println!("{:?}", s); capability::verify(5, 10, &s).expect("Verify"); assert!(capability::verify(6, 10, &s).is_err()); ...
{ let mut prehashed: Sha512 = Sha512::new(); prehashed.update(&pid.to_le_bytes()); prehashed.update(&cap.to_le_bytes()); get_keypair() .verify_prehashed(prehashed, Some(SIGNATURE_CONTEXT), signature) .map_err(|_| InvalidSignature) }
identifier_body
signature.rs
//! Kernel-provided signatures. //! We expose a new submodule for each use case, so arguments //! can be typed correctly and given separate context. use crate::random; use spin::Once; use ed25519_dalek::Keypair; static KEYPAIR: Once<Keypair> = Once::new(); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct In...
() { let s = capability::sign(5, 10); println!("{:?}", s); capability::verify(5, 10, &s).expect("Verify"); assert!(capability::verify(6, 10, &s).is_err()); let mut bytes = s.to_bytes(); bytes[0] = bytes[0].wrapping_add(1); let s2 = Signature::new(bytes); ...
test_signature
identifier_name
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
(input: &str) -> u64 { input .lines() .map(|line| { let values: Vec<_> = line.split_whitespace() .filter_map(|entry| entry.parse::<u64>().ok()) .collect(); let mut result = None; 'outer: for a in &values { for b in &...
part2
identifier_name
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
input .lines() .map(|line| { let values: Vec<_> = line.split_whitespace() .filter_map(|entry| entry.parse::<u64>().ok()) .collect(); let mut result = None; 'outer: for a in &values { for b in &values { ...
} fn part2(input: &str) -> u64 {
random_line_split
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
else { let mut file = File::open(&opt.input) .expect(&format!("file {} not found", opt.input)); file.read_to_string(&mut contents) .expect(&format!("could not read file {}", opt.input)); } println!("Part 1: {}", part1(&contents)); println!("Part 2: {}", part2(&conten...
{ std::io::stdin() .read_to_string(&mut contents) .expect("could not read stdin"); }
conditional_block
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
#[derive(StructOpt, Debug)] #[structopt(name = "day02", about = "Advent of code 2017 day 02")] struct Opt { #[structopt(help = "Input file")] input: String, } #[cfg(test)] mod tests { use super::*; #[test] fn part1_test() { assert_eq!(part1("5 1 9 5\n7 5 3\n2 4 6 8"), 18) } #[test] ...
{ let opt = Opt::from_args(); let mut contents = String::new(); if opt.input == "-" { std::io::stdin() .read_to_string(&mut contents) .expect("could not read stdin"); } else { let mut file = File::open(&opt.input) .expect(&format!("file {} not found", ...
identifier_body
util.py
############################################################################## # # Copyright Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS ...
if exception is not None: self.TimeOutWaitingFor = exception self.getnow = getnow self.getsleep = getsleep def __call__(self, func=None, timeout=None, wait=None, message=None): if func is None: return lambda func: self(func, timeout, wait, message) ...
self.wait = wait
conditional_block
util.py
############################################################################## # # Copyright Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS ...
def __call__(self, func=None, timeout=None, wait=None, message=None): if func is None: return lambda func: self(func, timeout, wait, message) if func(): return now = self.getnow() sleep = self.getsleep() if timeout is None: timeout = se...
if timeout is not None: self.timeout = timeout if wait is not None: self.wait = wait if exception is not None: self.TimeOutWaitingFor = exception self.getnow = getnow self.getsleep = getsleep
identifier_body
util.py
############################################################################## # # Copyright Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS ...
wait = Wait()
getattr(func, '__doc__') or getattr(func, '__name__') )
random_line_split
util.py
############################################################################## # # Copyright Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS ...
(self, timeout=None, wait=None, exception=None, getnow=(lambda: time.time), getsleep=(lambda: time.sleep)): if timeout is not None: self.timeout = timeout if wait is not None: self.wait = wait if exception is not None: self.TimeOutWaitingFo...
__init__
identifier_name
IPostComponentState.ts
export interface IPostComponentState {
*/ text: string /** * It's true if whole the text post is visible */ readMoreState: boolean /** * Handle open comment from parent component */ openComments: boolean /** * If it's true, share dialog will be open */ shareOpen: boolean /** ...
/** * Post text
random_line_split
Globalization.fr-LU.js
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["fr-LU"] = $.extend(true, {}, en, { name: "fr-LU", englishName: "French (Luxembourg)", nativeName: "français (Luxembourg)", language: "fr", ...
PM: null, eras: [{"name":"ap. J.-C.","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd d MMMM yyyy HH:mm", ...
random_line_split
Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ web_server: { options: { cors: true, port: 8000, nevercache: true, logRequests: true }, foo: 'bar' }, uglify: { my_target: { files: { 'dist/ng-video-preview.min.js': ['video-pre...
jQuery: true } } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-web-server'); grunt.loadNpmTasks('grunt-contrib-uglify'); gr...
random_line_split
radioButton.js
* @description radioButton module! */ angular.module('material.components.radioButton', [ 'material.core' ]) .directive('mdRadioGroup', mdRadioGroupDirective) .directive('mdRadioButton', mdRadioButtonDirective); /** * @ngdoc directive * @module material.components.radioButton * @name mdRadioGroup * * @res...
function keydownListener(ev) { var keyCode = ev.which || ev.keyCode; switch(keyCode) { case $mdConstant.KEY_CODE.LEFT_ARROW: case $mdConstant.KEY_CODE.UP_ARROW: ev.preventDefault(); rgCtrl.selectPrevious(); setFocus(); break; case $mdCon...
{ if (!element.hasClass('md-focused')) { element.addClass('md-focused'); } }
identifier_body
radioButton.js
* @description radioButton module! */ angular.module('material.components.radioButton', [ 'material.core' ]) .directive('mdRadioGroup', mdRadioGroupDirective) .directive('mdRadioButton', mdRadioButtonDirective); /** * @ngdoc directive * @module material.components.radioButton * @name mdRadioGroup * * @re...
() { if (!element.hasClass('md-focused')) { element.addClass('md-focused'); } } function keydownListener(ev) { var keyCode = ev.which || ev.keyCode; switch(keyCode) { case $mdConstant.KEY_CODE.LEFT_ARROW: case $mdConstant.KEY_CODE.UP_ARROW: ev.preventDefault(); ...
setFocus
identifier_name
radioButton.js
* @description radioButton module! */ angular.module('material.components.radioButton', [ 'material.core' ]) .directive('mdRadioGroup', mdRadioGroupDirective) .directive('mdRadioButton', mdRadioButtonDirective); /** * @ngdoc directive * @module material.components.radioButton * @name mdRadioGroup * * @re...
}, add: function(rbRender) { this._radioButtonRenderFns.push(rbRender); }, remove: function(rbRender) { var index = this._radioButtonRenderFns.indexOf(rbRender); if (index !== -1) { this._radioButtonRenderFns.splice(index, 1); } }, render: fu...
random_line_split
radioButton.js
* @description radioButton module! */ angular.module('material.components.radioButton', [ 'material.core' ]) .directive('mdRadioGroup', mdRadioGroupDirective) .directive('mdRadioButton', mdRadioButtonDirective); /** * @ngdoc directive * @module material.components.radioButton * @name mdRadioGroup * * @res...
}, render: function() { this._radioButtonRenderFns.forEach(function(rbRender) { rbRender(); }); }, setViewValue: function(value, eventType) { this._ngModelCtrl.$setViewValue(value, eventType); // update the other radio buttons as well this.rende...
{ this._radioButtonRenderFns.splice(index, 1); }
conditional_block
jquery.hotkeys.js
/****************************************************************************************************************************** * @ Original idea by by Binny V A, Original version: 2.00.A * @ http://www.openjs.com/scripts/events/keyboard_shortcuts/ * @ Original License : BSD * @ jQuery Plugin by Tzury Bar Yocha...
} }; // first hook for this element if (!this.all[opt.target]){ this.all[opt.target] = {events:{}}; } if (!this.all[opt.target].events[opt.type]){ this.all[opt.target].events[opt.type] = {callbackMap: {}} jQuery.event.add(opt.tar...
{ event.stopPropagation(); event.preventDefault(); return false; }
conditional_block
jquery.hotkeys.js
/****************************************************************************************************************************** * @ Original idea by by Binny V A, Original version: 2.00.A * @ http://www.openjs.com/scripts/events/keyboard_shortcuts/ * @ Original License : BSD * @ jQuery Plugin by Tzury Bar Yocha...
if( target.is("input") || target.is("textarea")){ return; } } var code = event.which, type = event.type, character = String.fromCharCode(code).toLowerCase(), special = that.special_keys[code], ...
// WP: not needed with newer jQuery // element = (element.nodeType==3) ? element.parentNode : element; if(opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields var target = jQuery(element);
random_line_split
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::{AsRawFd, RawFd}; use ports::localhost; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); l...
close(fd1).unwrap(); } { let mut buf = [0u8; 5]; let iov = [IoVec::from_mut_slice(&mut buf[..])]; let mut cmsgspace: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = recvmsg(fd2, &iov, Some(&mut cmsgspace), 0).unwrap(); for cmsg in msg.cmsgs() { i...
{ use nix::sys::uio::IoVec; use nix::unistd::{pipe, read, write, close}; use nix::sys::socket::{socketpair, sendmsg, recvmsg, AddressFamily, SockType, SockFlag, ControlMessage, CmsgSpace, MSG_TRUNC, MSG_CTRUNC}; let (fd1, ...
identifier_body
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::{AsRawFd, RawFd}; use ports::localhost; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); l...
let actual = Path::new("/foo/bar"); let addr = UnixAddr::new(actual).unwrap(); let expect: &'static [i8] = unsafe { mem::transmute(&b"/foo/bar"[..]) }; assert_eq!(&addr.0.sun_path[..8], expect); assert_eq!(addr.path(), Some(actual)); } #[test] pub fn test_getsockname() { use std::net::TcpList...
} #[test] pub fn test_path_to_sock_addr() {
random_line_split
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::{AsRawFd, RawFd}; use ports::localhost; #[test] pub fn
() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V4(addr) => { let ip: u32 = 0x7f000001; let port: u16 = 3000; assert_eq!(addr.sin_addr.s_addr, ip.to_be()); ...
test_inetv4_addr_to_sock_addr
identifier_name
softmax.rs
use activation::Activation; #[derive(Copy, Clone)] pub struct SoftMax; impl SoftMax { pub fn new() -> SoftMax { return SoftMax; } } impl Activation for SoftMax { /// Calculates the SoftMax of input `x` fn calc(&self, x: Vec<f64>) -> Vec<f64> { let max_x = x.iter() .cloned(...
() { let activation = SoftMax::new(); let result = activation.calc(vec![1f64, 5f64, 4f64]); let validate = vec![-0.011963105252f64, 0.751918768228f64, 0.260044337024f64]; for (i, r) in result.iter().enumerate() { assert_approx_eq!(r, validate[i]); } } #[test...
softmax_test
identifier_name
softmax.rs
use activation::Activation; #[derive(Copy, Clone)] pub struct SoftMax; impl SoftMax { pub fn new() -> SoftMax { return SoftMax; } } impl Activation for SoftMax { /// Calculates the SoftMax of input `x` fn calc(&self, x: Vec<f64>) -> Vec<f64> { let max_x = x.iter() .cloned(...
fn softmax_derivative_correctness_test() { let activation = SoftMax::new(); let delta = 1e-10f64; let val = vec![0.5f64, 0.1f64, 0.9f64]; let val_delta = val.iter().map(|n| n + delta).collect::<Vec<_>>(); let approx = activation .calc(val_delta) .iter...
#[test] #[ignore]
random_line_split
softmax.rs
use activation::Activation; #[derive(Copy, Clone)] pub struct SoftMax; impl SoftMax { pub fn new() -> SoftMax { return SoftMax; } } impl Activation for SoftMax { /// Calculates the SoftMax of input `x` fn calc(&self, x: Vec<f64>) -> Vec<f64> { let max_x = x.iter() .cloned(...
}
{ let activation = SoftMax::new(); let delta = 1e-10f64; let val = vec![0.5f64, 0.1f64, 0.9f64]; let val_delta = val.iter().map(|n| n + delta).collect::<Vec<_>>(); let approx = activation .calc(val_delta) .iter() .zip(activation.calc(val.clone...
identifier_body
bootstrap_view.ts
// Copyright 2018 Google 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 by applicable...
implements OnInit { /** Title for the component. */ private readonly title = `Setup - ${CONFIG.appName}`; constructor(private titleService: Title) {} ngOnInit() { this.titleService.setTitle(this.title); } }
BootstrapView
identifier_name
bootstrap_view.ts
// Copyright 2018 Google 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 by applicable...
import {CONFIG} from '../../app.config'; @Component({ preserveWhitespaces: true, selector: 'loaner-bootstrap-view', styleUrls: ['bootstrap_view.scss'], templateUrl: 'bootstrap_view.ng.html', }) export class BootstrapView implements OnInit { /** Title for the component. */ private readonly title = `Setup -...
// limitations under the License. import {Component, OnInit} from '@angular/core'; import {Title} from '@angular/platform-browser';
random_line_split
event_manager_spec.ts
import { describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, el } from 'angular2/testing_internal'; import {EventManager, EventManagerPlugin} from 'angular2/platform/common_dom'; import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; import {NgZone} from 'angular2/s...
() { super({enableLongStackTrace: false}); } run(fn) { fn(); } runOutsideAngular(fn) { return fn(); } }
constructor
identifier_name
event_manager_spec.ts
import { describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, el } from 'angular2/testing_internal'; import {EventManager, EventManagerPlugin} from 'angular2/platform/common_dom'; import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; import {NgZone} from 'angular2/s...
var receivedEvent = null; var handler = (e) => { receivedEvent = e; }; var manager = new EventManager([domEventPlugin], new FakeNgZone()); manager.addEventListener(element, 'click', handler); DOM.dispatchEvent(child, dispatchedEvent); expect(receivedEvent).toBe(dispatchedEvent); ...
DOM.appendChild(DOM.defaultDoc().body, element); var child = DOM.firstChild(element); var dispatchedEvent = DOM.createMouseEvent('click');
random_line_split
event_manager_spec.ts
import { describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, el } from 'angular2/testing_internal'; import {EventManager, EventManagerPlugin} from 'angular2/platform/common_dom'; import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; import {NgZone} from 'angular2/s...
}
{ return fn(); }
identifier_body
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
let mut traversal_data = PerLevelTraversalData { current_dom_depth: None, }; let mut tlc = traversal.create_thread_local_context(); if token.traverse_unstyled_children_only() { for kid in root.as_node().children() { if kid.as_element().map_or(false, |el| el.get_data().is_n...
{ traversal.process_preorder(traversal_data, thread_local, node); if let Some(el) = node.as_element() { if let Some(ref mut depth) = traversal_data.current_dom_depth { *depth += 1; } traversal.traverse_children(thread_local, el, |tlc, kid| { ...
identifier_body
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
<E, D>(traversal: &D, traversal_data: &mut PerLevelTraversalData, thread_local: &mut D::ThreadLocalContext, node: E::ConcreteNode) where E: TElement, D: DomTraversal<E> { traversal.process_preorder(traversal_data, thread_local, node); if let Some(el) = node.as...
doit
identifier_name
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
}
{ println!("{}", tlsc.statistics); }
conditional_block
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
let mut traversal_data = PerLevelTraversalData { current_dom_depth: None, }; let mut tlc = traversal.create_thread_local_context(); if token.traverse_unstyled_children_only() { for kid in root.as_node().children() { if kid.as_element().map_or(false, |el| el.get_data().is_non...
random_line_split
BaseRules.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from BaseReality import BaseReality import re class BaseRules(BaseReality): def _get_rule_precond(self,i): try: return re.match("^(.*)\s?->.*$",self._get_data(i)).groups()[0]
print "Error con el parametro a la expresion regular de extraccion de precondicion de una regla" except: print "Error con la expresion regular" def _get_rule_effect(self,i): try: return re.match(".*->\s?(.*)$",self._get_data(i)).groups()[0] except TypeError as te: print "Error con el parametro a ...
except TypeError as te:
random_line_split
BaseRules.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from BaseReality import BaseReality import re class BaseRules(BaseReality): def _get_rule_precond(self,i):
def _get_rule_effect(self,i): try: return re.match(".*->\s?(.*)$",self._get_data(i)).groups()[0] except TypeError as te: print "Error con el parametro a la expresion regular de la accion de precondicion de una regla" except: print "Error con la expresion regular" def _extract_set_of_precondition...
try: return re.match("^(.*)\s?->.*$",self._get_data(i)).groups()[0] except TypeError as te: print "Error con el parametro a la expresion regular de extraccion de precondicion de una regla" except: print "Error con la expresion regular"
identifier_body
BaseRules.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from BaseReality import BaseReality import re class
(BaseReality): def _get_rule_precond(self,i): try: return re.match("^(.*)\s?->.*$",self._get_data(i)).groups()[0] except TypeError as te: print "Error con el parametro a la expresion regular de extraccion de precondicion de una regla" except: print "Error con la expresion regular" def _get_rule_...
BaseRules
identifier_name
test_models.py
import os
from tsc.models import * def test_get_new_reservable_schedules(): old = [ Schedule(1, datetime.datetime(2015, 11, 1, 22, 00), ScheduleStatus.reservable), Schedule(1, datetime.datetime(2015, 11, 1, 23, 00), ScheduleStatus.reservable), ] new = [ Schedule(1, datetime.datetime(2015, 1...
random_line_split
test_models.py
import os from tsc.models import * def test_get_new_reservable_schedules(): old = [ Schedule(1, datetime.datetime(2015, 11, 1, 22, 00), ScheduleStatus.reservable), Schedule(1, datetime.datetime(2015, 11, 1, 23, 00), ScheduleStatus.reservable), ] new = [ Schedule(1, datetime.dateti...
(): gh = GitHub(os.environ.get("GITHUB_API_TOKEN")) assert gh.get_latest_version().split(".") >= "1.0.0".split(".")
test_github_get_latest_tag
identifier_name
test_models.py
import os from tsc.models import * def test_get_new_reservable_schedules(): old = [ Schedule(1, datetime.datetime(2015, 11, 1, 22, 00), ScheduleStatus.reservable), Schedule(1, datetime.datetime(2015, 11, 1, 23, 00), ScheduleStatus.reservable), ] new = [ Schedule(1, datetime.dateti...
gh = GitHub(os.environ.get("GITHUB_API_TOKEN")) assert gh.get_latest_version().split(".") >= "1.0.0".split(".")
identifier_body
wbalance.rs
/* * Copyright (C) 2012 The Android Open Source Project * * 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 app...
int maximum = max(estimation.r, max(estimation.g, estimation.b)); float avg = (minimum + maximum) / 2.f; scale.r = avg / estimation.r; scale.g = avg / estimation.g; scale.b = avg / estimation.b; } uchar4 __attribute__((kernel)) whiteBalanceKernel(uchar4 in) { float3 t = convert_float3(in.rg...
void prepareWhiteBalance() { uchar4 estimation = estimateWhite(); int minimum = min(estimation.r, min(estimation.g, estimation.b));
random_line_split
tunnelFactory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
export class TunnelFactoryContribution extends Disposable implements IWorkbenchContribution { constructor( @ITunnelService tunnelService: ITunnelService, @IWorkbenchEnvironmentService workbenchEnvironmentService: IWorkbenchEnvironmentService, ) { super(); const tunnelFactory = workbenchEnvironmentService.opt...
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
random_line_split
tunnelFactory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} } }
{ this._register(tunnelService.setTunnelProvider({ forwardPort: (tunnelOptions: TunnelOptions): Promise<RemoteTunnel> | undefined => { const tunnelPromise = tunnelFactory(tunnelOptions); if (!tunnelPromise) { return undefined; } return new Promise(resolve => { tunnelPromise.then(t...
conditional_block
tunnelFactory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}); } })); } } }
{ super(); const tunnelFactory = workbenchEnvironmentService.options?.tunnelProvider?.tunnelFactory; if (tunnelFactory) { this._register(tunnelService.setTunnelProvider({ forwardPort: (tunnelOptions: TunnelOptions): Promise<RemoteTunnel> | undefined => { const tunnelPromise = tunnelFactory(tunnelOptio...
identifier_body
tunnelFactory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
extends Disposable implements IWorkbenchContribution { constructor( @ITunnelService tunnelService: ITunnelService, @IWorkbenchEnvironmentService workbenchEnvironmentService: IWorkbenchEnvironmentService, ) { super(); const tunnelFactory = workbenchEnvironmentService.options?.tunnelProvider?.tunnelFactory; ...
TunnelFactoryContribution
identifier_name
sym_encrypted_session_key.js
// GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the Lice...
/** * Parsing function for a symmetric encrypted session key packet (tag 3). * * @param {String} input Payload of a tag 1 packet * @param {Integer} position Position to start reading from the input string * @param {Integer} len * Length of the packet or the remaining length of * input at ...
{ this.tag = enums.packet.symEncryptedSessionKey; this.sessionKeyEncryptionAlgorithm = null; this.sessionKeyAlgorithm = 'aes256'; this.encrypted = null; this.s2k = new type_s2k(); }
identifier_body
sym_encrypted_session_key.js
// GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the Lice...
() { this.tag = enums.packet.symEncryptedSessionKey; this.sessionKeyEncryptionAlgorithm = null; this.sessionKeyAlgorithm = 'aes256'; this.encrypted = null; this.s2k = new type_s2k(); } /** * Parsing function for a symmetric encrypted session key packet (tag 3). * * @param {String} input Payload of a tag 1...
SymEncryptedSessionKey
identifier_name
sym_encrypted_session_key.js
// GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the Lice...
else this.sessionKeyAlgorithm = algo; }; SymEncryptedSessionKey.prototype.write = function() { var algo = this.encrypted === null ? this.sessionKeyAlgorithm : this.sessionKeyEncryptionAlgorithm; var bytes = String.fromCharCode(this.version) + String.fromCharCode(enums.write(enums.symmetric, algo)...
{ this.encrypted = bytes.substr(done); this.sessionKeyEncryptionAlgorithm = algo; }
conditional_block
sym_encrypted_session_key.js
// GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the Lice...
} }; SymEncryptedSessionKey.prototype.encrypt = function(passphrase) { var length = crypto.getKeyLength(this.sessionKeyEncryptionAlgorithm); var key = this.s2k.produce_key(passphrase, length); var private_key = String.fromCharCode( enums.write(enums.symmetric, this.sessionKeyAlgorithm)) + crypto.getRan...
random_line_split
without_loop_counters.rs
#![warn(clippy::needless_range_loop, clippy::manual_memcpy)] const LOOP_OFFSET: usize = 5000; pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) { // plain manual memcpy for i in 0..src.len() { dst[i] = src[i]; } // dst offset memcpy for i in 0..src.len() { dst[i +...
(src: &[String], dst: &mut [String]) { for i in 0..src.len() { dst[i] = src[i].clone(); } } fn main() {}
manual_clone
identifier_name
without_loop_counters.rs
#![warn(clippy::needless_range_loop, clippy::manual_memcpy)] const LOOP_OFFSET: usize = 5000; pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) { // plain manual memcpy for i in 0..src.len() { dst[i] = src[i]; } // dst offset memcpy for i in 0..src.len() { dst[i +...
} // multiple copies - suggest two memcpy statements for i in 10..256 { dst[i] = src[i - 5]; dst2[i + 500] = src[i] } // this is a reversal - the copy lint shouldn't be triggered for i in 10..LOOP_OFFSET { dst[i + LOOP_OFFSET] = src[LOOP_OFFSET - i]; } let som...
{ break; }
conditional_block
without_loop_counters.rs
#![warn(clippy::needless_range_loop, clippy::manual_memcpy)] const LOOP_OFFSET: usize = 5000; pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) { // plain manual memcpy for i in 0..src.len() { dst[i] = src[i]; } // dst offset memcpy for i in 0..src.len() { dst[i +...
dst[i] = src[i - 5]; dst2[i + 500] = src[i] } // this is a reversal - the copy lint shouldn't be triggered for i in 10..LOOP_OFFSET { dst[i + LOOP_OFFSET] = src[LOOP_OFFSET - i]; } let some_var = 5; // Offset in variable for i in 10..LOOP_OFFSET { dst[i + LO...
random_line_split
demo_app.py
import logging import importlib import pyuavcan # Production applications are recommended to compile their DSDL namespaces as part of the build process. The enclosed # file "setup.py" provides an example of how to do that. The output path we specify here shall match that of "setup.py". # Here we compile DSDL just-in-t...
: REGISTER_FILE = "demo_app.db" """ The register file stores configuration parameters of the local application/node. The registers can be modified at launch via environment variables and at runtime via RPC-service "uavcan.register.Access". The file will be created automatically if it doesn't exist. ...
DemoApp
identifier_name
demo_app.py
sirius_cyber_corp # This is our vendor-specific root namespace. Custom data types. import pyuavcan.application # This module requires the root namespace "uavcan" to be transcompiled. except (ImportError, AttributeError): # Redistributable applications typically don't need this section. logging.warning("Tran...
asyncio.run(main())
conditional_block
demo_app.py
_dir = pathlib.Path(__file__).resolve().parent / ".demo_dsdl_compiled" # Make the compilation outputs importable. Let your IDE index this directory as sources to enable code completion. sys.path.insert(0, str(compiled_dsdl_dir)) try: import sirius_cyber_corp # This is our vendor-specific root namespace. Custom d...
""" This will close all the underlying resources down to the transport interface and all publishers/servers/etc. All pending tasks such as serve_in_background()/receive_in_background() will notice this and exit automatically. """ self._node.close()
identifier_body
demo_app.py
import logging import importlib import pyuavcan # Production applications are recommended to compile their DSDL namespaces as part of the build process. The enclosed # file "setup.py" provides an example of how to do that. The output path we specify here shall match that of "setup.py". # Here we compile DSDL just-in-t...
The main method that runs the business logic. It is also possible to use the library in an IoC-style by using receive_in_background() for all subscriptions if desired. """ temperature_setpoint = 0.0 temperature_error = 0.0 async def on_setpoint(msg: uavcan.si.unit.temper...
random_line_split
update_ingest.py
Received {0} articles from provider {1}, but only {2} are eligible to be saved in ingest' .format(len(items), provider['name'], len(filtered_items))) return filtered_items except Exception as ex: raise ProviderError.providerFilterExpiredContentError(ex, provider) def get_...
def get_provider_routing_scheme(provider): """Returns the ingests provider's routing scheme configuration. If provider has a routing scheme defined (i.e. scheme ID is not None), the scheme is fetched from the database. If not, nothing is returned. For all scheme rules that have a reference to a con...
if provider.get('rule_set'): return superdesk.get_resource_service('rule_sets').find_one(_id=provider['rule_set'], req=None)
identifier_body
update_ingest.py
00): return try: feeding_service = registered_feeding_services[provider['feeding_service']] feeding_service = feeding_service.__class__() update = {LAST_UPDATED: utcnow()} for items in feeding_service.update(provider): ingest_items(items, provider, feeding_serv...
ingest_item
identifier_name
update_ingest.py
from superdesk.media.media_operations import download_file_from_url, process_file from superdesk.media.renditions import generate_renditions from superdesk.metadata.item import GUID_NEWSML, GUID_FIELD, FAMILY_ID, ITEM_TYPE, CONTENT_TYPE, CONTENT_STATE, \ ITEM_STATE from superdesk.metadata.utils import generate_guid...
from superdesk.celery_task_utils import get_lock_id, get_host_id from superdesk.errors import ProviderError from superdesk.io import registered_feeding_services, registered_feed_parsers from superdesk.io.iptc import subject_codes from superdesk.lock import lock, unlock
random_line_split
update_ingest.py
:type routing_scheme: dict :py:class:`apps.rules.routing_rules.RoutingRuleSchemeResource` """ lock_name = get_lock_id('ingest', provider['name'], provider[superdesk.config.ID_FIELD]) host_name = get_host_id(self) if not lock(lock_name, host_name, expire=1800): return try: feeding...
failed_items.add(item[GUID_FIELD])
conditional_block
issue-2631-b.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let v = ~[@~"hi"]; let mut m: req::header_map = HashMap::new(); m.insert(~"METHOD", @RefCell::new(v)); request::<int>(&m); }
identifier_body
issue-2631-b.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use req::request; use std::cell::RefCell; use std::hashmap::HashMap; pub fn main() { let v = ~[@~"hi"]; let mut m: req::header_map = HashMap::new(); m.insert(~"METHOD", @RefCell::new(v)); request::<int>(&m); }
extern mod req;
random_line_split
issue-2631-b.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let v = ~[@~"hi"]; let mut m: req::header_map = HashMap::new(); m.insert(~"METHOD", @RefCell::new(v)); request::<int>(&m); }
main
identifier_name
observer-extras.ts
/// <reference path="./disposables/disposable.ts" /> /// <reference path="./checkedobserver.ts" /> /// <reference path="./notification.ts" /> module Rx { export interface Observer<T> { /** * Creates a notification callback from an observer. * @returns The action that forwards its input ...
// Handle completed if (n.kind === 'C') { console.log('Completed') } }); });
{ console.log('Error: ' + n.exception); }
conditional_block
observer-extras.ts
/// <reference path="./disposables/disposable.ts" /> /// <reference path="./checkedobserver.ts" /> /// <reference path="./notification.ts" /> module Rx { export interface Observer<T> { /** * Creates a notification callback from an observer. * @returns The action that forwards its input ...
if (n.kind === 'E') { console.log('Error: ' + n.exception); } // Handle completed if (n.kind === 'C') { console.log('Completed') } }); });
console.log('Next: ' + n.value); } // Handle error calls
random_line_split
header.tsx
import { Button } from '@wordpress/components'; import { Icon, wordpress } from '@wordpress/icons'; import { useI18n } from '@wordpress/react-i18n'; interface SignupFormHeaderProps { onRequestClose: () => void; } interface CloseButtonProps { onClose: () => void; } const CustomCloseButton = ( { onClose }: CloseButt...
</div> <div className="signup-form__header-section"> <div className="signup-form__header-section-item signup-form__header-close-button"> <CustomCloseButton onClose={ onRequestClose } /> </div> </div> </div> ); }; export default SignupFormHeader;
<div className="signup-form__header"> <div className="signup-form__header-section"> <div className="signup-form__header-section-item signup-form__header-wp-logo"> <Icon icon={ wordpress } size={ 28 } /> </div>
random_line_split
json_mixed_data.py
#!/usr/bin/env python # encoding: utf-8 import json decoder = json.JSONDecoder() def get_decoded_and_remainder(input_data): obj, end = decoder.raw_decode(input_data) remaining = input_data[end:] return (obj, end, remaining) encoded_object = '[{"a": "A", "c": 3.0, "b": [2, 4]}]' extra_text = 'This text...
except ValueError, err: print 'ERROR:', err
try: obj, end, remaining = get_decoded_and_remainder( ' '.join([extra_text, encoded_object, extra_text]) )
random_line_split
json_mixed_data.py
#!/usr/bin/env python # encoding: utf-8 import json decoder = json.JSONDecoder() def get_decoded_and_remainder(input_data):
encoded_object = '[{"a": "A", "c": 3.0, "b": [2, 4]}]' extra_text = 'This text is not JSON.' print 'JSON first:' obj, end, remaining = get_decoded_and_remainder(' '.join([encoded_object, extra_text])) print 'Object :', obj print 'End of parsed input :', end print 'Remaining text :', repr(remaining...
obj, end = decoder.raw_decode(input_data) remaining = input_data[end:] return (obj, end, remaining)
identifier_body
json_mixed_data.py
#!/usr/bin/env python # encoding: utf-8 import json decoder = json.JSONDecoder() def
(input_data): obj, end = decoder.raw_decode(input_data) remaining = input_data[end:] return (obj, end, remaining) encoded_object = '[{"a": "A", "c": 3.0, "b": [2, 4]}]' extra_text = 'This text is not JSON.' print 'JSON first:' obj, end, remaining = get_decoded_and_remainder(' '.join([encoded_object, extr...
get_decoded_and_remainder
identifier_name
SunNode.js
import NumberProperty from '../../../../axon/js/NumberProperty.js'; import Property from '../../../../axon/js/Property.js'; import Matrix3 from '../../../../dot/js/Matrix3.js'; import Range from '../../../../dot/js/Range.js'; import Vector2 from '../../../../dot/js/Vector2.js'; import { Shape } from '../../../../kite/j...
tandem: cloudsPanelTandem.createTandem( 'slider' ) } ); const tickLabel = label => { return new Text( label, { font: SLIDER_LABEL_FONT, maxWidth: CONTROL_PANEL_TEXT_MAX_WIDTH } ); }; slider.addMajorTick( 0, tickLabel( noneString ) ); slider.addMajorTick( 1...
sun.cloudinessProportionProperty, new Range( 0, 1 ), { top: 0, left: 0,
random_line_split
SunNode.js
import NumberProperty from '../../../../axon/js/NumberProperty.js'; import Property from '../../../../axon/js/Property.js'; import Matrix3 from '../../../../dot/js/Matrix3.js'; import Range from '../../../../dot/js/Range.js'; import Vector2 from '../../../../dot/js/Vector2.js'; import { Shape } from '../../../../kite/j...
} else if ( currentLightAbsorbingShape !== null ) { lightRays.removeLightAbsorbingShape( currentLightAbsorbingShape ); currentLightAbsorbingShape = null; // for debug if ( EFACQueryParameters.showHelperShapes && helperAbsorptionNode ) { this.removeCh...
{ helperAbsorptionNode = new Path( scaledAndTranslatedAbsorptionShape, { stroke: 'lime', lineDash: [ 4, 8 ] } ); this.addChild( helperAbsorptionNode ); }
conditional_block
SunNode.js
import NumberProperty from '../../../../axon/js/NumberProperty.js'; import Property from '../../../../axon/js/Property.js'; import Matrix3 from '../../../../dot/js/Matrix3.js'; import Range from '../../../../dot/js/Range.js'; import Vector2 from '../../../../dot/js/Vector2.js'; import { Shape } from '../../../../kite/j...
extends Node { /** * inner type - a cloud * @param cloud * @
CloudNode
identifier_name
novelCommentReplies.js
import { normalize } from 'normalizr'; import { takeEvery, apply, put } from 'redux-saga/effects'; import { fetchNovelCommentRepliesSuccess, fetchNovelCommentRepliesFailure, } from '../actions/novelCommentReplies'; import { addError } from '../actions/error'; import pixiv from '../helpers/apiClient'; import { NOVEL...
if (nextUrl) { response = yield apply(pixiv, pixiv.requestUrl, [nextUrl]); } else { response = yield apply(pixiv, pixiv.novelCommentReplies, [ commentId, options, ]); } const normalized = normalize( response.comments, Schemas.NOVEL_COMMENT_ARRAY, ); ...
try { let response;
random_line_split
novelCommentReplies.js
import { normalize } from 'normalizr'; import { takeEvery, apply, put } from 'redux-saga/effects'; import { fetchNovelCommentRepliesSuccess, fetchNovelCommentRepliesFailure, } from '../actions/novelCommentReplies'; import { addError } from '../actions/error'; import pixiv from '../helpers/apiClient'; import { NOVEL...
else { response = yield apply(pixiv, pixiv.novelCommentReplies, [ commentId, options, ]); } const normalized = normalize( response.comments, Schemas.NOVEL_COMMENT_ARRAY, ); yield put( fetchNovelCommentRepliesSuccess( normalized.entities, nor...
{ response = yield apply(pixiv, pixiv.requestUrl, [nextUrl]); }
conditional_block
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Markus Schneider # Copyright 2014 initOS GmbH & Co. KG # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as ...
'external_dependencies': {}, 'author': 'Connector Core Editors', 'license': 'AGPL-3', 'website': 'http://www.odoo-magento-connector.com', 'description': """ """, 'images': [], 'demo': [], 'data': ['magento_model_view.xml', ], 'installable': True, 'application': False, }
'version': '1.0.0', 'category': 'Connector', 'depends': ['magentoerpconnect', ],
random_line_split
jquery.resss.js
/* * Responsive Slideshow - jQuery plugin * * Copyright (c) 2010-2012 Roland Baldovino * * Project home: * https://github.com/junebaldovino/jquery.resss.plugin * * Version: 0.1 * */ (function($){ var _this,settings; var methods = { init : function( options ) { return this.each(function(){ setti...
}, resetCtrls : function(){ cc.find('div').each(function(i){ var li = $(this); i == settings.curPg ? li.addClass('active') : li.removeClass('active'); }); }, addListeners : function(){ // add swipe listeners _this.swipe({swipe:function(event, direction, distance, duration, fingerCount) {meth...
}
random_line_split
decorators-test.js
import Ember from 'ember'; import { task, drop, restartable, enqueue, maxConcurrency } from 'ember-concurrency'; import { enqueueTasksPolicy, dropQueuedTasksPolicy, cancelOngoingTasksPolicy, } from 'ember-concurrency/-buffer-policy'; let decorators = { drop, restartable, enqueue }; const decoratorPolicies = [ ...
let Obj = Ember.Object.extend({ myTask: task(maxConcurrency(5), function * () { }), }); Ember.run(() => { let obj = Obj.create(); let task = obj.get('myTask'); assert.equal(task._maxConcurrency, 5); }); });
test(`task accepts maxConcurrency as a decorator arg`, function(assert) { assert.expect(1);
random_line_split
decorators-test.js
import Ember from 'ember'; import { task, drop, restartable, enqueue, maxConcurrency } from 'ember-concurrency'; import { enqueueTasksPolicy, dropQueuedTasksPolicy, cancelOngoingTasksPolicy, } from 'ember-concurrency/-buffer-policy'; let decorators = { drop, restartable, enqueue }; const decoratorPolicies = [ ...
(decoratorName, decorator, bufferPolicy) { test(`task accepts ${decoratorName} as a decorator arg`, function(assert) { assert.expect(1); let Obj = Ember.Object.extend({ myTask: task(decorator, function * () { }), }); Ember.run(() => { let obj = Obj.create(); let task = obj.get('myT...
decoratorTest
identifier_name
decorators-test.js
import Ember from 'ember'; import { task, drop, restartable, enqueue, maxConcurrency } from 'ember-concurrency'; import { enqueueTasksPolicy, dropQueuedTasksPolicy, cancelOngoingTasksPolicy, } from 'ember-concurrency/-buffer-policy'; let decorators = { drop, restartable, enqueue }; const decoratorPolicies = [ ...
test(`task accepts maxConcurrency as a decorator arg`, function(assert) { assert.expect(1); let Obj = Ember.Object.extend({ myTask: task(maxConcurrency(5), function * () { }), }); Ember.run(() => { let obj = Obj.create(); let task = obj.get('myTask'); assert.equal(task._maxConcurrency, 5); ...
{ test(`task accepts ${decoratorName} as a decorator arg`, function(assert) { assert.expect(1); let Obj = Ember.Object.extend({ myTask: task(decorator, function * () { }), }); Ember.run(() => { let obj = Obj.create(); let task = obj.get('myTask'); assert.equal(task.bufferPoli...
identifier_body
nacl_utils_test.py
#!/usr/bin/env python # Copyright (c) 2012 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. """Unit tests for nacl_utils.py.""" import fileinput import mox import nacl_utils import os import sys import unittest def TestM...
def testGetJSONFromNexeSpec(self): valid_empty_json = '{\n "program": {\n }\n}\n' null_json = nacl_utils.GetJSONFromNexeSpec(None) self.assertEqual(null_json, valid_empty_json) empty_json = nacl_utils.GetJSONFromNexeSpec({}) self.assertEqual(empty_json, valid_empty_json) nexes = {'x86-32':...
output = nacl_utils.ToolchainPath('nacl_sdk_root') head, tail = os.path.split(output) base, toolchain = os.path.split(head) self.assertEqual('nacl_sdk_root', base) self.assertEqual('toolchain', toolchain) self.assertRaises(ValueError, nacl_utils.ToolchainPath, ...
identifier_body
nacl_utils_test.py
#!/usr/bin/env python # Copyright (c) 2012 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. """Unit tests for nacl_utils.py.""" import fileinput import mox import nacl_utils import os import sys import unittest def TestM...
(self): valid_empty_json = '{\n "program": {\n }\n}\n' null_json = nacl_utils.GetJSONFromNexeSpec(None) self.assertEqual(null_json, valid_empty_json) empty_json = nacl_utils.GetJSONFromNexeSpec({}) self.assertEqual(empty_json, valid_empty_json) nexes = {'x86-32': 'nacl_x86_32.nexe', ...
testGetJSONFromNexeSpec
identifier_name
nacl_utils_test.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be
"""Unit tests for nacl_utils.py.""" import fileinput import mox import nacl_utils import os import sys import unittest def TestMock(file_path, open_func): temp_file = open_func(file_path) temp_file.close() class TestNaClUtils(unittest.TestCase): """Class for test cases to cover globally declared helper funct...
# found in the LICENSE file.
random_line_split
nacl_utils_test.py
#!/usr/bin/env python # Copyright (c) 2012 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. """Unit tests for nacl_utils.py.""" import fileinput import mox import nacl_utils import os import sys import unittest def TestM...
return return_value if __name__ == '__main__': sys.exit(RunTests())
return_value = 0
conditional_block
stylepropertymapreadonly.rs
* 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 dom::bindings::codegen::Bindings::StylePropertyMapReadOnlyBinding::StylePropertyMapReadOnlyMethods; use dom::bindings::codegen::Bindings::StylePropertyMapReadOnlyBinding::Wrap; use ...
/* This Source Code Form is subject to the terms of the Mozilla Public
random_line_split
stylepropertymapreadonly.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 dom::bindings::codegen::Bindings::StylePropertyMapReadOnlyBinding::StylePropertyMapReadOnlyMethods; use dom::b...
{ reflector: Reflector, entries: HashMap<Atom, JS<CSSStyleValue>>, } impl StylePropertyMapReadOnly { fn new_inherited<Entries>(entries: Entries) -> StylePropertyMapReadOnly where Entries: IntoIterator<Item=(Atom, JS<CSSStyleValue>)> { StylePropertyMapReadOnly { reflector: R...
StylePropertyMapReadOnly
identifier_name
stylepropertymapreadonly.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 dom::bindings::codegen::Bindings::StylePropertyMapReadOnlyBinding::StylePropertyMapReadOnlyMethods; use dom::b...
}
{ // TODO: avoid constructing an Atom self.entries.contains_key(&Atom::from(property)) }
identifier_body
jquery-ui.searchflyout.js
/*global console: false, creatis_carpenterStorage_replaceContentFromStorage: false */ $(function () { function initDesktop() { $("#accordion").accordion({ collapsible: true, active: localStorage.selectedCarpenter ? false : true, }); // Kontaktseite Suche $...
{ window.removeEventListener('scroll', scrollHandler); window.addEventListener('scroll', noScrollFn); } function scrollFn() { window.addEventListener('scroll', scrollHandler); } function canScroll() { window.removeEventListener('scroll',...
Scroll()
identifier_name
jquery-ui.searchflyout.js
/*global console: false, creatis_carpenterStorage_replaceContentFromStorage: false */ $(function () { function initDesktop() { $("#accordion").accordion({ collapsible: true, active: localStorage.selectedCarpenter ? false : true, });
var searchQuery = $("#search-query-site").val(); if (isValidPostal(searchQuery)) { document.location = "/tischler?query=" + searchQuery; } return false; }); $("#search-query-site").on('input', function () { var isValid = is...
// Kontaktseite Suche $("#search-site-submit").click(function () {
random_line_split
jquery-ui.searchflyout.js
/*global console: false, creatis_carpenterStorage_replaceContentFromStorage: false */ $(function () { function initDesktop() { $("#accordion").accordion({ collapsible: true, active: localStorage.selectedCarpenter ? false : true, }); // Kontaktseite Suche $...
}); var mobileSearchMorphingButton = new UIMorphingButton(mobileSearchButton, { closeEl: '.icon-close', onBeforeOpen: function () { // don't allow to scroll noScroll(); }, onAfterOpen: function () { // can sc...
ev.originalEvent.preventDefault(); }
conditional_block
jquery-ui.searchflyout.js
/*global console: false, creatis_carpenterStorage_replaceContentFromStorage: false */ $(function () { function initDesktop() { $("#accordion").accordion({ collapsible: true, active: localStorage.selectedCarpenter ? false : true, }); // Kontaktseite Suche $...
if (localStorage.selectedCarpenter) { $('#div_text').css('display', 'none'); var data = JSON.parse(localStorage.getItem('selectedCarpenter')); var cId = data.id; setTimeout(function () { $('#' + cId + ' .btn-select').first().trigger('click'); }, 50); } }
identifier_body
program.component.ts
import { Component, ComponentFactoryResolver, Input, OnChanges, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import {ProgramsService} from '../../../services/dataLoading/programs.service'; import {Program} from "../../../models/Program.model"; import {OrganizationUnit} from "../../../models/Orga...
/* * Send a ValidationMessage upon changes in the checkbox selection */ selectProgram(event: any): void { this.container.clear(); let comp = this._cfr.resolveComponentFactory(ProgramFilterComponent); let filterComp = this.container.createComponent(comp); filterComp.ins...
}
random_line_split
program.component.ts
import { Component, ComponentFactoryResolver, Input, OnChanges, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import {ProgramsService} from '../../../services/dataLoading/programs.service'; import {Program} from "../../../models/Program.model"; import {OrganizationUnit} from "../../../models/Orga...
this.query = 'organisationUnits?filter=id:eq:' + orgUnit.id + '&fields=programs[id,displayName]&paging=0'; this._progService.loadPrograms(this.query) .subscribe((units: any) => { this.programs = units.organisationUnits[0].programs; this.selectedProgram = null...
{ this.programs = []; return; }
conditional_block
program.component.ts
import { Component, ComponentFactoryResolver, Input, OnChanges, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import {ProgramsService} from '../../../services/dataLoading/programs.service'; import {Program} from "../../../models/Program.model"; import {OrganizationUnit} from "../../../models/Orga...
(private _progService: ProgramsService, private _mapInputDataService: MapInputDataService, private _cfr: ComponentFactoryResolver) { } /* * Upon changes in the input (organisationUnit), then reload the programs */ ngOnChanges(changes: any) { this.showProgra...
constructor
identifier_name
program.component.ts
import { Component, ComponentFactoryResolver, Input, OnChanges, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import {ProgramsService} from '../../../services/dataLoading/programs.service'; import {Program} from "../../../models/Program.model"; import {OrganizationUnit} from "../../../models/Orga...
ngOnInit() { } /* * Loads the programs thats connected to a given org.unit */ showPrograms(orgUnit: OrganizationUnit): void { if (orgUnit == null) { this.programs = []; return; } this.query = 'organisationUnits?filter=id:eq:' + orgUnit.id + '&...
{ this.showPrograms(this.selectedOrgUnit); }
identifier_body
atomic_xor_relaxed.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_xor_relaxed; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_xor_relaxed<T>(dst: *mut T, src: T) -> T; struct
<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = usize; macro_rules! atomic_xor_relaxed_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>:...
A
identifier_name
atomic_xor_relaxed.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_xor_relaxed; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_xor_relaxed<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } un...
#[test] fn atomic_xor_relaxed_test1() { atomic_xor_relaxed_test!( 0xff00, 0x0a0a, 0xf50a ); } }
}
random_line_split