file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
prepare.py
# -*- coding: utf-8 -*- # # This file is part of kwalitee # Copyright (C) 2014, 2015 CERN. # # kwalitee 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 2 of the # License, or (at your option) an...
for lbl, bullet in commit['paragraphs'] if lbl == label and bullet is not None ] if len(bullets) > 0: print(section) print('-' * len(section)) print() if group_components: def key(cmt): ...
for commit in full_messages: bullets += [ {'text': bullet, 'component': commit['component']}
random_line_split
prepare.py
# -*- coding: utf-8 -*- # # This file is part of kwalitee # Copyright (C) 2014, 2015 CERN. # # kwalitee 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 2 of the # License, or (at your option) an...
"""Generate release notes.""" from ..kwalitee import get_options from ..hooks import _read_local_kwalitee_configuration options = get_options(current_app.config) options.update(_read_local_kwalitee_configuration(directory=repository)) try: sha = 'oid' commits = _pygit2_commits(commi...
identifier_body
point-mutations.rs
extern crate point_mutations as dna; #[test] fn
() { assert_eq!(dna::hamming_distance("", "").unwrap(), 0); } #[test] #[ignore] fn test_no_difference_between_identical_strands() { assert_eq!(dna::hamming_distance("GGACTGA", "GGACTGA").unwrap(), 0); } #[test] #[ignore] fn test_complete_hamming_distance_in_small_strand() { assert_eq!(dna::hamming_distanc...
test_no_difference_between_empty_strands
identifier_name
point-mutations.rs
extern crate point_mutations as dna; #[test] fn test_no_difference_between_empty_strands() { assert_eq!(dna::hamming_distance("", "").unwrap(), 0); } #[test] #[ignore] fn test_no_difference_between_identical_strands() { assert_eq!(dna::hamming_distance("GGACTGA", "GGACTGA").unwrap(), 0); } #[test] #[ignore] ...
#[test] #[ignore] fn test_first_string_is_longer() { assert_eq!(dna::hamming_distance("AAA", "AA"), Result::Err("inputs of different length")); } #[test] #[ignore] fn test_second_string_is_longer() { assert_eq!(dna::hamming_distance("A", "AA"), Result::Err("inputs of different length")); }
fn test_larger_distance() { assert_eq!(dna::hamming_distance("ACCAGGG", "ACTATGG").unwrap(), 2); }
random_line_split
point-mutations.rs
extern crate point_mutations as dna; #[test] fn test_no_difference_between_empty_strands() { assert_eq!(dna::hamming_distance("", "").unwrap(), 0); } #[test] #[ignore] fn test_no_difference_between_identical_strands() { assert_eq!(dna::hamming_distance("GGACTGA", "GGACTGA").unwrap(), 0); } #[test] #[ignore] ...
#[test] #[ignore] fn test_larger_distance() { assert_eq!(dna::hamming_distance("ACCAGGG", "ACTATGG").unwrap(), 2); } #[test] #[ignore] fn test_first_string_is_longer() { assert_eq!(dna::hamming_distance("AAA", "AA"), Result::Err("inputs of different length")); } #[test] #[ignore] fn test_second_string_is_lo...
{ assert_eq!(dna::hamming_distance("GGACG", "GGTCG").unwrap(), 1); }
identifier_body
firewall.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you m...
LOG = logging.getLogger(__name__) class Dom0IptablesFirewallDriver(firewall.IptablesFirewallDriver): """ Dom0IptablesFirewallDriver class This class provides an implementation for nova.virt.Firewall using iptables. This class is meant to be used with the xenapi backend and uses xenapi plugin to enfo...
from nova.virt import firewall from nova.virt import netutils
random_line_split
firewall.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you m...
elif protocol == 'icmp': icmp_type = rule['from_port'] icmp_code = rule['to_port'] if icmp_type == -1: icmp_type_arg = None else: icmp_type_arg = '%s' % icmp_type if not icmp_code ==...
args += ['--dport', '%s:%s' % (rule['from_port'], rule['to_port'])]
conditional_block
firewall.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you m...
(self, *cmd, **kwargs): # Prepare arguments for plugin call args = {} args.update(map(lambda x: (x, str(kwargs[x])), kwargs)) args['cmd_args'] = jsonutils.dumps(cmd) ret = self._session.call_plugin('xenhost', 'iptables_config', args) json_ret = jsonutils.loads(ret) ...
_plugin_execute
identifier_name
firewall.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you m...
def __init__(self, virtapi, xenapi_session=None, **kwargs): from nova.network import linux_net super(Dom0IptablesFirewallDriver, self).__init__(virtapi, **kwargs) self._session = xenapi_session # Create IpTablesManager with executor through plugin self.iptables = linux_net....
args = {} args.update(map(lambda x: (x, str(kwargs[x])), kwargs)) args['cmd_args'] = jsonutils.dumps(cmd) ret = self._session.call_plugin('xenhost', 'iptables_config', args) json_ret = jsonutils.loads(ret) return (json_ret['out'], json_ret['err'])
identifier_body
jquery.tweet.js
(function($) { $.fn.tweet = function(o){ var s = $.extend({ username: ["seaofclouds"], // [string] required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"] list: null, // [string] optional name of ...
template: "{avatar}{time}{join}{text}", // [string or function] template used to construct each tweet <li> - see code for available vars comparator: function(tweet1, tweet2) { // [function] comparator used to sort tweets (see Array.sort) return tweet2["tweet_time"] - tweet1["tweet_time"]; ...
refresh_interval: null , // [integer] optional number of seconds after which to reload tweets twitter_url: "twitter.com", // [string] custom twitter url, if any (apigee, etc.) twitter_api_url: "api.twitter.com", // [string] custom twitter api url, if any (apig...
random_line_split
jquery.tweet.js
(function($) { $.fn.tweet = function(o){ var s = $.extend({ username: ["seaofclouds"], // [string] required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"] list: null, // [string] optional name of ...
tion build_url() { var proto = ('https:' == document.location.protocol ? 'https:' : 'http:'); var count = (s.fetch === null) ? s.count : s.fetch; if (s.list) { return proto+"//"+s.twitter_api_url+"/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+count+"&callback=?"; } else ...
r relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - date) / 1000, 10); var r = ''; if (delta < 60) { r = delta + ' seconds ago'; } else if(delta < 120) { r = 'a minute ago'; } else if(delta < (45*60)) { r...
identifier_body
jquery.tweet.js
(function($) { $.fn.tweet = function(o){ var s = $.extend({ username: ["seaofclouds"], // [string] required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"] list: null, // [string] optional name of ...
urn 'about ' + r; } function build_url() { var proto = ('https:' == document.location.protocol ? 'https:' : 'http:'); var count = (s.fetch === null) ? s.count : s.fetch; if (s.list) { return proto+"//"+s.twitter_api_url+"/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+c...
r = (parseInt(delta / 86400, 10)).toString() + ' days ago'; } ret
conditional_block
jquery.tweet.js
(function($) { $.fn.tweet = function(o){ var s = $.extend({ username: ["seaofclouds"], // [string] required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"] list: null, // [string] optional name of ...
var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - date) / 1000, 10); var r = ''; if (delta < 60) { r = delta + ' seconds ago'; } else if(delta < 120) { r = 'a minute ago'; } else if(delta < (45*60)) { ...
ime(date) {
identifier_name
p048.rs
//! [Problem 48](https://projecteuler.net/problem=48) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; use num_traits::{FromPrimitive, ToPrimitive}; fn compute(max: u64, modulo: u64) -> u64 { ...
} common::problem!("9110846700", solve); #[cfg(test)] mod tests { #[test] fn ten() { let modulo = 100_0000_0000; assert_eq!(10405071317 % modulo, super::compute(10, modulo)) } }
random_line_split
p048.rs
//! [Problem 48](https://projecteuler.net/problem=48) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; use num_traits::{FromPrimitive, ToPrimitive}; fn compute(max: u64, modulo: u64) -> u64 { ...
() -> String { compute(1000, 100_0000_0000).to_string() } common::problem!("9110846700", solve); #[cfg(test)] mod tests { #[test] fn ten() { let modulo = 100_0000_0000; assert_eq!(10405071317 % modulo, super::compute(10, modulo)) } }
solve
identifier_name
p048.rs
//! [Problem 48](https://projecteuler.net/problem=48) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; use num_traits::{FromPrimitive, ToPrimitive}; fn compute(max: u64, modulo: u64) -> u64 { ...
common::problem!("9110846700", solve); #[cfg(test)] mod tests { #[test] fn ten() { let modulo = 100_0000_0000; assert_eq!(10405071317 % modulo, super::compute(10, modulo)) } }
{ compute(1000, 100_0000_0000).to_string() }
identifier_body
index.js
/* * Copyright 2020 Google LLC * * 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 *
* distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Manipulate pages. export { default as addPage } from './addPag...
* https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software
random_line_split
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T, F>(mut f: F) -> io::Result<T> where T: SignedInt, F: FnMut() -> T { loop { match cvt(f()) { Err(ref e) if e.kind() == ErrorKind::Interrupted => {} other => return other, } } } pub fn ms_to_timeval(ms: u64) -> libc::timeval { libc::timeval { tv_sec: (m...
cvt_r
identifier_name
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn wouldblock() -> bool { let err = os::errno(); err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32 } pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> { let set = nb as libc::c_int; mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) })) } // nothing needed on unix...
{ libc::timeval { tv_sec: (ms / 1000) as libc::time_t, tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t, } }
identifier_body
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}; ) } pub mod backtrace; pub mod c; pub mod condvar; pub mod ext; pub mod fd; pub mod fs; // support for std::old_io pub mod fs2; // support for std::fs pub mod helper_signal; pub mod mutex; pub mod net; pub mod os; pub mod os_str; pub mod pipe; pub mod process; pub mod rwlock; pub mod stack_overflow; pub mod sy...
cond: ::sync::CONDVAR_INIT, chan: ::cell::UnsafeCell { value: 0 as *mut Sender<$m> }, signal: ::cell::UnsafeCell { value: 0 }, initialized: ::cell::UnsafeCell { value: false }, shutdown: ::cell::UnsafeCell { value: false },
random_line_split
configs.py
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # ModRana config files handling #---------------------------------------------------------------------------- # Copyright 2012, Martin Kolman # # This program is free software: you can redistribute it and/or modify # i...
(self): """ get the "raw" map config """ return self.mapConfig def loadMapConfig(self): """ load the map configuration file """ configVariables = { 'label': 'label', 'url': 'tiles', 'max_zoom': 'maxZoom', ...
getMapConfig
identifier_name
configs.py
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # ModRana config files handling #---------------------------------------------------------------------------- # Copyright 2012, Martin Kolman # # This program is free software: you can redistribute it and/or modify # i...
def getUserConfig(self): return self.userConfig def loadUserConfig(self): """load the user oriented configuration file.""" path = os.path.join(self.modrana.paths.getProfilePath(), "user_config.conf") try: config = ConfigObj(path) if 'enabled' in config...
""" load all configuration files """ self.loadMapConfig() self.loadUserConfig()
identifier_body
configs.py
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # ModRana config files handling #---------------------------------------------------------------------------- # Copyright 2012, Martin Kolman # # This program is free software: you can redistribute it and/or modify # i...
def loadAll(self): """ load all configuration files """ self.loadMapConfig() self.loadUserConfig() def getUserConfig(self): return self.userConfig def loadUserConfig(self): """load the user oriented configuration file.""" path = os.path.joi...
log.info("no configuration files needed upgrade")
conditional_block
configs.py
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # ModRana config files handling #---------------------------------------------------------------------------- # Copyright 2012, Martin Kolman # # This program is free software: you can redistribute it and/or modify # i...
def getUserAgent(self): """return the default modRana User-Agent""" #debugging: # return "Mozilla/5.0 (compatible; MSIE 5.5; Linux)" #TODO: setting from configuration file, CLI & interface return "modRana flexible GPS navigation system (compatible; Linux)"
random_line_split
main.rs
#![feature(asm)] #![feature(const_fn)] #![feature(proc_macro)] #![no_std] extern crate cast; extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate blue_pill; extern crate numtoa; use blue_pill::stm32f103xx::Interrupt; use cortex_m::peripheral::SystClkSource; use rtfm::{app, Threshold}; mod font5x7;...
p.RCC.apb1enr.modify(|_, w| w.i2c1en().enabled()); p.I2C1.cr1.write(|w| w.pe().clear_bit()); p.GPIOA.crl.modify(|_, w| w.mode6().input()); p.GPIOA.crh.modify(|_, w| { w.mode8().output50().cnf8().push().mode9().input() }); p.GPIOA.bsrr.write(|w| { w.bs6().set_bit().bs8().set_bi...
}); p.AFIO.mapr.modify(|_, w| unsafe { w.swj_cfg().bits(2).i2c1_remap().clear_bit() });
random_line_split
main.rs
#![feature(asm)] #![feature(const_fn)] #![feature(proc_macro)] #![no_std] extern crate cast; extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate blue_pill; extern crate numtoa; use blue_pill::stm32f103xx::Interrupt; use cortex_m::peripheral::SystClkSource; use rtfm::{app, Threshold}; mod font5x7;...
(_t: &mut Threshold, r: EXTI0::Resources) { let i2c1 = &**r.I2C1; let oled = SSD1306(OLED_ADDR, &i2c1); let am = MMA8652FC(&i2c1); r.STATE.update_accel(am.accel()); r.STATE.update_state(); oled.print(0, 0, "X "); oled.print(8, 0, "Y "); oled.print(0, 1, "Z "); let accel = r.STATE....
update_ui
identifier_name
main.rs
#![feature(asm)] #![feature(const_fn)] #![feature(proc_macro)] #![no_std] extern crate cast; extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate blue_pill; extern crate numtoa; use blue_pill::stm32f103xx::Interrupt; use cortex_m::peripheral::SystClkSource; use rtfm::{app, Threshold}; mod font5x7;...
; exti.pr.write(|w| w.pr6().set_bit()); // Button B } else if exti.pr.read().pr9().bit_is_set() { if gpioa.idr.read().idr9().bit_is_clear() { r.STATE.update_keys(Keys::B) } else { r.STATE.update_keys(Keys::None) }; exti.pr.write(|w| w.pr9().set_bit(...
{ r.STATE.update_keys(Keys::None); }
conditional_block
main.rs
#![feature(asm)] #![feature(const_fn)] #![feature(proc_macro)] #![no_std] extern crate cast; extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate blue_pill; extern crate numtoa; use blue_pill::stm32f103xx::Interrupt; use cortex_m::peripheral::SystClkSource; use rtfm::{app, Threshold}; mod font5x7;...
fn idle() -> ! { rtfm::set_pending(Interrupt::EXTI0); loop { rtfm::wfi(); } } fn tick(_t: &mut Threshold, r: SYS_TICK::Resources) { **r.TICKS += 1; } fn update_ui(_t: &mut Threshold, r: EXTI0::Resources) { let i2c1 = &**r.I2C1; let oled = SSD1306(OLED_ADDR, &i2c1); let am = MMA8...
{ // 48Mhz p.FLASH.acr.modify( |_, w| w.prftbe().enabled().latency().one(), ); p.RCC.cfgr.modify(|_, w| unsafe { w.bits(0x0068840A) }); p.RCC.cr.modify( |_, w| w.pllon().set_bit().hsion().set_bit(), ); while p.RCC.cr.read().pllrdy().bit_is_clear() {} while p.RCC.cr.read(...
identifier_body
index.d.ts
export { default as RNG } from "./rng.js"; export { default as Display } from "./display/display.js"; export { default as StringGenerator } from "./stringgenerator.js"; export { default as EventQueue } from "./eventqueue.js"; export { default as Scheduler, SpeedActor } from "./scheduler/index.js"; export { default as F...
import * as color from "./color.js"; export declare const Color: typeof color; import * as text from "./text.js"; export declare const Text: typeof text;
import * as util from "./util.js"; export declare const Util: typeof util;
random_line_split
ActivityServices.js
app.factory("ActivityIndexService",ActivityIndexService); ActivityIndexService.$inject = ['$http']; function ActivityIndexService($http){ return {getActivities: function(offsets){ var url = "/index_pagination?page="+offsets; return $http.get(url); } } } app.factory("...
($resource){ return { removeFeed:function(){ return $resource("/activities/remove_activity"); } } }
ActivityRemoveService
identifier_name
ActivityServices.js
app.factory("ActivityIndexService",ActivityIndexService); ActivityIndexService.$inject = ['$http']; function ActivityIndexService($http)
app.factory("ActivityOtherUserService",ActivityOtherUserService); ActivityOtherUserService.$inject = ['$http']; function ActivityOtherUserService($http){ return { getFeed:function(user_id,trackable_id,trackable_type){ var tr_type = angular.lowercase(trackable_type); ...
{ return {getActivities: function(offsets){ var url = "/index_pagination?page="+offsets; return $http.get(url); } } }
identifier_body
ActivityServices.js
app.factory("ActivityIndexService",ActivityIndexService); ActivityIndexService.$inject = ['$http']; function ActivityIndexService($http){ return {getActivities: function(offsets){ var url = "/index_pagination?page="+offsets; return $http.get(url); } }
} app.factory("ActivityOtherUserService",ActivityOtherUserService); ActivityOtherUserService.$inject = ['$http']; function ActivityOtherUserService($http){ return { getFeed:function(user_id,trackable_id,trackable_type){ var tr_type = angular.lowercase(trackable_type); ...
random_line_split
RuleDetailsProfiles.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, o...
}
</div> </div> ); }
random_line_split
RuleDetailsProfiles.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, o...
const profilePath = getQualityProfileUrl(profile.parentName, profile.language); return ( <div className="coding-rules-detail-quality-profile-inheritance"> {(activation.inherit === 'OVERRIDES' || activation.inherit === 'INHERITED') && ( <> <RuleInheritanceIcon className="text...
{ return null; }
conditional_block
RuleDetailsProfiles.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, o...
( 'coding_rules.revert_to_parent_definition.confirm', profile.parentName )} modalHeader={translate('coding_rules.revert_to_parent_definition')} onConfirm={this.handleRevert}> {({ onClick }) => ( ...
translateWithParameters
identifier_name
RuleDetailsProfiles.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, o...
onConfirm={this.handleRevert}> {({ onClick }) => ( <Button className="coding-rules-detail-quality-profile-revert button-red spacer-left" onClick={onClick}> {translate('coding_rules.revert_to_parent...
{translate('coding_rules.revert_to_parent_definition')}
identifier_body
sidemenu.js
/* * @version $Id: sidemenu.js 12458 2013-08-05 22:27:48Z djamil $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ ((function(){var a=this.SideMenu=new Class({initialize:function(){...
if(d=="(min-width: 768px)"){e.inject(this.originalPosition);this.toggler.setStyle("display","none");}else{e.inject(c);this.toggler.setStyle("display","block"); }this.toggler.removeClass("active");}});window.addEvent("domready",function(){this.RokNavMenu=new a();});})());
{return;}
conditional_block
sidemenu.js
/*
*/ ((function(){var a=this.SideMenu=new Class({initialize:function(){this.build(); this.attachEvents();this.mediaQuery(RokMediaQueries.getQuery());},build:function(){if(this.toggler){return this.toggler;}this.toggler=new Element("div.gf-menu-toggle").inject(document.body); this.container=document.getElement(".gf-menu-...
* @version $Id: sidemenu.js 12458 2013-08-05 22:27:48Z djamil $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
random_line_split
DOM.js
/* Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.DOM"]){ //_hasResource checks added by build. Do not use _hasResource directly in your ...
for (var i = 0; i < arguments.length; i++){ arguments[i] = unwrap(arguments[i]); } return wrap(result.apply(unwrap(this),arguments)); } } } return result; } unwrap = dojox.secure.unwrap; function safeCSS(css){ css += ''; // make sure it is a string if(css.match(/behavior:|conte...
{ result.safetyCheck.apply(unwrap(this),arguments); }
conditional_block
DOM.js
/* Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.DOM"]){ //_hasResource checks added by build. Do not use _hasResource directly in your ...
throw new Error("Illegal CSS"); } var id = element.id || (element.id = "safe" + ('' + Math.random()).substring(2)); return css.replace(/(\}|^)\s*([^\{]*\{)/g,function(t,a,b){ // put all the styles in the context of the id of the sandbox return a + ' #' + id + ' ' + b; // need to remove body and html referen...
random_line_split
DOM.js
/* Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.DOM"]){ //_hasResource checks added by build. Do not use _hasResource directly in your ...
function safeElement(el){ // test an element to see if it is safe if(el && el.nodeType == 1){ if(el.tagName.match(/script/i)){ var src = el.src; if (src && src != ""){ // load the src and evaluate it safely el.parentNode.removeChild(el); dojo.xhrGet({url:src,secure:true}).addCallbac...
{ // test a url to see if it is safe if(url.match(/:/) && !url.match(/^(http|ftp|mailto)/)){ throw new Error("Unsafe URL " + url); } }
identifier_body
DOM.js
/* Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.DOM"]){ //_hasResource checks added by build. Do not use _hasResource directly in your ...
(name,newNodeArg){ return function(node,args){ safeElement(args[newNodeArg]); // check to make sure the new node is safe return node[name](args[0]);// execute the method }; } var invokers = { appendChild : domChanger("appendChild",0), insertBefore : domChanger("insertBefore",0), replaceChild : domCh...
domChanger
identifier_name
version.py
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 usefu...
def execute_post(self, *args, **kwargs): return hresponse.HandlerResponse(501) def execute_delete(self, *args, **kwargs): return hresponse.HandlerResponse(501)
} ] return response
random_line_split
version.py
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 usefu...
(self, *args, **kwargs): response = hresponse.HandlerResponse() response.result = [ { models.VERSION_FULL_KEY: handlers.__versionfull__, models.VERSION_KEY: handlers.__version__, } ] return response def execute_post(self, *args...
execute_get
identifier_name
version.py
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 usefu...
def execute_get(self, *args, **kwargs): response = hresponse.HandlerResponse() response.result = [ { models.VERSION_FULL_KEY: handlers.__versionfull__, models.VERSION_KEY: handlers.__version__, } ] return response def exe...
super(VersionHandler, self).__init__(application, request, **kwargs)
identifier_body
elementClick.ts
import getElementTagName from './getElementTagName' import selectOptionScript from '../scripts/selectOption' import { getStaleElementError } from '../utils' import type DevToolsDriver from '../devtoolsdriver' /** * The Element Click command scrolls into view the element if it is not already pointer-interactable, * a...
( this: DevToolsDriver, { elementId }: { elementId: string } ) { const page = this.getPageHandle() const elementHandle = await this.elementStore.get(elementId) if (!elementHandle) { throw getStaleElementError(elementId) } /** * in order to allow clicking on option elements (a...
elementClick
identifier_name
elementClick.ts
import getElementTagName from './getElementTagName' import selectOptionScript from '../scripts/selectOption' import { getStaleElementError } from '../utils' import type DevToolsDriver from '../devtoolsdriver' /** * The Element Click command scrolls into view the element if it is not already pointer-interactable, * a...
page.once('dialog', dialogHandler) return elementHandle.click().then(() => { /** * no modals popped up, so clean up the listener */ page.removeListener('dialog', dialogHandler) resolve(null) }).catch(reject) }) }
* click action, just continue in this case */ const dialogHandler = () => resolve(null)
random_line_split
elementClick.ts
import getElementTagName from './getElementTagName' import selectOptionScript from '../scripts/selectOption' import { getStaleElementError } from '../utils' import type DevToolsDriver from '../devtoolsdriver' /** * The Element Click command scrolls into view the element if it is not already pointer-interactable, * a...
{ const page = this.getPageHandle() const elementHandle = await this.elementStore.get(elementId) if (!elementHandle) { throw getStaleElementError(elementId) } /** * in order to allow clicking on option elements (as WebDriver does) * we need to check if the element is such a an el...
identifier_body
elementClick.ts
import getElementTagName from './getElementTagName' import selectOptionScript from '../scripts/selectOption' import { getStaleElementError } from '../utils' import type DevToolsDriver from '../devtoolsdriver' /** * The Element Click command scrolls into view the element if it is not already pointer-interactable, * a...
/** * ensure to fulfill the click promise if the click has triggered an alert */ return new Promise((resolve, reject) => { /** * listen on possible modal dialogs that might pop up due to the * click action, just continue in this case */ const dialogHandler ...
{ return page.$eval('html', selectOptionScript, elementHandle) }
conditional_block
error-msg.pipe.ts
/** * Copyright 2020 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
// add an html tag to links let urlStartIdx = newValue.indexOf('https://'); let urlEndIdx = newValue.indexOf(' ', urlStartIdx); let startTag = '<a href="' + newValue.substring(urlStartIdx, urlEndIdx) + '"target="_blank">'; let endTag = '</a>'; newValue = newValue.substr...
// Remove Error code if it exists let newValue = value.replace('403 ', ''); // Add new lines to make it more readible newValue = newValue.replaceAll('. ', '.\n\n');
random_line_split
error-msg.pipe.ts
/** * Copyright 2020 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
(private sanitizer: DomSanitizer) {} transform(value: any, ...args: unknown[]): unknown { // Remove Error code if it exists let newValue = value.replace('403 ', ''); // Add new lines to make it more readible newValue = newValue.replaceAll('. ', '.\n\n'); // add an html tag to links let urlStar...
constructor
identifier_name
packet_kind.rs
/* Copyright © 2016 Zetok Zalbavar <zexavexxe@gmail.com> This file is part of Tox.
Tox 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 received a copy of the GNU General Public License alon...
Tox is libre 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.
random_line_split
packet_kind.rs
/* Copyright © 2016 Zetok Zalbavar <zexavexxe@gmail.com> This file is part of Tox. Tox is libre 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...
{ /// [`Ping`](./struct.Ping.html) request number. PingReq = 0, /// [`Ping`](./struct.Ping.html) response number. PingResp = 1, /// [`GetNodes`](./struct.GetNodes.html) packet number. GetN = 2, /// [`SendNodes`](./struct.SendNodes.html) packet number. SendN = ...
acketKind
identifier_name
instr_subsd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn subsd_1() { run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM2...
{ run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(RBX, 212302300, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 163, 220...
identifier_body
instr_subsd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn subsd_1() { run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM2...
() { run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(RBX, 212302300, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 163, ...
subsd_4
identifier_name
instr_subsd.rs
use ::RegScale::*; use ::test::run_test; #[test] fn subsd_1() { run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92...
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*;
random_line_split
index.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
export { ExploreType, ExploreTypeLink } from './ExploreType' export { ExploreProperty, ExplorePropertyNode, ExplorePropertyDetail, ExplorePropertyType, } from './ExploreProperty' export { typeIcon, pickTypeProps, typeLinkPrefix, typeLinkSuffix, pickType, expandable, } from './exploreUtils'
random_line_split
index.tsx
// TODO: 4.0 - codemod should help to change `filterOption` to support node props. import * as React from 'react'; import omit from 'rc-util/lib/omit'; import classNames from 'classnames'; import RcSelect, { Option, OptGroup, SelectProps as RcSelectProps } from 'rc-select'; import { OptionProps } from 'rc-select/lib/O...
} export interface SelectProps<VT> extends Omit<InternalSelectProps<VT>, 'inputIcon' | 'mode' | 'getInputElement' | 'backfill'> { mode?: 'multiple' | 'tags'; } export interface RefSelectProps { focus: () => void; blur: () => void; } const SECRET_COMBOBOX_MODE_DO_NOT_USE = 'SECRET_COMBOBOX_MODE_DO_NOT_USE'; ...
mode?: 'multiple' | 'tags' | 'SECRET_COMBOBOX_MODE_DO_NOT_USE'; bordered?: boolean;
random_line_split
index.tsx
// TODO: 4.0 - codemod should help to change `filterOption` to support node props. import * as React from 'react'; import omit from 'rc-util/lib/omit'; import classNames from 'classnames'; import RcSelect, { Option, OptGroup, SelectProps as RcSelectProps } from 'rc-select'; import { OptionProps } from 'rc-select/lib/O...
if (m === SECRET_COMBOBOX_MODE_DO_NOT_USE) { return 'combobox'; } return m; }, [props.mode]); const isMultiple = mode === 'multiple' || mode === 'tags'; // ===================== Empty ===================== let mergedNotFound: React.ReactNode; if (notFoundContent !== undefined) { mer...
{ return undefined; }
conditional_block
svm.py
# -*- coding: utf-8 -*- # Copyright (C) 2008-2015, Luis Pedro Coelho <luis@luispedro.org> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # License: MIT. See COPYING.MIT file in the milk distribution from __future__ import division from .classifier import normaliselabels, ctransforms_model from .base import superv...
class svm_raw_model(supervised_model): def __init__(self, svs, Yw, b, kernel): self.svs = svs self.Yw = Yw self.b = b self.kernel = kernel try: self.kernelfunction = self.kernel.preprocess(self.svs) except AttributeError: self.kernelfunction ...
return preprocessed_dot_kernel(svs)
identifier_body
svm.py
# -*- coding: utf-8 -*- # Copyright (C) 2008-2015, Luis Pedro Coelho <luis@luispedro.org> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # License: MIT. See COPYING.MIT file in the milk distribution from __future__ import division from .classifier import normaliselabels, ctransforms_model from .base import superv...
elif alphas.dtype != np.double or len(alphas) != n: raise ValueError('milk.supervised.svm_learn_libsvm: alphas is in wrong format') _svm.eval_LIBSVM(features, labels, alphas, p, params, kernel, cache_size) return alphas, params[0] class preprocessed_rbf_kernel(object): def __init__(self, X, s...
alphas = np.zeros(n, np.double)
conditional_block
svm.py
# -*- coding: utf-8 -*- # Copyright (C) 2008-2015, Luis Pedro Coelho <luis@luispedro.org> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # License: MIT. See COPYING.MIT file in the milk distribution from __future__ import division from .classifier import normaliselabels, ctransforms_model from .base import superv...
def sigma_value_fisher(features,labels): ''' f = sigma_value_fisher(features,labels) value_s = f(s) Computes a function which computes how good the value of sigma is for the features. This function should be *minimised* for a good value of sigma. Parameters ----------- features : ...
def set_params(self,params): self.max_iters = params
random_line_split
svm.py
# -*- coding: utf-8 -*- # Copyright (C) 2008-2015, Luis Pedro Coelho <luis@luispedro.org> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # License: MIT. See COPYING.MIT file in the milk distribution from __future__ import division from .classifier import normaliselabels, ctransforms_model from .base import superv...
(self,params): self.C,self.eps,self.tol = params def set_option(self, optname, value): setattr(self, optname, value) def learn_sigmoid_constants(F,Y, max_iters=None, min_step=1e-10, sigma=1e-12, eps=1e-5): ''' A,B = learn_sigmoid_constants(...
set_params
identifier_name
iframe-video.js
/** * Copyright 2018 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...
*/ export function mutedOrUnmutedEvent(isMuted) { return isMuted ? VideoEvents.MUTED : VideoEvents.UNMUTED; } /** * TEMPORARY workaround for M72-M74 user-activation breakage. * If this method is still here in May 2019, please ping @aghassemi * Only used by trusted video players: IMA and YouTube. * See https://g...
/** * @param {boolean} isMuted * @return {string}
random_line_split
iframe-video.js
/** * Copyright 2018 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...
{ let val = iframe.getAttribute('allow') || ''; val += 'autoplay;'; iframe.setAttribute('allow', val); }
identifier_body
iframe-video.js
/** * Copyright 2018 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...
(objOrStr) { if (isObject(objOrStr)) { return /** @type {!JsonObject} */ (objOrStr); } return tryParseJson(objOrStr); } /** * @param {boolean} isMuted * @return {string} */ export function mutedOrUnmutedEvent(isMuted) { return isMuted ? VideoEvents.MUTED : VideoEvents.UNMUTED; } /** * TEMPORARY workar...
objOrParseJson
identifier_name
iframe-video.js
/** * Copyright 2018 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...
const dispatchEvent = events[event]; (isArray(dispatchEvent) ? dispatchEvent : [dispatchEvent]).forEach(e => { element.dispatchCustomEvent(dev().assertString(e)); }); return true; } /** * @param {!./base-element.BaseElement} video * @param {string} src * @param {string=} opt_name * @param {!Array<!San...
{ return false; }
conditional_block
BlockView.js
var BlockView = Backbone.View.extend({ tagName : 'div', initialize : function() { this.render(); }, render: function() { this.$el.attr({ class : 'block gimmick-' + this.model.get('gimmick'), 'data-gimmick' : this.model.get('gimmick') }); }, collide: function() { if (this.model.get('isDead')) ...
this.$el.remove(); this.remove(); } });
random_line_split
policies.py
import sys, os, fabric class PiServicePolicies: @staticmethod def is_local(): return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1']) @staticmethod def is_pi(): return os.path.isdir('/home/pi') @staticmethod def
(): if not PiServicePolicies.is_local(): print "...only callable on localhost!!!" sys.exit(-1) @staticmethod def check_remote_or_exit(): if PiServicePolicies.is_local(): print "...only callable on remote host!!!" sys.exit(-1) def check_installed_or_exit(self): if not PiServic...
check_local_or_exit
identifier_name
policies.py
import sys, os, fabric class PiServicePolicies: @staticmethod def is_local(): return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1']) @staticmethod def is_pi(): return os.path.isdir('/home/pi') @staticmethod def check_local_or_exit(): if not PiService...
def check_installed_or_exit(self): if not PiServicePolicies.installed(self): print "...first you have to install this service! fab pi %s:install" sys.exit(-1) def installed(self): ret = self.file_exists('__init__.py') if not ret: print self.name+' not installed' return ret
if PiServicePolicies.is_local(): print "...only callable on remote host!!!" sys.exit(-1)
identifier_body
policies.py
import sys, os, fabric class PiServicePolicies: @staticmethod def is_local(): return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1']) @staticmethod def is_pi(): return os.path.isdir('/home/pi') @staticmethod def check_local_or_exit(): if not PiService...
if not ret: print self.name+' not installed' return ret
random_line_split
policies.py
import sys, os, fabric class PiServicePolicies: @staticmethod def is_local(): return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1']) @staticmethod def is_pi(): return os.path.isdir('/home/pi') @staticmethod def check_local_or_exit(): if not PiService...
return ret
print self.name+' not installed'
conditional_block
acl-confirmation.component.ts
import { Component, OnInit } from '@angular/core'; import { ApiStatusCodes } from 'moh-common-lib'; import { ActivatedRoute } from '@angular/router'; import { environment } from '../../../../../environments/environment'; import { Subscription } from 'rxjs'; import * as moment from 'moment'; import { format } from 'date...
}
random_line_split
acl-confirmation.component.ts
import { Component, OnInit } from '@angular/core'; import { ApiStatusCodes } from 'moh-common-lib'; import { ActivatedRoute } from '@angular/router'; import { environment } from '../../../../../environments/environment'; import { Subscription } from 'rxjs'; import * as moment from 'moment'; import { format } from 'date...
(): string { return format(new Date(), 'MMMM dd, yyyy'); } }
dateStamp
identifier_name
acl-confirmation.component.ts
import { Component, OnInit } from '@angular/core'; import { ApiStatusCodes } from 'moh-common-lib'; import { ActivatedRoute } from '@angular/router'; import { environment } from '../../../../../environments/environment'; import { Subscription } from 'rxjs'; import * as moment from 'moment'; import { format } from 'date...
} ); } ngOnDestroy() { this._subscription.unsubscribe(); } get isSucess() { return this.status === ApiStatusCodes.SUCCESS; } /** * Today's date * @returns {string} */ get dateStamp(): string { return format(new Date(), 'MMMM dd, yyyy'); } }
{ this.message = params['message']; this.message = this.message.replace('HIBC', '<a href=\"' + this.links.HIBC + '\" target=\"blank\">Health Insurance BC</a>'); this.message = this.message.replace('ACBC', ...
conditional_block
opeq.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 mut x: int = 1; x *= 2; debug!(x); assert_eq!(x, 2); x += 3; debug!(x); assert_eq!(x, 5); x *= x; debug!(x); assert_eq!(x, 25); x /= 5; debug!(x); assert_eq!(x, 5); }
identifier_body
opeq.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 mut x: int = 1; x *= 2; debug!(x); assert_eq!(x, 2); x += 3; debug!(x); assert_eq!(x, 5); x *= x; debug!(x); assert_eq!(x, 25); x /= 5; debug!(x); assert_eq!(x, 5); }
main
identifier_name
opeq.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 ...
}
x /= 5; debug!(x); assert_eq!(x, 5);
random_line_split
app.py
from cStringIO import StringIO from datetime import datetime from functools import partial from itertools import chain, imap, izip from logging import StreamHandler import os from os import chdir from os.path import join, basename, split, dirname, relpath from sys import stderr from time import time from mimetypes impo...
(tree, path, config): """Return a rendered folder listing for folder ``path``. Search for FILEs having folder == path. If any matches, render the folder listing. Otherwise, raise NotFound. """ frozen = frozen_config(tree) files_and_folders = filtered_query( frozen['es_alias'], ...
_browse_folder
identifier_name
app.py
from cStringIO import StringIO from datetime import datetime from functools import partial from itertools import chain, imap, izip from logging import StreamHandler import os from os import chdir from os.path import join, basename, split, dirname, relpath from sys import stderr from time import time from mimetypes impo...
return _browse_file(tree, path, lines, files[0], config, frozen['generated_date']) def _browse_folder(tree, path, config): """Return a rendered folder listing for folder ``path``. Search for FILEs having folder == path. If any matches, render the folder listing. Otherwise, raise NotFound. ...
doc['content'] = doc['content'][0]
conditional_block
app.py
from cStringIO import StringIO from datetime import datetime from functools import partial from itertools import chain, imap, izip from logging import StreamHandler import os from os import chdir from os.path import join, basename, split, dirname, relpath from sys import stderr from time import time from mimetypes impo...
:arg list line_docs: LINE documents as defined in the mapping of core.py, where the `content` field is dereferenced :arg file_doc: the FILE document as defined in core.py :arg config: TreeConfig object of this tree :arg date: a formatted string representing the generated date, default to now ...
:arg string tree: name of tree on which file is found :arg string path: relative path from tree root of file
random_line_split
app.py
from cStringIO import StringIO from datetime import datetime from functools import partial from itertools import chain, imap, izip from logging import StreamHandler import os from os import chdir from os.path import join, basename, split, dirname, relpath from sys import stderr from time import time from mimetypes impo...
def _icon_class_name(file_doc): """Return a string for the CSS class of the icon for file document.""" if file_doc['is_folder']: return 'folder' class_name = icon(file_doc['name']) # for small images, we can turn the image into icon via javascript # if bigger than the cutoff, we mark it a...
"""If a file or dir parallel to the given path exists in the given tree, redirect to it. Otherwise, redirect to the root of the given tree. Deferring this test lets us avoid doing 50 queries when drawing the Switch Tree menu when 50 trees are indexed: we check only when somebody actually chooses someth...
identifier_body
item_lock.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from ..mode...
def __init__(self, app): self.app = app self.app.on_session_end += self.on_session_end @classmethod def name(cls): return 'item_lock' def lock(self, item_filter, user_id, session_id, etag): item_model = get_model(ItemModel) item = item_model.find_one(item_filter) ...
identifier_body
item_lock.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from ..mode...
(self, app): self.app = app self.app.on_session_end += self.on_session_end @classmethod def name(cls): return 'item_lock' def lock(self, item_filter, user_id, session_id, etag): item_model = get_model(ItemModel) item = item_model.find_one(item_filter) if no...
__init__
identifier_name
item_lock.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license
from superdesk.utc import utcnow from superdesk.notification import push_notification from apps.common.components.base_component import BaseComponent from apps.common.models.utils import get_model from superdesk.users.services import current_user_has_privilege import superdesk LOCK_USER = 'lock_user' LOCK_SESSION = 'l...
from ..models.item import ItemModel from eve.utils import config from superdesk.errors import SuperdeskApiError
random_line_split
item_lock.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from ..mode...
else: if str(item.get(LOCK_USER, '')) != str(user_id): return False, 'Item is locked by another user.' else: return False, error_message return True, '' def can_unlock(self, item, user_id): """ Function checks...
return False, 'Item is locked by you in another session.'
conditional_block
Config.ts
module TSXKP { export module Configs { export enum SeparatorCharacterType { None = 0, Random = 1, Specific = 2 } export enum PaddingType { None = 0, Fixed = 1, Adaptive ...
return numbers; } export interface CharacterSubstitutions { [key: string]: string; } export interface IConfig { symbol_alphabet: string[]; separator_alphabet: string[]; word_length_min: number; word_length_max: n...
{ numbers.push(Math.random()); }
conditional_block
Config.ts
module TSXKP { export module Configs { export enum SeparatorCharacterType { None = 0, Random = 1, Specific = 2 } export enum PaddingType { None = 0, Fixed = 1, Adaptive ...
return numbers; } export interface CharacterSubstitutions { [key: string]: string; } export interface IConfig { symbol_alphabet: string[]; separator_alphabet: string[]; word_length_min: number; word_length_max: num...
for (i = 0; i < count; ++i) { numbers.push(Math.random()); }
random_line_split
utils.py
import libnacl.secret import libnacl.utils from StringIO import StringIO from .response import FileObjResponse from pyramid.httpexceptions import HTTPBadRequest def generate_secret_key(): return libnacl.utils.salsa_key().encode('hex') def encrypt_file(key, fileobj, nonce=None): if nonce is None: non...
(key, fileobj): box = libnacl.secret.SecretBox(key.decode('hex')) decrypted = box.decrypt(fileobj.read()) return StringIO(decrypted) def validate_key(view_callable): def inner(context, request): key = request.params.get('key') if key is None: raise HTTPBadRequest('Key misse...
decrypt_file
identifier_name
utils.py
import libnacl.secret import libnacl.utils from StringIO import StringIO from .response import FileObjResponse from pyramid.httpexceptions import HTTPBadRequest def generate_secret_key(): return libnacl.utils.salsa_key().encode('hex') def encrypt_file(key, fileobj, nonce=None):
def decrypt_file(key, fileobj): box = libnacl.secret.SecretBox(key.decode('hex')) decrypted = box.decrypt(fileobj.read()) return StringIO(decrypted) def validate_key(view_callable): def inner(context, request): key = request.params.get('key') if key is None: raise HTTPBa...
if nonce is None: nonce = libnacl.utils.rand_nonce() box = libnacl.secret.SecretBox(key.decode('hex')) encrypted = box.encrypt(fileobj.read(), nonce) return StringIO(encrypted)
identifier_body
utils.py
import libnacl.secret import libnacl.utils from StringIO import StringIO from .response import FileObjResponse from pyramid.httpexceptions import HTTPBadRequest def generate_secret_key(): return libnacl.utils.salsa_key().encode('hex')
if nonce is None: nonce = libnacl.utils.rand_nonce() box = libnacl.secret.SecretBox(key.decode('hex')) encrypted = box.encrypt(fileobj.read(), nonce) return StringIO(encrypted) def decrypt_file(key, fileobj): box = libnacl.secret.SecretBox(key.decode('hex')) decrypted = box.decrypt(fil...
def encrypt_file(key, fileobj, nonce=None):
random_line_split
utils.py
import libnacl.secret import libnacl.utils from StringIO import StringIO from .response import FileObjResponse from pyramid.httpexceptions import HTTPBadRequest def generate_secret_key(): return libnacl.utils.salsa_key().encode('hex') def encrypt_file(key, fileobj, nonce=None): if nonce is None: non...
if len(key) != 64: raise HTTPBadRequest('The key must be exactly 32 bytes long.') try: key.decode('hex') except TypeError: raise HTTPBadRequest('Invalid key: Non-hexadecimal digit found.') return view_callable(context, request) return inner
raise HTTPBadRequest('Key missed.')
conditional_block
resource.js
import React from 'react'; import { Component, PropTypes } from 'react'; import Link from 'react-router/lib/Link' // Utils import { getAvg } from '@/utils'; // Boostrap import { Tooltip, OverlayTrigger } from 'react-bootstrap'; // Components import Rating from '@/components/common/rating'; import SvgComponent from '...
lse { return ( <span className="list__element--buttons"> <ProtectedButton className="cta primary outline no-border action-btn" target={"/descobrir/detalhes-recurso/" + el.slug}>Ver Recurso</ProtectedButton> </span> ) } } // // Render favorite and highlight button // const renderAuthOptions = (el, isAuth...
return ( <span className="list__element--buttons"> <Link to={"/descobrir/detalhes-recurso/" + el.slug} className="cta primary outline no-border">Ver Recurso</Link> </span> ) }e
conditional_block
resource.js
import React from 'react'; import { Component, PropTypes } from 'react'; import Link from 'react-router/lib/Link' // Utils import { getAvg } from '@/utils'; // Boostrap import { Tooltip, OverlayTrigger } from 'react-bootstrap'; // Components import Rating from '@/components/common/rating'; import SvgComponent from '...
) } return( <ProtectedButton target={target}> {obj} </ProtectedButton> ); } // // Render option buttons // const optionsRender = (el, isAuthenticated, addscript, viewmore) => { if (addscript && isAuthenticated){ return ( <span className="list__element--buttons"> <Link to={...
<Link to={target}> {obj} </Link>
random_line_split
setup.py
import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand):
requires = [ 'blessings >= 1.6, < 2.0', 'sqlalchemy >= 1.3, < 2.0', 'PyYAML >= 5.1, < 6.0', 'python-dateutil >= 2.8, <3.0', 'click >= 6.7, <7.0', 'czech-holidays', 'python-slugify', ] tests_require = ['pytest'] if sys.version_info < (3, 4): # pathlib is in the stdlib since Python 3....
def finalize_options(self): super().finalize_options() self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno)
identifier_body
setup.py
import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def
(self): super().finalize_options() self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) requires = [ 'blessings >= 1.6, < 2.0', 'sqlalchemy >= 1.3, < 2.0', 'PyYAML >= 5.1, < 6....
finalize_options
identifier_name
setup.py
import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): super().finalize_options() self.test_args = [] self.test_suite = True def run_tests(self): import pytest ...
setup_args = dict( name='pyvodb', version='1.0', packages=find_packages(), url='https://github.com/pyvec/pyvodb', description="""Database of Pyvo meetups""", author='Petr Viktorin', author_email='encukou@gmail.com', classifiers=[ 'Intended Audience :: Developers', 'Lic...
requires.append('pathlib >= 1.0.1, < 2.0')
conditional_block
setup.py
import sys
class PyTest(TestCommand): def finalize_options(self): super().finalize_options() self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) requires = [ 'blessings >= 1.6, < 2.0', ...
from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand
random_line_split
cache.py
""" Caching facility for SymPy """ # TODO: refactor CACHE & friends into class? # global cache registry: CACHE = [] # [] of # (item, {} or tuple of {}) from sympy.core.decorators import wraps def print_cache(): """print cache content""" for item, cache in CACHE: item = str(item) ...
def __cacheit(func): """caching decorator. important: the result of cached function must be *immutable* Examples ======== >>> from sympy.core.cache import cacheit >>> @cacheit ... def f(a,b): ... return a+b >>> @cacheit ... def f(a,b): ...
return func
identifier_body
cache.py
""" Caching facility for SymPy """ # TODO: refactor CACHE & friends into class? # global cache registry: CACHE = [] # [] of # (item, {} or tuple of {}) from sympy.core.decorators import wraps def print_cache(): """print cache content""" for item, cache in CACHE: item = str(item) ...
else: k = args k = k + tuple(map(lambda x: type(x), k)) try: return func_cache_it_cache[k] except KeyError: pass func_cache_it_cache[k] = r = func(*args, **kw_args) return r return wrapper def __cacheit_debug(func): """cacheit...
keys = kw_args.keys() keys.sort() items = [(k+'=', kw_args[k]) for k in keys] k = args + tuple(items)
conditional_block