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
test_script.py
# -*- coding: utf-8 -*- # Copyright 2017 Chris Meyers <cmeyers@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (...
(self): self.popen.side_effect = OSError("dummy text") inventory_module = InventoryModule() with pytest.raises(AnsibleError) as e: inventory_module.parse(self.inventory, self.loader, '/foo/bar/foobar.py') assert e.value.message == "problem running /foo/bar/foobar.py --list (...
test_parse_subprocess_path_not_found_fail
identifier_name
angular-desktop-notification-tests.ts
import * as angular from 'angular'; angular .module('app', ['ngDesktopNotification']) .config(['desktopNotificationProvider', (desktopNotificationProvider: angular.desktopNotification.IDesktopNotificationProvider) => { desktopNotificationProvider.config({ autoClose: true, durati...
// Request permission desktopNotification.requestPermission().then( // Permission granted (permission) => { // Show notification desktopNotification.show( "Notification title", { tag...
{ // Permission granted }
conditional_block
angular-desktop-notification-tests.ts
import * as angular from 'angular'; angular .module('app', ['ngDesktopNotification']) .config(['desktopNotificationProvider', (desktopNotificationProvider: angular.desktopNotification.IDesktopNotificationProvider) => { desktopNotificationProvider.config({ autoClose: true, durati...
const currentNotificationPermission = desktopNotification.currentPermission(); if (currentNotificationPermission === desktopNotification.permissions.granted) { // Permission granted } // Request permission desktopNotification.requestPermission().then( //...
// Check support and permission const isNotificationSupported = desktopNotification.isSupported();
random_line_split
ua_handler.js
var fs = require('fs'), path = require('path'); var uaList = fs.readFileSync(path.join(__dirname, 'ua.txt')); uaList = uaList.toString().split('\n'); var OSs = {}; var browsers = {}; var browserVersions = {}; var unknown = []; var osMatch = { ios: /iOS|iPhone OS/i, android: /Android/i, linux: /Linux/i, win: /W...
if (!browsers[os + ' ' + browser]) { browsers[os + ' ' + browser] = 1; } else { browsers[os + ' ' + browser]++; } if (os == 'unknown' || browser == 'unknown') { unknown.push(uaName); } if (!browserVersions[os + ' ' + browser + ' ' + version]) { browserVersions[os + ' ' + browser + ' ' + version] = 1; ...
{ OSs[os]++; }
conditional_block
ua_handler.js
var fs = require('fs'), path = require('path'); var uaList = fs.readFileSync(path.join(__dirname, 'ua.txt')); uaList = uaList.toString().split('\n'); var OSs = {}; var browsers = {}; var browserVersions = {}; var unknown = []; var osMatch = { ios: /iOS|iPhone OS/i, android: /Android/i, linux: /Linux/i, win: /W...
uaName.match( /.+(?:me|ox|on|rv|it|era|opr|ie)[\/: ]([\d.]+)/) || [0,'0'] )[1]; if (!OSs[os]) { OSs[os] = 1; } else { OSs[os]++; } if (!browsers[os + ' ' + browser]) { browsers[os + ' ' + browser] = 1; } else { browsers[os + ' ' + browser]++; } if (os == 'unknown' || browser == 'unknown') { unk...
} var version = ( uaName.match(/MSIE ([\d.]+)/) ||
random_line_split
configureStore.js
/* 用 action 来描述“发生了什么”,和使用 reducers 来根据 action 更新 state 的用法。 Store 就是把它们联系到一起的对象。Store 有以下职责: 维持应用的 state; 提供 getState() 方法获取 state; 提供 dispatch(action) 方法更新 state; 通过 subscribe(listener) 注册监听器; 通过 subscribe(listener) 返回的函数注销监听器。 再次强调一下 Redux 应用只有一个单一的 store。当需要拆分数据处理逻辑时,你应该使用 reducer 组合 而不是创建多个 store */ imp...
b167f3560057bb00a7 persistStore(store, { blacklist: ['signIn', 'someKey'], // 黑名单数组,可以忽略指定 reducers 中的 key // whitelist: ['auth'], // 白名单数组,一旦设置,其他的 key 都会被忽略。 storage: AsyncStorage, // transforms: // 在 rehydration 和 storage 阶段被调用的转换器 debounce: 100 // storage 操作被调用的频度, ms // store: // redux st...
{ store = createStore(rootReducer, initialState, enhancers); hotReloading(); setPersistStore(); return store; } function setPersistStore() { // more information: http://gold.xitu.io/entry/57cac7
conditional_block
configureStore.js
/* 用 action 来描述“发生了什么”,和使用 reducers 来根据 action 更新 state 的用法。 Store 就是把它们联系到一起的对象。Store 有以下职责: 维持应用的 state; 提供 getState() 方法获取 state; 提供 dispatch(action) 方法更新 state; 通过 subscribe(listener) 注册监听器; 通过 subscribe(listener) 返回的函数注销监听器。 再次强调一下 Redux 应用只有一个单一的 store。当需要拆分数据处理逻辑时,你应该使用 reducer 组合 而不是创建多个 store */ imp...
67f3560057bb00a7 persistStore(store, { blacklist: ['signIn', 'someKey'], // 黑名单数组,可以忽略指定 reducers 中的 key // whitelist: ['auth'], // 白名单数组,一旦设置,其他的 key 都会被忽略。 storage: AsyncStorage, // transforms: // 在 rehydration 和 storage 阶段被调用的转换器 debounce: 100 // storage 操作被调用的频度, ms // store: // redux stor...
educer = require(reducerPath).default; store.replaceReducer(nextRootReducer); }); } } export default function configureStore(initialState = {}) { store = createStore(rootReducer, initialState, enhancers); hotReloading(); setPersistStore(); return store; } function setPersistStore() { // more ...
identifier_body
configureStore.js
/* 用 action 来描述“发生了什么”,和使用 reducers 来根据 action 更新 state 的用法。 Store 就是把它们联系到一起的对象。Store 有以下职责: 维持应用的 state; 提供 getState() 方法获取 state; 提供 dispatch(action) 方法更新 state; 通过 subscribe(listener) 注册监听器; 通过 subscribe(listener) 返回的函数注销监听器。 再次强调一下 Redux 应用只有一个单一的 store。当需要拆分数据处理逻辑时,你应该使用 reducer 组合 而不是创建多个 store */ imp...
otReducer = require(reducerPath).default; store.replaceReducer(nextRootReducer); }); } } export default function configureStore(initialState = {}) { store = createStore(rootReducer, initialState, enhancers); hotReloading(); setPersistStore(); return store; } function setPersistStore() { // mo...
let nextRo
identifier_name
configureStore.js
/* 用 action 来描述“发生了什么”,和使用 reducers 来根据 action 更新 state 的用法。 Store 就是把它们联系到一起的对象。Store 有以下职责: 维持应用的 state; 提供 getState() 方法获取 state; 提供 dispatch(action) 方法更新 state; 通过 subscribe(listener) 注册监听器; 通过 subscribe(listener) 返回的函数注销监听器。 再次强调一下 Redux 应用只有一个单一的 store。当需要拆分数据处理逻辑时,你应该使用 reducer 组合 而不是创建多个 store */ imp...
setPersistStore(); return store; } function setPersistStore() { // more information: http://gold.xitu.io/entry/57cac7b167f3560057bb00a7 persistStore(store, { blacklist: ['signIn', 'someKey'], // 黑名单数组,可以忽略指定 reducers 中的 key // whitelist: ['auth'], // 白名单数组,一旦设置,其他的 key 都会被忽略。 storage: AsyncStorage...
random_line_split
q2_rnn_cell.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Q2(c): Recurrent neural nets for NER """ from __future__ import absolute_import from __future__ import division import argparse import logging import sys import tensorflow as tf import numpy as np logger = logging.getLogger("hw3.q2.1") logger.setLevel(logging.DEBUG...
parser = argparse.ArgumentParser(description='Tests the RNN cell implemented as part of Q2 of Homework 3') subparsers = parser.add_subparsers() command_parser = subparsers.add_parser('test', help='') command_parser.set_defaults(func=do_test) ARGS = parser.parse_args() if ARGS.func is None: ...
conditional_block
q2_rnn_cell.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Q2(c): Recurrent neural nets for NER """ from __future__ import absolute_import from __future__ import division import argparse import logging import sys import tensorflow as tf import numpy as np logger = logging.getLogger("hw3.q2.1") logger.setLevel(logging.DEBUG...
(_): logger.info("Testing rnn_cell") test_rnn_cell() logger.info("Passed!") if __name__ == "__main__": parser = argparse.ArgumentParser(description='Tests the RNN cell implemented as part of Q2 of Homework 3') subparsers = parser.add_subparsers() command_parser = subparsers.add_parser('test', ...
do_test
identifier_name
q2_rnn_cell.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Q2(c): Recurrent neural nets for NER """ from __future__ import absolute_import from __future__ import division import argparse import logging import sys import tensorflow as tf import numpy as np logger = logging.getLogger("hw3.q2.1") logger.setLevel(logging.DEBUG...
h = np.array([ [0.2, 0.5], [-0.3, -0.3]], dtype=np.float32) y = np.array([ [0.832, 0.881], [0.731, 0.622]], dtype=np.float32) ht = y y_, ht_ = session.run([y_var, ht_var], fee...
with tf.Graph().as_default(): with tf.variable_scope("test_rnn_cell"): x_placeholder = tf.placeholder(tf.float32, shape=(None,3)) h_placeholder = tf.placeholder(tf.float32, shape=(None,2)) with tf.variable_scope("rnn"): tf.get_variable("W_x", initializer=np.a...
identifier_body
q2_rnn_cell.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Q2(c): Recurrent neural nets for NER """ from __future__ import absolute_import from __future__ import division import argparse import logging import sys import tensorflow as tf import numpy as np logger = logging.getLogger("hw3.q2.1") logger.setLevel(logging.DEBUG...
TODO: In the code below, implement an RNN cell using @inputs (x_t above) and the state (h_{t-1} above). - Define W_x, W_h, b to be variables of the apporiate shape using the `tf.get_variable' functions. Make sure you use the names "W_x", "W_h" and "b"! ...
Remember the RNN equations are: h_t = sigmoid(x_t W_x + h_{t-1} W_h + b)
random_line_split
timer.rs
in writing, software // 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. #![allow(missing_docs)] //! Timer configuratio...
timer.configure(prescale); timer } /// Configure timer registers /// TODO(simias): Only Periodic and OneShot modes are implemented so far pub fn configure(&self, prescale: u32) { // Make sure the timer is disabled before making changes. self.regs.ctl.set_taen(false); // Configure the tim...
let timer = Timer { regs: get_reg_ref(regs), wide: wide, mode: mode};
random_line_split
timer.rs
in writing, software // 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. #![allow(missing_docs)] //! Timer configuratio...
self.regs.tailr.set_tailr(0xffffffff); // Set prescale value if !self.wide && prescale > 0xffff { panic!("prescale is too wide for this timer"); } self.regs.apr.set_psr(prescale as u32); // Timer is now configured, we can enable it self.regs.ctl.set_taen(true); } } impl timer::T...
{ // Make sure the timer is disabled before making changes. self.regs.ctl.set_taen(false); // Configure the timer as half-width so that we can use the prescaler self.regs.cfg.set_cfg(reg::Timer_cfg_cfg::HalfWidth); self.regs.amr .set_mr(match self.mode { Mode::OneShot => reg::Timer...
identifier_body
timer.rs
in writing, software // 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. #![allow(missing_docs)] //! Timer configuratio...
{ Timer0, Timer1, Timer2, Timer3, Timer4, Timer5, TimerW0, TimerW1, TimerW2, TimerW3, TimerW4, TimerW5, } /// Timer modes #[derive(Clone, Copy)] pub enum Mode { /// Periodic timer loops and restarts once the timeout is reached. Periodic, /// One shot timer is disabled once the timeout is...
TimerId
identifier_name
init.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly.
## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## - Redistributions of source code must retain the above copyright...
## Copyright (C) 2006-2011, University of Utah.
random_line_split
init.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
def importWidgetModules(basicWidgets): """ importWidgetModules(basicWidgets: widget) -> None Find all widget package under ./widgets/* to add to the spreadsheet registry """ packageName = __name__.lower().endswith('.init') and \ __name__[:-5] or __name__ widgetDir = os.path.join( ...
""" addWidget(packagePath: str) -> package Add a new widget type to the spreadsheet registry supplying a basic set of spreadsheet widgets """ try: registry = get_module_registry() widget = importReturnLast(packagePath) if hasattr(widget, 'widgetName'): widgetName = w...
identifier_body
init.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
def initialize(*args, **keywords): """ initialize() -> None Package-entry to initialize the package """ import vistrails.core.application if not vistrails.core.application.is_running_gui(): raise RuntimeError, "GUI is not running. The Spreadsheet package requires the GUI" # initiali...
if os.path.isdir(os.path.join(widgetDir, folder)) and folder != '.svn': addWidget('.'.join([packageName, 'widgets', folder]))
conditional_block
init.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
(*args, **keywords): """ initialize() -> None Package-entry to initialize the package """ import vistrails.core.application if not vistrails.core.application.is_running_gui(): raise RuntimeError, "GUI is not running. The Spreadsheet package requires the GUI" # initialize widgets de...
initialize
identifier_name
migrationlib.py
import sys, os sys.path.append(os.sep.join(("..","..","..","src"))) from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import traceback import MySQLdb as dbi import weblab.db.model as Model ######################################################## # # Abstract class. All classes implementi...
for klass in Patch.__subclasses__(): if not klass.ABSTRACT and not klass in self.order: print "WARNING: Class %s not found in provided order: " % klass.__name__, if force: print "[skipped]" else: print "[aborted]...
self.dbs = dbs self.order = order def execute(self, force = False):
random_line_split
migrationlib.py
import sys, os sys.path.append(os.sep.join(("..","..","..","src"))) from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import traceback import MySQLdb as dbi import weblab.db.model as Model ######################################################## # # Abstract class. All classes implementi...
(self, user, password, db): self.user = user self.db = db self.password = password def execute(self): connection_url = "mysql://%(USER)s:%(PASS)s@%(HOST)s/%(NAME)s" % { "USER": self.user, "PASS": self.password,...
__init__
identifier_name
migrationlib.py
import sys, os sys.path.append(os.sep.join(("..","..","..","src"))) from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import traceback import MySQLdb as dbi import weblab.db.model as Model ######################################################## # # Abstract class. All classes implementi...
applicable = self.check(check_arg) except: print "[ERROR CHECKING]" print traceback.print_exc() print applicable = False if applicable:...
connection_url = "mysql://%(USER)s:%(PASS)s@%(HOST)s/%(NAME)s" % { "USER": self.user, "PASS": self.password, "HOST": "localhost", "NAME": self.db } self.engine = create_engine(connecti...
identifier_body
migrationlib.py
import sys, os sys.path.append(os.sep.join(("..","..","..","src"))) from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import traceback import MySQLdb as dbi import weblab.db.model as Model ######################################################## # # Abstract class. All classes implementi...
else: check_arg = session try: applicable = self.check(check_arg) except: print "[ERROR CHECKING]" print traceback.pri...
check_arg = cursor
conditional_block
table34.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; wi...
*/ function table34() { var success; if(checkInitialization(builder, "table34") != null) return; var nodeList; var testNode; var vborder; var doc; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } doc = load(docRef, "doc", "table...
* @author Netscape * @author Sivakiran Tummala * @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-50969400
random_line_split
table34.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; wi...
setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allows the // body of the test to be executed. function load...
setUpPageStatus = 'running'; try { // // creates test document builder, may throw exception // builder = createConfiguredBuilder(); docsLoaded = 0; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } docsLoaded += preload(docRe...
identifier_body
table34.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; wi...
if (++docsLoaded == 1) { setUpPageStatus = 'complete'; } } /** * The width of the border around the table. The value of attribute border of the table element is read and checked against the expected value. * @author Netscape * @author Sivakiran Tummala * @see http://www.w3.org/TR/1998/REC-DOM-Level-1...
Complete() {
identifier_name
table34.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; wi...
} catch(ex) { catchInitializationError(builder, ex); setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allo...
setUpPageStatus = 'complete'; }
conditional_block
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
} impl Drop for HeadlessContext { fn drop(&mut self) { unsafe { ffi::OSMesaDestroyContext(self.context) } } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {}
{ }
identifier_body
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
ctxt } }) } pub unsafe fn make_current(&self) { let ret = ffi::OSMesaMakeCurrent(self.context, self.buffer.as_ptr() as *mut libc::c_void, 0x1401, self.width as libc::c_int, self.height as libc::c_int); if ret == 0 { panic...
{ return Err(OsError("OSMesaCreateContext failed".to_string())); }
conditional_block
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { let dimensions = builder.dimensions.unwrap(); Ok(HeadlessContext { width: dimensions.0, height: dimensions.1, buffer: ::std::iter::repeat(unsafe { mem::uninitialized() }) ...
impl HeadlessContext {
random_line_split
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
(&mut self) { unsafe { ffi::OSMesaDestroyContext(self.context) } } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {}
drop
identifier_name
DataGridScope.ts
/* * Copyright 2017 TWO SIGMA OPEN SOURCE, 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appl...
{ contextMenu: DataGridContextMenu; readonly dataGrid: BeakerXDataGrid; readonly element: HTMLElement; readonly store: BeakerXDataStore; private tableDisplayModel: any; private tableDisplayView: any; constructor(options: IDataGridScopeOptions) { this.store = createStore(options.data); this.elem...
DataGridScope
identifier_name
DataGridScope.ts
/* * Copyright 2017 TWO SIGMA OPEN SOURCE, 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appl...
return new ColumnLimitModal(this.dataGrid, this.element); } }
createContextMenu() { this.contextMenu = new DataGridContextMenu(this); } initColumnLimitModal() {
random_line_split
lang.js
/** * Created by Flynn Buckingham (https://github.com/flynnham) on 17/05/17. */ var Promise = require('es6-promise/auto'); import { fetchJSONFile, STORAGE_LANG } from '../global' import './flags.css'; // flags layout import '../logo/logo.css'; // logo layout import './layout.css'; // layout import languageMappings...
(targetLang){ document.body.classList.add('fetching'); fetchJSONFile(`lang/${targetLang}.json`, function (languageData) { // compile the string and fetch via vanilla AJAX require.ensure([], (require) => { // webpack smart-require document.body.classList.remove('fetching'); let...
loader
identifier_name
lang.js
/** * Created by Flynn Buckingham (https://github.com/flynnham) on 17/05/17. */ var Promise = require('es6-promise/auto'); import { fetchJSONFile, STORAGE_LANG } from '../global' import './flags.css'; // flags layout import '../logo/logo.css'; // logo layout import './layout.css'; // layout import languageMappings...
// ToDO: detect is animations are set document.body.classList.add('loader'); const createLanguageList = () => Object.keys(languageMappings).map( langName => `<li data-name="${ langName }" data-lang-src="${ languageMappings[langName] }"></li>` ).join(''); /* init loader app environment */ document.body.innerHTML...
{ let langName = localStorage.getItem(STORAGE_LANG); langName && loader(langName); }
conditional_block
lang.js
/** * Created by Flynn Buckingham (https://github.com/flynnham) on 17/05/17. */ var Promise = require('es6-promise/auto'); import { fetchJSONFile, STORAGE_LANG } from '../global' import './flags.css'; // flags layout import '../logo/logo.css'; // logo layout import './layout.css'; // layout import languageMappings...
{ document.body.classList.add('fetching'); fetchJSONFile(`lang/${targetLang}.json`, function (languageData) { // compile the string and fetch via vanilla AJAX require.ensure([], (require) => { // webpack smart-require document.body.classList.remove('fetching'); let main = requ...
identifier_body
lang.js
/** * Created by Flynn Buckingham (https://github.com/flynnham) on 17/05/17. */ var Promise = require('es6-promise/auto'); import { fetchJSONFile, STORAGE_LANG } from '../global' import './flags.css'; // flags layout import '../logo/logo.css'; // logo layout import './layout.css'; // layout import languageMappings...
langName => `<li data-name="${ langName }" data-lang-src="${ languageMappings[langName] }"></li>` ).join(''); /* init loader app environment */ document.body.innerHTML = `<div id="app"> <div id="loader-left"> <div class="sw-logo"><div></div><div></div><div></div></div> <h1 id="loader-lang-name"...
random_line_split
main.rs
// Copyright 2013-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-MI...
{ unsafe { let path = Path::new("libdylib.so"); let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4")....
identifier_body
main.rs
// Copyright 2013-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-MI...
let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4").is_ok()); assert!(a.symbol::<isize>("fun5").is_ok())...
use std::path::Path; pub fn main() { unsafe { let path = Path::new("libdylib.so");
random_line_split
main.rs
// Copyright 2013-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-MI...
() { unsafe { let path = Path::new("libdylib.so"); let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4...
main
identifier_name
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn
() { // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap(); // Enable detail mode. This is needed if you want to get instruction details. dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs...
main
identifier_name
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn main() { // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X...
if details.regs_write.len() != 0 { print!(" Implicit registers written:"); for write in details.regs_write.iter() { print!(" {}", dec.reg_name(*write).unwrap()); } print!("\n"); } } }
{ print!(" Implicit registers read:"); for read in details.regs_read.iter() { // `read` is an int that correspond to an arch-specific register. In order to // get its human readable name use `reg_name`. print!(" {}", dec.reg_name(*read).unwrap());...
conditional_block
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn main()
print!(" {}", dec.reg_name(*read).unwrap()); } print!("\n"); } if details.regs_write.len() != 0 { print!(" Implicit registers written:"); for write in details.regs_write.iter() { print!(" {}", dec.reg_name(*write).unwrap()...
{ // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap(); // Enable detail mode. This is needed if you want to get instruction details. dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs_op...
identifier_body
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn main() { // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X...
} }
random_line_split
dart.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 Canonical # # Authors: # Didier Roche # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; version 3. # # This program is distributed in the hope that ...
return ((url, None), in_download) def post_install(self): """Add flutter necessary env variables""" add_env_to_user(self.name, {"PATH": {"value": os.path.join(self.install_path, "bin")}}) UI.delayed_display(DisplayMessage(self.RELOGIN_REQUIRE_MSG.format(self.name)))
with suppress(AttributeError): url = "https://storage.googleapis.com/flutter_infra/releases/stable/linux/" +\ "flutter_linux_v{}-stable.tar.xz".format(p.group(1))
conditional_block
dart.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 Canonical # # Authors: # Didier Roche # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; version 3. # # This program is distributed in the hope that ...
def post_install(self): """Add flutter necessary env variables""" add_env_to_user(self.name, {"PATH": {"value": os.path.join(self.install_path, "bin")}}) UI.delayed_display(DisplayMessage(self.RELOGIN_REQUIRE_MSG.format(self.name)))
"""Parse Flutter SDK download links""" url = None in_download = False if 'Flutter ' in line: p = re.search(r"Flutter\s(\S+)", line) if p is not None: in_download = True if in_download: with suppress(AttributeError): url ...
identifier_body
dart.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 Canonical # # Authors: # Didier Roche # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; version 3. # # This program is distributed in the hope that ...
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Dartlang module""" ...
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
random_line_split
dart.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 Canonical # # Authors: # Didier Roche # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; version 3. # # This program is distributed in the hope that ...
(self, **kwargs): super().__init__(name="Dart SDK", description=_("Dart SDK (default)"), is_category_default=True, only_on_archs=_supported_archs, download_page="https://raw.githubusercontent.com/dart-lang/sdk/master/CHANGELOG.md", dir_t...
__init__
identifier_name
surface.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
#[cfg(target_os="linux")] pub use platform::linux::surface::NativeCompositingGraphicsContext; #[cfg(target_os="linux")] pub use platform::linux::surface::NativeGraphicsMetadata; #[cfg(target_os="linux")] pub use platform::linux::surface::NativeGraphicsMetadataDescriptor; #[cfg(target_os="linux")] pub use platform::linu...
random_line_split
print-pdf.js
/** * phantomjs script for printing presentations to PDF. * * Example: * phantomjs print-pdf.js "http://lab.hakim.se/reveal-js?print-pdf" reveal-demo.pdf * * By Manuel Bieh (https://github.com/manuelbieh) */ // html2pdf.js var page = new WebPage(); var system = require( 'system' ); var slideWidth = system.args...
console.log( 'Printing PDF (Paper size: '+ page.paperSize.width + 'x' + page.paperSize.height +')' ); page.open( inputFile, function( status ) { window.setTimeout( function() { console.log( 'Printed succesfully' ); page.render( outputFile ); phantom.exit(); }, 1000 ); } );
{ outputFile += '.pdf'; }
conditional_block
print-pdf.js
/** * phantomjs script for printing presentations to PDF. * * Example: * phantomjs print-pdf.js "http://lab.hakim.se/reveal-js?print-pdf" reveal-demo.pdf * * By Manuel Bieh (https://github.com/manuelbieh) */ // html2pdf.js var page = new WebPage(); var system = require( 'system' ); var slideWidth = system.args...
page.render( outputFile ); phantom.exit(); }, 1000 ); } );
window.setTimeout( function() { console.log( 'Printed succesfully' );
random_line_split
encoding.py
# coding: utf-8 """ Utilities for dealing with text encodings """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2012 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part...
(stream, default=None): """Return the given stream's encoding or a default. There are cases where ``sys.std*`` might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. ``default`` is None if not provid...
get_stream_enc
identifier_name
encoding.py
# coding: utf-8 """ Utilities for dealing with text encodings """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2012 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part...
else: return stream.encoding # Less conservative replacement for sys.getdefaultencoding, that will try # to match the environment. # Defined here as central function, so if we find better choices, we # won't need to make changes all over IPython. def getdefaultencoding(prefer_stream=True): """Return...
return default
conditional_block
encoding.py
# coding: utf-8 """ Utilities for dealing with text encodings """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2012 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part...
enc = locale.getpreferredencoding() except Exception: pass enc = enc or sys.getdefaultencoding() # On windows `cp0` can be returned to indicate that there is no code page. # Since cp0 is an invalid encoding return instead cp1252 which is the # Western European default. ...
# in some cases, which may well be fixed, but let's be conservative # here.
random_line_split
encoding.py
# coding: utf-8 """ Utilities for dealing with text encodings """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2012 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part...
pass enc = enc or sys.getdefaultencoding() # On windows `cp0` can be returned to indicate that there is no code page. # Since cp0 is an invalid encoding return instead cp1252 which is the # Western European default. if enc == 'cp0': warnings.warn( "Invalid code page c...
"""Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default ...
identifier_body
synology.py
.main import DownloaderBase from couchpotato.core.helpers.encoding import isInt from couchpotato.core.helpers.variable import cleanHost from couchpotato.core.logger import CPLog import requests log = CPLog(__name__) autoload = 'Synology' class Synology(DownloaderBase): protocol = ['nzb', 'torrent', 'torrent_m...
def _req(self, url, args, files = None): response = {'success': False} try: req = requests.post(url, data = args, files = files, verify = False) req.raise_for_status() response = json.loads(req.text) if response['success']: log.info('...
args = {'api':'SYNO.API.Auth', 'version':1, 'method':'logout', 'session':self.session_name, '_sid':self.sid} return self._req(self.auth_url, args)
identifier_body
synology.py
.main import DownloaderBase from couchpotato.core.helpers.encoding import isInt from couchpotato.core.helpers.variable import cleanHost from couchpotato.core.logger import CPLog import requests log = CPLog(__name__) autoload = 'Synology' class Synology(DownloaderBase): protocol = ['nzb', 'torrent', 'torrent_m...
(self, manual = False, data = None): if not data: data = {} for_protocol = ['both'] if data and 'torrent' in data.get('protocol'): for_protocol.append('torrent') elif data: for_protocol.append(data.get('protocol')) return super(Synology, self).isEnabled(...
isEnabled
identifier_name
synology.py
.main import DownloaderBase from couchpotato.core.helpers.encoding import isInt from couchpotato.core.helpers.variable import cleanHost from couchpotato.core.logger import CPLog import requests log = CPLog(__name__) autoload = 'Synology' class Synology(DownloaderBase): protocol = ['nzb', 'torrent', 'torrent_m...
'default': 0, 'type': 'bool', '
'values': [('usenet & torrents', 'both'), ('usenet', 'nzb'), ('torrent', 'torrent')], }, { 'name': 'manual',
random_line_split
synology.py
.main import DownloaderBase from couchpotato.core.helpers.encoding import isInt from couchpotato.core.helpers.variable import cleanHost from couchpotato.core.logger import CPLog import requests log = CPLog(__name__) autoload = 'Synology' class Synology(DownloaderBase): protocol = ['nzb', 'torrent', 'torrent_m...
elif data['protocol'] in ['nzb', 'torrent']: log.info('Adding %s' % data['protocol']) if not filedata: log.error('No %s data found', data['protocol']) else: filename = data['name'] + '.' + data['protocol'] ...
log.info('Adding torrent URL %s', data['url']) response = srpc.create_task(url = data['url'])
conditional_block
website.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2015 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com) # Pedro M. Baeza <pedro.baeza@serviciosbaeza.com> # # This program is free software: you can redistribute it a...
(self, force_create=False, code=None, update_pricelist=None): res = super(Website, self).sale_get_order( force_create=force_create, code=code, update_pricelist=update_pricelist) return res if res is not None else self.env['sale.order']
sale_get_order
identifier_name
website.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2015 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com) # Pedro M. Baeza <pedro.baeza@serviciosbaeza.com> # # This program is free software: you can redistribute it a...
_inherit = 'website' @api.multi def sale_get_order(self, force_create=False, code=None, update_pricelist=None): res = super(Website, self).sale_get_order( force_create=force_create, code=code, update_pricelist=update_pricelist) return res if res is...
identifier_body
website.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2015 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com) # Pedro M. Baeza <pedro.baeza@serviciosbaeza.com> # # This program is free software: you can redistribute it a...
return res if res is not None else self.env['sale.order']
force_create=force_create, code=code, update_pricelist=update_pricelist)
random_line_split
Pop3Reception.tsx
import * as React from 'react' import { classes } from '@framework/Globals' import { FormGroup, FormControlReadonly, ValueLine, ValueLineType, EntityLine, EntityCombo, EntityList, EntityRepeater, EntityTabRepeater, EntityDetail} from '@framework/Lines' import { SearchControl, ValueSearchControlLine } from '@framew...
}
); }
random_line_split
api.py
import releng_tooltool.aws import releng_tooltool.utils logger = cli_common.log.get_logger(__name__) def _get_region_and_bucket(region, regions): if region and region in regions: return region, regions[region] # no region specified, so return one at random return random.choice(regions.items()) ...
def search_files(q): session = flask.g.db.session query = session.query(releng_tooltool.models.File).join(releng_tooltool.models.BatchFile) query = query.filter(sa.or_(releng_tooltool.models.BatchFile.filename.contains(q), releng_tooltool.models.File.sha512.startswith(q)))...
if not releng_tooltool.utils.is_valid_sha512(digest): raise werkzeug.exceptions.BadRequest('Invalid sha512 digest') # if the pending upload is still valid, then we can't check this file # yet, so return 409 Conflict. If there is no PU, or it's expired, # then we can proceed. file = releng_tool...
identifier_body
api.py
import releng_tooltool.aws import releng_tooltool.utils logger = cli_common.log.get_logger(__name__) def _get_region_and_bucket(region, regions): if region and region in regions: return region, regions[region] # no region specified, so return one at random return random.choice(regions.items()) ...
session.delete(instance) elif change['op'] == 'set_visibility': if change['visibility'] not in ('internal', 'public'): raise werkzeug.exceptions.BadRequest('bad visibility level') file.visibility = change['visibility'] else: raise wer...
'No bucket for region `{}` defined.'.format(instance.region)) bucket = conn.get_bucket(region_bucket) bucket.delete_key(key_name)
random_line_split
api.py
import releng_tooltool.aws import releng_tooltool.utils logger = cli_common.log.get_logger(__name__) def _get_region_and_bucket(region, regions): if region and region in regions: return region, regions[region] # no region specified, so return one at random return random.choice(regions.items()) ...
if not releng_tooltool.utils.is_valid_sha512(info.digest): raise werkzeug.exceptions.BadRequest('Invalid sha512 digest' ) digest = info.digest file = releng_tooltool.models.File.query.filter(releng_tooltool.models.File.sha512 == dige...
raise werkzeug.exceptions.BadRequest('`sha512` is the only allowed digest algorithm')
conditional_block
api.py
import releng_tooltool.aws import releng_tooltool.utils logger = cli_common.log.get_logger(__name__) def _get_region_and_bucket(region, regions): if region and region in regions: return region, regions[region] # no region specified, so return one at random return random.choice(regions.items()) ...
(q): return [row.to_dict() for row in releng_tooltool.models.Batch.query.filter( sa.or_(releng_tooltool.models.Batch.author.contains(q), releng_tooltool.models.Batch.message.contains(q))).all()] def get_batch(id): row = releng_tooltool.models.Batch.query.filt...
search_batches
identifier_name
test_buoyant.py
ant import buoy sampledata = [ { "latitude (degree)": "39.235", "sea_surface_wave_peak_period (s)": "13.79", "polar_coordinate_r1 (1)": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "station_id": "urn:ioos:station:wmo:46014", "sea_surface_wind_wave_period (s)": "3.80", ...
def test_degroup(self): waves
station = buoyant.Buoy(51001) assert buoy.CAM_ENDPOINT in station.image_url self.assertIsNotNone(station.image)
identifier_body
test_buoyant.py
buoyant import buoy sampledata = [ { "latitude (degree)": "39.235", "sea_surface_wave_peak_period (s)": "13.79", "polar_coordinate_r1 (1)": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "station_id": "urn:ioos:station:wmo:46014", "sea_surface_wind_wave_period (s)": "3.80...
assert isinstance(self.b.coords, tuple) assert (self.b.__dict__["lat"], self.b.__dict__["lon"]) == self.b.coords def test_keys(self): """Test that observation attributes exist in Buoy class.""" self.assertIsNotNone(self.b.sea_water_salinity) self.assertIsNotNone(self.b.air_p...
random_line_split
test_buoyant.py
ant import buoy sampledata = [ { "latitude (degree)": "39.235", "sea_surface_wave_peak_period (s)": "13.79", "polar_coordinate_r1 (1)": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "station_id": "urn:ioos:station:wmo:46014", "sea_surface_wind_wave_period (s)": "3.80", ...
(unittest.TestCase): def setUp(self): self.b = buoyant.Buoy("41012") def test_observation(self): """Test the Observation class.""" self.assertTrue(issubclass(buoyant.Observation, float)) subint = float.__new__(buoyant.Observation, 11) assert subint == 11 assert i...
BuoyTestCase
identifier_name
test_buoyant.py
"urn:ioos:station:wmo:46014", "sea_surface_wind_wave_period (s)": "3.80", "spectral_energy (m**2/Hz)": "0;0;0;0;0.117495;0.347233;0.340078;1.07545;1.31407;0.644604;0.319928;0.20951;0.203445;0.407703;0.501098;1.05528;0.552653;0.982512;0.40238;0.259344;0.176087;0.156276;0.10127;0.0713481;0.1257;0.0469963...
unittest.main()
conditional_block
range_arg.rs
use std::ops::{Range, RangeFrom, RangeTo, RangeFull}; pub struct RangeArg { pub start: usize, pub end: Option<usize>, } impl RangeArg { pub fn len(&self, len: usize) -> usize { self.end.unwrap_or(len) - self.start } } impl From<Range<usize>> for RangeArg { #[inline] fn from(r: Range<u...
#[test] fn test_s_macro() { let s: [RangeArg; 2] = s![1..3, 1]; assert!(s[0].start == 1); assert!(s[1].start == 1); assert!(s[0].end == Some(3)); assert!(s[1].end == Some(2)); assert!(s[0].len(5) == 2); assert!(s[1].len(5) == 1); }
);
random_line_split
range_arg.rs
use std::ops::{Range, RangeFrom, RangeTo, RangeFull}; pub struct RangeArg { pub start: usize, pub end: Option<usize>, } impl RangeArg { pub fn len(&self, len: usize) -> usize
} impl From<Range<usize>> for RangeArg { #[inline] fn from(r: Range<usize>) -> RangeArg { RangeArg { start: r.start, end: Some(r.end), } } } impl From<RangeFrom<usize>> for RangeArg { #[inline] fn from(r: RangeFrom<usize>) -> RangeArg { RangeArg { ...
{ self.end.unwrap_or(len) - self.start }
identifier_body
range_arg.rs
use std::ops::{Range, RangeFrom, RangeTo, RangeFull}; pub struct RangeArg { pub start: usize, pub end: Option<usize>, } impl RangeArg { pub fn len(&self, len: usize) -> usize { self.end.unwrap_or(len) - self.start } } impl From<Range<usize>> for RangeArg { #[inline] fn from(r: Range<u...
(i: usize) -> RangeArg { RangeArg { start: i, end: Some(i+1), } } } //////////////////////////////////////////////////////////////////////////////////////////////////// #[macro_export] macro_rules! s( (@as_expr $e:expr) => ($e); (@parse [$($stack:tt)*] $r:expr) => {...
from
identifier_name
ignores.py
#!/usr/bin/env python # Copyright 2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import unittest import os import tempfile # internal modules: from yotta.lib.fsutils import mkDirP, rmRf from yotta.lib.detect import systemDefaultTarg...
'module.json': ''' { "name": "test-testdep-f", "version": "0.0.6", "description": "Module to test test-dependencies and ignoring things", "author": "autopulated", "licenses": [ { "url": "https://spdx.org/licenses/Apache-2.0", "type": "Apache-2.0" } ], "dependencies": {}, "testDep...
random_line_split
ignores.py
#!/usr/bin/env python # Copyright 2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import unittest import os import tempfile # internal modules: from yotta.lib.fsutils import mkDirP, rmRf from yotta.lib.detect import systemDefaultTarg...
(files): test_dir = tempfile.mkdtemp() for path, contents in files.items(): path_dir, file_name = os.path.split(path) path_dir = os.path.join(test_dir, path_dir) mkDirP(path_dir) with open(os.path.join(path_dir, file_name), 'w') as f: f.write(contents) return tes...
writeTestFiles
identifier_name
ignores.py
#!/usr/bin/env python # Copyright 2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import unittest import os import tempfile # internal modules: from yotta.lib.fsutils import mkDirP, rmRf from yotta.lib.detect import systemDefaultTarg...
self.assertEqual(statuscode, 0) return stdout or stderr if __name__ == '__main__': unittest.main()
print('command failed with status %s' % statuscode) print(stdout) print(stderr)
conditional_block
ignores.py
#!/usr/bin/env python # Copyright 2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import unittest import os import tempfile # internal modules: from yotta.lib.fsutils import mkDirP, rmRf from yotta.lib.detect import systemDefaultTarg...
def runCheckCommand(self, args, test_dir): stdout, stderr, statuscode = cli.run(args, cwd=self.test_dir) if statuscode != 0: print('command failed with status %s' % statuscode) print(stdout) print(stderr) self.assertEqual(statuscode, 0) return st...
stdout = self.runCheckCommand(['--target', systemDefaultTarget(), 'clean'], self.test_dir) stdout = self.runCheckCommand(['--target', systemDefaultTarget(), 'test'], self.test_dir) self.assertNotIn('ignoredbyfname', stdout) self.assertNotIn('someothertest', stdout) self.assertNotIn('some...
identifier_body
version.py
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 governi...
# regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at #
random_line_split
visualization_cellsystem.py
# Copyright (C) 2010-2019 The ESPResSo project # # This file is part of ESPResSo.
# (at your option) any later version. # # ESPResSo 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...
# # ESPResSo is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or
random_line_split
visualization_cellsystem.py
# Copyright (C) 2010-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later v...
system.non_bonded_inter[0, 0].lennard_jones.set_params( epsilon=100.0, sigma=1.0, cutoff=3.0, shift="auto") energy = system.analysis.energy() print(f"Before Minimization: E_total = {energy['total']:.2e}") system.integrator.set_steepest_descent(f_max=50, gamma=30.0, max_disp...
system.part.add(pos=box * np.random.random(3))
conditional_block
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString; extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers")...
{ let c_new_root = new_root.to_cstring(); let c_put_old = put_old.to_cstring(); if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) } != 0 { return Err(format!("Error pivot_root to {:?}: {}", new_root, IoError::last_os_error())); } let c_root = CString:...
identifier_body
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString;
extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers"))] pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E> where F: FnMut() -> Result<T, E>, E: From<String>, ...
random_line_split
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString; extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers")...
if unsafe { chroot(path.to_cstring().as_ptr()) } != 0 { return Err(format!("Error chroot to {:?}: {}", path, IoError::last_os_error()).into()); } let res = fun(); let c_pwd = CString::new(".").unwrap(); if unsafe { chroot(c_pwd.as_ptr()) } != 0 { return Er...
{ return Err(format!("Error chdir to root: {}", IoError::last_os_error()).into()); }
conditional_block
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString; extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers")...
(new_root: &Path, put_old: &Path) -> Result<(), String> { let c_new_root = new_root.to_cstring(); let c_put_old = put_old.to_cstring(); if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) } != 0 { return Err(format!("Error pivot_root to {:?}: {}", new_root, IoE...
change_root
identifier_name
_health.component.ts
<%# Copyright 2013-2017 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You ma...
else { return 'badge-danger'; } } refresh() { this.updatingHealth = true; this.healthService.checkHealth().subscribe((health) => { this.healthData = this.healthService.transformHealthData(health); this.updatingHealth = false; }, (error) => {...
{ return 'badge-success'; }
conditional_block
_health.component.ts
<%# Copyright 2013-2017 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You ma...
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. -%> import { Component, OnInit } from '@angular/core'; import { NgbModal } fro...
Unless required by applicable law or agreed to in writing, software
random_line_split
_health.component.ts
<%# Copyright 2013-2017 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You ma...
implements OnInit { healthData: any; updatingHealth: boolean; constructor( private modalService: NgbModal, private healthService: <%=jhiPrefixCapitalized%>HealthService ) { } ngOnInit() { this.refresh(); } baseName(name: string) { return this.healthSe...
HealthCheckComponent
identifier_name
keys_iterator.py
import traceback import sys from gribapi import * INPUT = 'rap_130_20120822_2200_001.grb2' VERBOSE = 1 # verbose error reporting def example(): f = open(INPUT)
gid = grib_new_from_file(f) if gid is None: break iterid = grib_keys_iterator_new(gid, 'ls') # Different types of keys can be skipped # grib_skip_computed(iterid) # grib_skip_coded(iterid) # grib_skip_edition_specific(iterid) # grib_skip_duplicates(iteri...
while 1:
random_line_split
keys_iterator.py
import traceback import sys from gribapi import * INPUT = 'rap_130_20120822_2200_001.grb2' VERBOSE = 1 # verbose error reporting def example(): f = open(INPUT) while 1: gid = grib_new_from_file(f) if gid is None: break iterid = grib_keys_iterator_new(gid, 'ls') # Differen...
if __name__ == "__main__": sys.exit(main())
try: example() except GribInternalError, err: if VERBOSE: traceback.print_exc(file=sys.stderr) else: print >> sys.stderr, err.msg return 1
identifier_body
keys_iterator.py
import traceback import sys from gribapi import * INPUT = 'rap_130_20120822_2200_001.grb2' VERBOSE = 1 # verbose error reporting def
(): f = open(INPUT) while 1: gid = grib_new_from_file(f) if gid is None: break iterid = grib_keys_iterator_new(gid, 'ls') # Different types of keys can be skipped # grib_skip_computed(iterid) # grib_skip_coded(iterid) # grib_skip_edition_specific(iterid...
example
identifier_name
keys_iterator.py
import traceback import sys from gribapi import * INPUT = 'rap_130_20120822_2200_001.grb2' VERBOSE = 1 # verbose error reporting def example(): f = open(INPUT) while 1: gid = grib_new_from_file(f) if gid is None: break iterid = grib_keys_iterator_new(gid, 'ls') # Differen...
grib_keys_iterator_delete(iterid) grib_release(gid) f.close() def main(): try: example() except GribInternalError, err: if VERBOSE: traceback.print_exc(file=sys.stderr) else: print >> sys.stderr, err.msg return 1 if __name__ == ...
keyname = grib_keys_iterator_get_name(iterid) keyval = grib_get_string(iterid, keyname) print "%s = %s" % (keyname, keyval)
conditional_block
syft_message.py
# stdlib from typing import Any from typing import Dict from typing import List from typing import Optional # third party from nacl.signing import VerifyKey from pydantic import BaseModel from pydantic.error_wrappers import ValidationError as PydanticValidationError # relative from .....common.message import Immediat...
( self, node: NodeServiceInterface, verify_key: Optional[VerifyKey] = None ) -> None: """Check if the user has relevant permissions to run this message. Args: node (NodeServiceInterface): node interface used to invoke this message. verify_key (Optional[VerifyKey], op...
check_permissions
identifier_name
syft_message.py
# stdlib from typing import Any from typing import Dict from typing import List from typing import Optional # third party from nacl.signing import VerifyKey from pydantic import BaseModel from pydantic.error_wrappers import ValidationError as PydanticValidationError # relative from .....common.message import Immediat...
Args: node (NodeServiceInterface): node interface used to invoke this message. verify_key (Optional[VerifyKey], optional): user signed verification key. Defaults to None. Raises: AuthorizationError: Error when one of the permission is denied. """ if ...
self, node: NodeServiceInterface, verify_key: Optional[VerifyKey] = None ) -> None: """Check if the user has relevant permissions to run this message.
random_line_split
syft_message.py
# stdlib from typing import Any from typing import Dict from typing import List from typing import Optional # third party from nacl.signing import VerifyKey from pydantic import BaseModel from pydantic.error_wrappers import ValidationError as PydanticValidationError # relative from .....common.message import Immediat...
# If it's a reply message, then load kwargs as a proper reply payload. else: return self.reply_payload_type(**kwargs_dict) except PydanticValidationError: raise BadPayloadException def run( self, node: NodeServiceInterface, verify_key: Optional[V...
return self.request_payload_type(**kwargs_dict)
conditional_block
syft_message.py
# stdlib from typing import Any from typing import Dict from typing import List from typing import Optional # third party from nacl.signing import VerifyKey from pydantic import BaseModel from pydantic.error_wrappers import ValidationError as PydanticValidationError # relative from .....common.message import Immediat...
def get_permissions(self) -> List: """Returns the list of permission classes applicable to the given message.""" raise NotImplementedError def check_permissions( self, node: NodeServiceInterface, verify_key: Optional[VerifyKey] = None ) -> None: """Check if the user has re...
raise NotImplementedError
identifier_body
viewer-error-dialog.ts
// Copyright 2014 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. import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resou...
interface HTMLElementTagNameMap { 'viewer-error-dialog': ViewerErrorDialogElement; } } customElements.define(ViewerErrorDialogElement.is, ViewerErrorDialogElement);
declare global {
random_line_split
viewer-error-dialog.ts
// Copyright 2014 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. import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resou...
} } declare global { interface HTMLElementTagNameMap { 'viewer-error-dialog': ViewerErrorDialogElement; } } customElements.define(ViewerErrorDialogElement.is, ViewerErrorDialogElement);
{ this.reloadFn(); }
conditional_block
viewer-error-dialog.ts
// Copyright 2014 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. import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resou...
() { return 'viewer-error-dialog'; } static get template() { return html`{__html_template__}`; } static get properties() { return { reloadFn: Function, }; } reloadFn: (() => void)|null; private onReload_() { if (this.reloadFn) { this.reloadFn(); } } } declare glo...
is
identifier_name