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
ImageButton.js
/** * 上午9:16 * 2017年6月28日 * Author : 罗浩 (Luo Hao) * GitHub : https://github.com/RoJoHub * Blog : http://blog.csdn.net/mandmg */
static propTypes = { onPress: PropTypes.func, disabled: PropTypes.bool, containStyle: ViewPropTypes.style, activeOpacity: PropTypes.number, source: PropTypes.node } static defaultProps = { onPress: () => { }, disabled: false, activeOpacity: 0.8 } constructor(props) { super...
import React, { PureComponent } from 'react'; import { View, Text, Image, TouchableOpacity, ViewPropTypes } from 'react-native' import PropTypes from 'prop-types' export default class ImageButton extends PureComponent {
random_line_split
parsers.py
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 # version 2 along with this program; if not, write to the Free Software # Foundation, I...
"(can be specified multiple times; default: *deleted.rules)" if show_advanced else argparse.SUPPRESS}), (("--no-ignore",), {'action': 'store_true', 'default': False, 'help': "Disables the ignore option." if show_advanced else argparse.SUPPRESS}), (("--threshold-in",),...
(("--ignore",), {'metavar': '<pattern>', 'action': 'append', 'default': None, 'help': "Filenames to ignore "
random_line_split
parsers.py
# Global arguments - command line options for suricata-update global_arg = [ (("-v", "--verbose"), {'action': 'store_true', 'default': None, 'help': "Be more verbose"}), (("-q", "--quiet"), {'action': 'store_true', 'default': None, 'help': "Be quiet, warning and error messages only"}), ...
setattr(args, arg, getattr(global_args, arg))
conditional_block
parsers.py
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 # version 2 along with this program; if not, write to the Free Software # Foundation, I...
def parse_commands(subparsers, global_parser): commands.listsources.register(subparsers.add_parser( "list-sources", parents=[global_parser])) commands.listsources.register(subparsers.add_parser( "list-enabled-sources", parents=[global_parser])) commands.addsource.register(subparsers.add_p...
update_parser = subparsers.add_parser( "update", add_help=True, parents=[global_parser], formatter_class=argparse.RawDescriptionHelpFormatter) for arg, opts in update_arg: update_parser.add_argument(*arg, **opts) return update_parser
identifier_body
parsers.py
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 # version 2 along with this program; if not, write to the Free Software # Foundation, Inc.,...
(subparsers, global_parser): commands.listsources.register(subparsers.add_parser( "list-sources", parents=[global_parser])) commands.listsources.register(subparsers.add_parser( "list-enabled-sources", parents=[global_parser])) commands.addsource.register(subparsers.add_parser( "add-s...
parse_commands
identifier_name
fingerprint.js
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ ;(function (name, context, definition) { if (typeof module !== 'undefined' && module.exports) { module.exports = definition(); } else if (typeof define === 'function' &&...
return !!window.sessionStorage; } catch(e) { return true; // SecurityError when referencing it means it exists } }, isCanvasSupported: function () { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }, isIE: functi...
random_line_split
fingerprint.js
; } } } }; this.map = function(obj, iterator, context) { var results = []; // Not using strict equality so that this acts as a // shortcut to checking for `null` and `undefined`. if (obj == null) return results; if (nativeMap && obj.map === nativeMap) retur...
{ resolution = [screen.height, screen.width]; }
conditional_block
restore.py
# This file is part of VoltDB. # Copyright (C) 2008-2013 VoltDB Inc. # # This file contains original code and/or modifications of original code. # Any modifications made by VoltDB Inc. are licensed under the following # terms and conditions: # # Permission is hereby granted, free of charge, to any person obtaining # a...
columns = [VOLT.FastSerializer.VOLTTYPE_STRING, VOLT.FastSerializer.VOLTTYPE_STRING] params = [runner.opts.directory, runner.opts.nonce] response = runner.call_proc('@SnapshotRestore', columns, params) runner.info('The snapshot was restored.') print response.table(0).format_table(caption = 'Snapshot Re...
identifier_body
restore.py
# This file is part of VoltDB. # Copyright (C) 2008-2013 VoltDB Inc. # # This file contains original code and/or modifications of original code. # Any modifications made by VoltDB Inc. are licensed under the following # terms and conditions: # # Permission is hereby granted, free of charge, to any person obtaining # a...
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. @VOLT.Command( bundles = VOLT.AdminBundle(), description = 'Resto...
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
random_line_split
restore.py
# This file is part of VoltDB. # Copyright (C) 2008-2013 VoltDB Inc. # # This file contains original code and/or modifications of original code. # Any modifications made by VoltDB Inc. are licensed under the following # terms and conditions: # # Permission is hereby granted, free of charge, to any person obtaining # a...
(runner): columns = [VOLT.FastSerializer.VOLTTYPE_STRING, VOLT.FastSerializer.VOLTTYPE_STRING] params = [runner.opts.directory, runner.opts.nonce] response = runner.call_proc('@SnapshotRestore', columns, params) runner.info('The snapshot was restored.') print response.table(0).format_table(caption ...
restore
identifier_name
triggerPhotons.py
from matplotlib import rcParams, rc import numpy as np import sys from fitFunctions import gaussian import scipy.interpolate import scipy.signal from baselineIIR import IirFilter import pickle import smooth # common setup for matplotlib params = {'savefig.dpi': 300, # save figures to 300 dpi 'axes.labelsize'...
return optSigmaThresh, optNNegDerivChecks, optNegDerivLenience, minSigma, optPeakDict def findSigmaThresh(data, initSigmaThresh=2., tailSlack=0., isPlot=False): ''' Finds the optimal photon trigger threshold by cutting out the noise tail in the pulse height histogram. INPUTS: data - fil...
sigma = np.std(peakDict['peakHeights']) if(sigma<minSigma): minSigma = sigma optSigmaThresh = sigmaThresh optNNegDerivChecks = nNegDerivChecks optNegDerivLenience = negDerivLenience ...
conditional_block
triggerPhotons.py
from matplotlib import rcParams, rc import numpy as np import sys from fitFunctions import gaussian import scipy.interpolate import scipy.signal from baselineIIR import IirFilter import pickle import smooth # common setup for matplotlib params = {'savefig.dpi': 300, # save figures to 300 dpi 'axes.labelsize'...
(data, initSigmaThresh=2., tailSlack=0., isPlot=False): ''' Finds the optimal photon trigger threshold by cutting out the noise tail in the pulse height histogram. INPUTS: data - filtered phase timestream data (positive pulses) initSigmaThresh - sigma threshold to use when constructing ini...
findSigmaThresh
identifier_name
triggerPhotons.py
from matplotlib import rcParams, rc import numpy as np import sys from fitFunctions import gaussian import scipy.interpolate import scipy.signal from baselineIIR import IirFilter import pickle import smooth # common setup for matplotlib params = {'savefig.dpi': 300, # save figures to 300 dpi 'axes.labelsize'...
except IndexError: return {'peakIndices':np.array([]),'peakHeights':np.array([])} if bNegativePulses: peakHeights = data[peakIndices] else: peakHeights = -data[peakIndices] #flip back to positive sign return {'peakIndices':peakIndices,'peakHeights':peakHeights} def opti...
if i < len(peakIndices): p = peakIndices[i] else: p = peakIndices[-1]
random_line_split
triggerPhotons.py
from matplotlib import rcParams, rc import numpy as np import sys from fitFunctions import gaussian import scipy.interpolate import scipy.signal from baselineIIR import IirFilter import pickle import smooth # common setup for matplotlib params = {'savefig.dpi': 300, # save figures to 300 dpi 'axes.labelsize'...
plt.show() print 'peaksHistLen:', len(peaksHist) peaksHist = smooth.smooth(peaksHist,(len(peaksHistBins)/20)*2+1) print 'peaksHistSmoothLen:', len(peaksHist) if(isPlot): plt.plot(peaksHistBins[0:len(peaksHist)], peaksHist) plt.title('smoothed plot') plt.show() mi...
''' Finds the optimal photon trigger threshold by cutting out the noise tail in the pulse height histogram. INPUTS: data - filtered phase timestream data (positive pulses) initSigmaThresh - sigma threshold to use when constructing initial pulse height histogram tailSlack - amount (...
identifier_body
quant_exp.py
try: from IBMQuantumExperience import IBMQuantumExperience from pprint import pprint def quant_exp(args):
except ModuleNotFoundError: print('IBM suite not installed') #1/0 def quant_exp(args): 1/0
with open('etc/IBMtoken', 'r') as infile: token = infile.read().replace('\n', '') config = { "url": 'https://quantumexperience.ng.bluemix.net/api' } QuantExp = IBMQuantumExperience.IBMQuantumExperience api = QuantExp(token, config) for code in api.get_last...
identifier_body
quant_exp.py
try: from IBMQuantumExperience import IBMQuantumExperience from pprint import pprint def quant_exp(args): with open('etc/IBMtoken', 'r') as infile: token = infile.read().replace('\n', '') config = { "url": 'https://quantumexperience.ng.bluemix.net/api' } ...
(args): 1/0
quant_exp
identifier_name
quant_exp.py
try: from IBMQuantumExperience import IBMQuantumExperience from pprint import pprint def quant_exp(args): with open('etc/IBMtoken', 'r') as infile: token = infile.read().replace('\n', '') config = { "url": 'https://quantumexperience.ng.bluemix.net/api' } ...
except ModuleNotFoundError: print('IBM suite not installed') #1/0 def quant_exp(args): 1/0
pprint(code) ''' name = code['name'] if 'grover' in name.lower(): print('IBM Results for{}'.format(name)) pprint(code['executions'][-1]['result']) #pprint(code.keys()) #pprint(api.get_execution(name)) '''
conditional_block
main.rs
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate mui; use std::cell::Cell; use mui::prelude::*; fn main() { let mut app = mui::App::new("Mui Widgets Demo!"); // primitives let rect = mui::Rect::new("r1", true); rect.set_zpos(3); app.add_widget(&rect); let count = Ce...
layout.set_zpos(5); layout.add_widget(&button); layout.add_widget(&button2); app.add_widget(&layout); let sa_textbox = mui::TextBox::new("textbox"); sa_textbox.set_xy(600.0, 200.0); app.add_widget(&sa_textbox); app.run(); }
let mut layout = mui::BoxLayout::new("l1"); layout.set_xy(300.0, 40.0);
random_line_split
main.rs
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate mui; use std::cell::Cell; use mui::prelude::*; fn
() { let mut app = mui::App::new("Mui Widgets Demo!"); // primitives let rect = mui::Rect::new("r1", true); rect.set_zpos(3); app.add_widget(&rect); let count = Cell::new(0); let count2 = Cell::new(0); // sa - stand alone let mut sa_button = mui::Button::new("b1"); sa_butto...
main
identifier_name
main.rs
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate mui; use std::cell::Cell; use mui::prelude::*; fn main()
let mut button = mui::Button::new("b2"); button.set_text("Click me"); button.set_on_click_fn(Box::new(move |this| { count.set(count.get()+1); this.set_text(format!("Clicked {}", count.get())); })); let mut button2 = mui::Button::new("b3"); button2.set_text("Click me"); butt...
{ let mut app = mui::App::new("Mui Widgets Demo!"); // primitives let rect = mui::Rect::new("r1", true); rect.set_zpos(3); app.add_widget(&rect); let count = Cell::new(0); let count2 = Cell::new(0); // sa - stand alone let mut sa_button = mui::Button::new("b1"); sa_button.s...
identifier_body
issue-15094.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 ...
(&self, _args: ()) { //~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn println!("{}", self.x); } } fn make_shower<T>(x: T) -> Shower<T> { Shower { x: x } } pub fn main() { let show3 = make_shower(3i); show3(); }
call
identifier_name
issue-15094.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 ...
{ let show3 = make_shower(3i); show3(); }
identifier_body
issue-15094.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.
// except according to those terms. #![feature(unboxed_closures)] use std::{fmt, ops}; struct Shower<T> { x: T } impl<T: fmt::Show> ops::Fn<(), ()> for Shower<T> { fn call(&self, _args: ()) { //~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn println!("{}"...
// // 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 your // option. This file may not be copied, modified, or distributed
random_line_split
config.py
import os import re import yaml try: from packaging.version import parse as parse_version except ImportError: from pkg_resources import parse_version from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS from .utils import counted_error, fatal_e...
except Exception as e: fatal_error('%s(%s)', type(e).__name__, e) def parse_bool(value) -> bool: return str(value).lower() in ('true', '1') def validate_bool(key, value): if str(value).lower() not in ('true', 'false', '1', '0'): counted_error('Invalid %s value. It must be boolean.', key...
""" Read the config.yml file :param path: path to the file or the base directory :param pre_validate: check version and crp_type fields :return: dict """ if os.path.isdir(path): path = os.path.join(path, 'config.yml') try: with open(path, 'r') as f: config = yam...
identifier_body
config.py
import os import re import yaml try: from packaging.version import parse as parse_version except ImportError: from pkg_resources import parse_version from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS from .utils import counted_error, fatal_e...
for button_key, button in buttons.items(): if button_key not in ports: counted_error('Button key %s is not found in ports.', button_key) for key in button.keys(): if key not in BUTTON_CONFIG_KEYS: counted_error('Key %s is i...
conditional_block
config.py
import os import re import yaml try: from packaging.version import parse as parse_version except ImportError: from pkg_resources import parse_version from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS from .utils import counted_error, fatal_e...
counted_error('Key %s is invalid for button %s.', key, button_key)
if button_key not in ports: counted_error('Button key %s is not found in ports.', button_key) for key in button.keys(): if key not in BUTTON_CONFIG_KEYS:
random_line_split
config.py
import os import re import yaml try: from packaging.version import parse as parse_version except ImportError: from pkg_resources import parse_version from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS from .utils import counted_error, fatal_e...
(config: dict, min_version: str, max_version: str): version = parse_version(config['version']) if version < parse_version(min_version): return -1 if version > parse_version(max_version): return 1 return 0 def validate_version(config: dict): cmp = compare_version(config, CURRENT_MI...
compare_version
identifier_name
calc_delta_BC.py
#!/usr/bin/env python # # Calculate the change in the betweenness centrality of each residue over the # course of an MD simulation # # Script distributed under GNU GPL 3.0 # # Author: David Brown # Date: 17-11-2016 import argparse, calc_delta from lib.cli import CLI from lib.utils import Logger def main(args): ...
parser.add_argument('--normalization-mode', help="Method used to normalize - default: (Delta BC/(BC+1))", default=None) parser.add_argument("--generate-plots", help="Plot results - without setting this flag, no graph will be generated", action='store_true', default=False) CLI(parser, main, log)
random_line_split
calc_delta_BC.py
#!/usr/bin/env python # # Calculate the change in the betweenness centrality of each residue over the # course of an MD simulation # # Script distributed under GNU GPL 3.0 # # Author: David Brown # Date: 17-11-2016 import argparse, calc_delta from lib.cli import CLI from lib.utils import Logger def main(args):
log = Logger() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--reference", help="The reference BC matrix (.dat)") parser.add_argument("--alternatives", help="The alternative BC matrices (.dat)", nargs="*") parser.add_argument("--normalize", help="Normalizes the ...
args.matrix_type = "BC" calc_delta.main(args)
identifier_body
calc_delta_BC.py
#!/usr/bin/env python # # Calculate the change in the betweenness centrality of each residue over the # course of an MD simulation # # Script distributed under GNU GPL 3.0 # # Author: David Brown # Date: 17-11-2016 import argparse, calc_delta from lib.cli import CLI from lib.utils import Logger def
(args): args.matrix_type = "BC" calc_delta.main(args) log = Logger() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--reference", help="The reference BC matrix (.dat)") parser.add_argument("--alternatives", help="The alternative BC matrices (.dat)", nargs="*")...
main
identifier_name
calc_delta_BC.py
#!/usr/bin/env python # # Calculate the change in the betweenness centrality of each residue over the # course of an MD simulation # # Script distributed under GNU GPL 3.0 # # Author: David Brown # Date: 17-11-2016 import argparse, calc_delta from lib.cli import CLI from lib.utils import Logger def main(args): ...
parser = argparse.ArgumentParser() parser.add_argument("--reference", help="The reference BC matrix (.dat)") parser.add_argument("--alternatives", help="The alternative BC matrices (.dat)", nargs="*") parser.add_argument("--normalize", help="Normalizes the values", action='store_true', default=False) p...
conditional_block
validateDni.ts
export class ValidateDni implements ng.IDirective{ public link: (scope: angular.IScope , elem: ng.IAugmentedJQuery, attrs: angular.IAttributes, ngModel: angular.INgModelController) => void; restrict ='A'; require = 'ngModel';
(scope: angular.IScope, elem:ng.IAugmentedJQuery, attrs: angular.IAttributes, ngModel: angular.INgModelController, $log:angular.ILogService) { // It's important to add `link` to the prototype or you will end up with state issues. // See http://blog.aaronholmes.net/writing-angularjs-directives-as-typescript-cl...
constructor
identifier_name
validateDni.ts
export class ValidateDni implements ng.IDirective{ public link: (scope: angular.IScope , elem: ng.IAugmentedJQuery, attrs: angular.IAttributes, ngModel: angular.INgModelController) => void; restrict ='A'; require = 'ngModel';
constructor(scope: angular.IScope, elem:ng.IAugmentedJQuery, attrs: angular.IAttributes, ngModel: angular.INgModelController, $log:angular.ILogService) { // It's important to add `link` to the prototype or you will end up with state issues. // See http://blog.aaronholmes.net/writing-angularjs-directives-as-...
random_line_split
issue-7663.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 my_main() { assert!(p() == 2); } } } mod test2 { mod foo { pub fn p() -> int { 1 } } mod bar { pub fn p() -> int { 2 } } pub mod baz { use test2::foo::p; //~ ERROR: unused import use test2::bar::p; pub fn my_main() { assert!(p() == 2); } } } mod test3 { ...
use test1::bar::*;
random_line_split
issue-7663.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 ...
} } mod test3 { mod foo { pub fn p() -> int { 1 } } mod bar { pub fn p() -> int { 2 } } pub mod baz { use test3::foo::*; //~ ERROR: unused import use test3::bar::p; pub fn my_main() { assert!(p() == 2); } } } fn main() { }
{ assert!(p() == 2); }
identifier_body
issue-7663.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 ...
() -> int { 2 } } pub mod baz { use test2::foo::p; //~ ERROR: unused import use test2::bar::p; pub fn my_main() { assert!(p() == 2); } } } mod test3 { mod foo { pub fn p() -> int { 1 } } mod bar { pub fn p() -> int { 2 } } pub mod baz { use test3::foo::*; //~ ERR...
p
identifier_name
fitsheader.py
containing keywords EXTNAME='SCI' and EXTVER='2':: $ fitsheader --extension "SCI,2" filename.fits 4. Print only specific keywords:: $ fitsheader --keyword BITPIX --keyword NAXIS filename.fits 5. Print keywords NAXIS, NAXIS1, NAXIS2, etc using a wildcard:: $ fitsheader --keyword NAXIS* filename.fits...
If the hdukey does not correspond to an extension. """ # First we obtain the desired header try: if compressed: # In the case of a compressed image, return the header before # decompression (not the default behavior) header ...
"""Returns a list of `astropy.io.fits.card.Card` objects. This function will return the desired header cards, taking into account the user's preference to see the compressed or uncompressed version. Parameters ---------- hdukey : int or str Key of a single H...
identifier_body
fitsheader.py
containing keywords EXTNAME='SCI' and EXTVER='2':: $ fitsheader --extension "SCI,2" filename.fits 4. Print only specific keywords:: $ fitsheader --keyword BITPIX --keyword NAXIS filename.fits 5. Print keywords NAXIS, NAXIS1, NAXIS2, etc using a wildcard:: $ fitsheader --keyword NAXIS* filename.fits...
Parameters ---------- args : argparse.Namespace Arguments passed from the command-line as defined below. """ for idx, filename in enumerate(args.filename): # support wildcards if idx > 0 and not args.keywords: print() # print a newline between different files t...
def print_headers_traditional(args): """Prints FITS header(s) using the traditional 80-char format.
random_line_split
fitsheader.py
keywords EXTNAME='SCI' and EXTVER='2':: $ fitsheader --extension "SCI,2" filename.fits 4. Print only specific keywords:: $ fitsheader --keyword BITPIX --keyword NAXIS filename.fits 5. Print keywords NAXIS, NAXIS1, NAXIS2, etc using a wildcard:: $ fitsheader --keyword NAXIS* filename.fits 6. Dump t...
(args): """Prints FITS header(s) in a machine-readable table format. Parameters ---------- args : argparse.Namespace Arguments passed from the command-line as defined below. """ tables = [] # Create a Table object for each file for filename in args.filename: # Support wildcards...
print_headers_as_table
identifier_name
fitsheader.py
containing keywords EXTNAME='SCI' and EXTVER='2':: $ fitsheader --extension "SCI,2" filename.fits 4. Print only specific keywords:: $ fitsheader --keyword BITPIX --keyword NAXIS filename.fits 5. Print keywords NAXIS, NAXIS1, NAXIS2, etc using a wildcard:: $ fitsheader --keyword NAXIS* filename.fits...
if tablerows: from .... import table return table.Table(tablerows) return None def print_headers_traditional(args): """Prints FITS header(s) using the traditional 80-char format. Parameters ---------- args : argparse.Namespace Arguments passed from th...
try: for card in self._get_cards(hdu, keywords, compressed): tablerows.append({'filename': self.filename, 'hdu': hdu, 'keyword': card.keyword, 'value': str(card.value)}) ...
conditional_block
accept-user-invite.ts
/// <reference path='./context.d.ts' /> /// <reference path='../../../../third_party/polymer/polymer.d.ts' /> var ui = ui_context.ui; var model = ui_context.model; var core = ui_context.core; Polymer({ addUser: function() { core.addUser(this.receivedInviteToken).then(() => { this.fire('open-dialog', { ...
}, closeAcceptUserInvitePanel: function() { this.$.acceptUserInvitePanel.close(); }, showInviteUser: function() { this.fire('core-signal', { name: 'open-invite-user-dialog' }); // accept-user-invite may be added on top of uproxy-invite-user, so // we need to close this panel. this.closeAccep...
}, openAcceptUserInvitePanel: function() { this.$.acceptUserInvitePanel.open();
random_line_split
sct_get_centerline_from_labels.py
#!/usr/bin/env python import commands, sys # Get path of the toolbox status, path_sct = commands.getstatusoutput('echo $SCT_DIR') # Append path that contains scripts, to be able to load modules sys.path.append(path_sct + '/scripts') from msct_parser import Parser from nibabel import load, save, Nifti1Image import ...
(list_file, param, output_file_name=None, remove_temp_files = 1, verbose = 0): path, file, ext = sct.extract_fname(list_file[0]) # create temporary folder path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") sct.run('mkdir '+path_tmp) # copy files into tmp folder sct.printv('\nCopy files into tmp ...
main
identifier_name
sct_get_centerline_from_labels.py
#!/usr/bin/env python import commands, sys # Get path of the toolbox status, path_sct = commands.getstatusoutput('echo $SCT_DIR') # Append path that contains scripts, to be able to load modules sys.path.append(path_sct + '/scripts') from msct_parser import Parser from nibabel import load, save, Nifti1Image import ...
if "-o" in arguments: output_file_name = arguments["-o"] else: output_file_name = None param = Param() param.verbose = verbose param.remove_temp_files =remove_temp_files main(list_file, param, output_file_name, remove_temp_files, verbose)
list_file = None
conditional_block
sct_get_centerline_from_labels.py
#!/usr/bin/env python import commands, sys # Get path of the toolbox status, path_sct = commands.getstatusoutput('echo $SCT_DIR') # Append path that contains scripts, to be able to load modules sys.path.append(path_sct + '/scripts') from msct_parser import Parser from nibabel import load, save, Nifti1Image import ...
hdr_0 = file_0.get_header() orientation_file_0 = get_orientation(list_file[0]) if len(list_file)>0: for i in range(1, len(list_file)): orientation_file_temp = get_orientation(list_file[i]) if orientation_file_0 != orientation_file_temp : print "ERROR: The files ",...
path, file, ext = sct.extract_fname(list_file[0]) # create temporary folder path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") sct.run('mkdir '+path_tmp) # copy files into tmp folder sct.printv('\nCopy files into tmp folder...', verbose) for i in range(len(list_file)): file_temp = os.path....
identifier_body
sct_get_centerline_from_labels.py
#!/usr/bin/env python import commands, sys # Get path of the toolbox status, path_sct = commands.getstatusoutput('echo $SCT_DIR') # Append path that contains scripts, to be able to load modules sys.path.append(path_sct + '/scripts') from msct_parser import Parser from nibabel import load, save, Nifti1Image import ...
def main(list_file, param, output_file_name=None, remove_temp_files = 1, verbose = 0): path, file, ext = sct.extract_fname(list_file[0]) # create temporary folder path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") sct.run('mkdir '+path_tmp) # copy files into tmp folder sct.printv('\nCopy files i...
random_line_split
002.py
blocklevel = ["blockquote", "div", "form", "p", "table", "video", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "details", "article", "header", "main"] def normalizeEnter(src): #Deletes all user defined for readability reason existing line breaks that are issues for the HTML output
def main(islinput, inputfile, pluginData, globalData): currentIndex = 0 for item in islinput: item = normalizeEnter(item) #Deletes not wanted line breaks in order to prevent the problem we have with Markdown. islinput[currentIndex] = item currentIndex += 1 return islinput, pluginData, globalData
for elem in blocklevel: while src.find("\r<" + elem) > -1: src = src.replace("\r<" + elem, "<" + elem) while src.find("</" + elem + ">\r") > -1: src = src.replace("</" + elem + ">\r", "</" + elem + ">") while src.find(">\r") > -1: src = src.replace(">\r", ">") #It is really needed, it created some other ...
identifier_body
002.py
blocklevel = ["blockquote", "div", "form", "p", "table", "video", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "details", "article", "header", "main"] def normalizeEnter(src): #Deletes all user defined for readability reason existing line breaks that are issues for the HTML output for elem in blocklevel: while src.fin...
(islinput, inputfile, pluginData, globalData): currentIndex = 0 for item in islinput: item = normalizeEnter(item) #Deletes not wanted line breaks in order to prevent the problem we have with Markdown. islinput[currentIndex] = item currentIndex += 1 return islinput, pluginData, globalData
main
identifier_name
002.py
blocklevel = ["blockquote", "div", "form", "p", "table", "video", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "details", "article", "header", "main"] def normalizeEnter(src): #Deletes all user defined for readability reason existing line breaks that are issues for the HTML output for elem in blocklevel: while src.fin...
while src.find("</" + elem + ">\r") > -1: src = src.replace("</" + elem + ">\r", "</" + elem + ">") while src.find(">\r") > -1: src = src.replace(">\r", ">") #It is really needed, it created some other bugs?! while src.find("\r</") > -1: src = src.replace("\r</", "</") ##It is really needed, it created ...
src = src.replace("\r<" + elem, "<" + elem)
conditional_block
002.py
blocklevel = ["blockquote", "div", "form", "p", "table", "video", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "details", "article", "header", "main"] def normalizeEnter(src): #Deletes all user defined for readability reason existing line breaks that are issues for the HTML output for elem in blocklevel:
src = src.replace("\r<" + elem, "<" + elem) while src.find("</" + elem + ">\r") > -1: src = src.replace("</" + elem + ">\r", "</" + elem + ">") while src.find(">\r") > -1: src = src.replace(">\r", ">") #It is really needed, it created some other bugs?! while src.find("\r</") > -1: src = src.replace("\...
while src.find("\r<" + elem) > -1:
random_line_split
index.d.ts
import { ReactMouseEvents, SemanticSIZES } from '../..'; import * as React from 'react'; interface RatingProps { /** An element type to render as (string or function). */ as?: any; /** Additional classes. */ className?: string; /** * You can clear the rating by clicking on the current start rating. *...
} export const RatingIcon: React.ComponentClass<RatingIconProps>;
/** An index of icon inside Rating. */ index?: number; /** Indicates selection of an icon. */ selected?: boolean;
random_line_split
clusters.ts
/iron-list/iron-list.js'; import {IronScrollThresholdElement} from 'chrome://resources/polymer/v3_0/iron-scroll-threshold/iron-scroll-threshold.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BrowserProxyImpl} from './browser_proxy.js'; import {getTemplate} f...
{ // Scroll to the top when `result` contains a new set of clusters. this.scrollTop = 0; this.result_ = result; }
conditional_block
clusters.ts
_ts.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {Time} from 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-webui.js'; import {IronListElement} from 'chrome://resources/polymer/...
() { return { /** * The current query for which related clusters are requested and shown. */ query: { type: String, observer: 'onQueryChanged_', value: '', }, /** * The header text to show when the query and the results are non-empty. */ ...
properties
identifier_name
clusters.ts
/assert_ts.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {Time} from 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-webui.js'; import {IronListElement} from 'chrome://resources/p...
return; } this.onLoadMoreButtonClick_(); } //============================================================================ // Helper methods //============================================================================ private computeHeaderText_(): string { return this.result_ && this.res...
// on page load, and whenever the user is typing in the searchbox.
random_line_split
clusters.ts
_ts.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {Time} from 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-webui.js'; import {IronListElement} from 'chrome://resources/polymer/...
/** * Returns a promise that resolves when the browser is idle. */ private onBrowserIdle_(): Promise<void> { return new Promise(resolve => { window.requestIdleCallback(() => { resolve(); }); }); } private onClustersQueryResult_(result: QueryResult) { if (result.isContinu...
{ return !this.result_ || this.result_.clusters.length === 0 || !this.result_.canLoadMore; }
identifier_body
kwarqs_drive_mech.py
import wpilib import hal from wpilib import RobotDrive class KwarqsDriveMech(RobotDrive): def
(self, *args, **kwargs): super().__init__(*args, **kwargs) self.weight_multiplier = 1 def set_multiplier(self, in_multi = None): if in_multi != None : self.weight_multiplier = in_multi else: self.weight_multiplier = 1 def mecanumDrive_Car...
__init__
identifier_name
kwarqs_drive_mech.py
import wpilib import hal from wpilib import RobotDrive class KwarqsDriveMech(RobotDrive): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.weight_multiplier = 1 def set_multiplier(self, in_multi = None): if in_multi != None : sel...
xIn = x yIn = y # Negate y for the joystick. yIn = -yIn # Compenstate for gyro angle. xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle) wheelSpeeds = [0]*self.kMaxNumberOfMotors wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation ...
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive, self.getNumMotors(), hal.HALUsageReporting.kRobotDrive_MecanumCartesian) RobotDrive.kMecanumCartesian_Reported = True
conditional_block
kwarqs_drive_mech.py
import wpilib import hal from wpilib import RobotDrive class KwarqsDriveMech(RobotDrive):
:param x: The speed that the robot should drive in the X direction. [-1.0..1.0] :param y: The speed that the robot should drive in the Y direction. This input is inverted to match the forward == -1.0 that joysticks produce. [-1.0..1.0] :param rotation: The rat...
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.weight_multiplier = 1 def set_multiplier(self, in_multi = None): if in_multi != None : self.weight_multiplier = in_multi else: self.weight_multiplier = 1 def meca...
identifier_body
kwarqs_drive_mech.py
import wpilib import hal from wpilib import RobotDrive class KwarqsDriveMech(RobotDrive): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.weight_multiplier = 1 def set_multiplier(self, in_multi = None): if in_multi != None : sel...
if not wpilib.RobotDrive.kMecanumCartesian_Reported: hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive, self.getNumMotors(), hal.HALUsageReporting.kRobotDrive_MecanumCartesian) RobotDrive.kMecanumCartesian_Reported = True ...
"""
random_line_split
cross-section.js
define(function(require) { 'use strict'; var GraphView = require('../graph'); var StaticGraphView = require('./static'); require('less!styles/cross-section-graph'); /* * "Local" variables for functions to share and recycle */ var length, lat, latWidth, latHeight, height, xSpacing, poi...
}, /** * Sets the border back to normal. */ stopChanging: function() { if (this.$canvas) { this.changing = false; this.$canvasWrapper.removeClass('changing'); } }, show: function(event) { StaticGraphView.prototype.show.apply(this, [event]); this.heatmapView.showCrossSectionSlider...
{ this.changing = true; this.$canvasWrapper.addClass('changing'); }
conditional_block
cross-section.js
define(function(require) { 'use strict'; var GraphView = require('../graph'); var StaticGraphView = require('./static'); require('less!styles/cross-section-graph'); /* * "Local" variables for functions to share and recycle */ var length, lat, latWidth, latHeight, height, xSpacing, poi...
// Hide the beginning points[0].x = -1; }, /** * Change the canvas border to give the user feedback. * This is called when the user starts sliding the * cross section slider to show that changing its * position affects what is rendered in this view. */ startChanging: function() { if...
for (i = 0; i < length; i++) { points[i].x = i * xSpacing; points[i].y = ((lat[i][j] - 2) / -4) * height; }
random_line_split
select-kernel.tsx
Actions } from "./browser-actions"; const row_style: React.CSSProperties = { marginTop: "5px", marginBottom: "5px", }; const main_style: React.CSSProperties = { padding: "20px 10px", overflowY: "auto", overflowX: "hidden", }; interface KernelSelectorProps { actions: JupyterActions; site_name: string; ...
l={"noopener"}> {descr} </a> ); } else { return descr; } } render_kernel_button( name: string, size?: string, show_icon: boolean = true ): Rendered { const lang = this.kernel_attr(name, "language"); let icon: Rendered | undefined = undefined; if (lang...
return ( <a href={url} target={"_blank"} re
conditional_block
select-kernel.tsx
Actions } from "./browser-actions"; const row_style: React.CSSProperties = { marginTop: "5px", marginBottom: "5px", }; const main_style: React.CSSProperties = { padding: "20px 10px", overflowY: "auto", overflowX: "hidden", }; interface KernelSelectorProps { actions: JupyterActions; site_name: string; ...
me: string): string | undefined { return this.kernel_attr(name, "display_name"); } kernel_attr(name: string, attr: string): string | undefined { if (this.props.kernels_by_name == null) return undefined; const k = this.props.kernels_by_name.get(name); if (k == null) return undefined; return k.ge...
nel_name(na
identifier_name
select-kernel.tsx
upyterActions } from "./browser-actions"; const row_style: React.CSSProperties = { marginTop: "5px", marginBottom: "5px", }; const main_style: React.CSSProperties = { padding: "20px 10px", overflowY: "auto", overflowX: "hidden", }; interface KernelSelectorProps { actions: JupyterActions; site_name: str...
// the idea here is to not set the kernel, but still render the notebook. // looks like that's not easy, and well, probably incompatible with classical jupyter. /* <Row style={row_style} className={"pull-right"}> {this.close_button()} </Row> close_button() { return ( <Button ke...
random_line_split
select-kernel.tsx
Actions } from "./browser-actions"; const row_style: React.CSSProperties = { marginTop: "5px", marginBottom: "5px", }; const main_style: React.CSSProperties = { padding: "20px 10px", overflowY: "auto", overflowX: "hidden", }; interface KernelSelectorProps { actions: JupyterActions; site_name: string; ...
se { const name = this.kernel_name(this.props.kernel); const current = name != null ? <> The currently selected kernel is "{name}".</> : ""; return ( <Row style={row_style}> <strong>Select a new kernel.</strong> {current} </Row> ); } } render...
let msg: Rendered; // kernel, but no info means it is not known if (this.props.kernel != null && this.props.kernel_info == null) { msg = ( <> Your notebook kernel <code>"{this.props.kernel}"</code> does not exist on {this.props.site_name}. </> ...
identifier_body
from_proxy.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ // Two tests involving Array.from and a Proxy. var log = []; function LoggingProxy(target)
} // When the new object created by Array.from is a Proxy, // Array.from calls handler.defineProperty to create new elements // but handler.set to set the length. LoggingProxy.from = Array.from; LoggingProxy.from([3, 4, 5]); assertDeepEq(log, ["define", "0", "define", "1", "define", "2", "set", "length"]); // When t...
{ var h = { defineProperty: function (t, id) { log.push("define", id); return undefined; }, has: function (t, id) { log.push("has", id); return id in t; }, get: function (t, id) { log.push("get", id); ret...
identifier_body
from_proxy.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ // Two tests involving Array.from and a Proxy. var log = []; function
(target) { var h = { defineProperty: function (t, id) { log.push("define", id); return undefined; }, has: function (t, id) { log.push("has", id); return id in t; }, get: function (t, id) { log.push("get", id); ...
LoggingProxy
identifier_name
from_proxy.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ // Two tests involving Array.from and a Proxy. var log = []; function LoggingProxy(target) { var h = { defineProperty: function (t, id) { log.push("define", id); return undefi...
// calls handler.get on it. log = []; assertDeepEq(Array.from(new LoggingProxy([3, 4, 5])), [3, 4, 5]); assertDeepEq(log, ["get", Symbol.iterator, "get", "length", "get", "0", "get", "length", "get", "1", "get", "length", "get", "2", "get", "le...
LoggingProxy.from([3, 4, 5]); assertDeepEq(log, ["define", "0", "define", "1", "define", "2", "set", "length"]); // When the argument passed to Array.from is a Proxy, Array.from
random_line_split
modal-backdrop.component.ts
import { Component, ElementRef, Renderer } from '@angular/core'; import { ClassName } from './modal-options.class'; export class ModalBackdropOptions { public animate:boolean = true; public constructor(options:ModalBackdropOptions) { Object.assign(this, options); } } /** This component will be added as ba...
}
{ this.element = element; this.renderer = renderer; }
identifier_body
modal-backdrop.component.ts
import { Component, ElementRef, Renderer } from '@angular/core'; import { ClassName } from './modal-options.class'; export class ModalBackdropOptions { public animate:boolean = true; public constructor(options:ModalBackdropOptions) { Object.assign(this, options); } } /** This component will be added as ba...
}
public constructor(element:ElementRef, renderer:Renderer) { this.element = element; this.renderer = renderer; }
random_line_split
modal-backdrop.component.ts
import { Component, ElementRef, Renderer } from '@angular/core'; import { ClassName } from './modal-options.class'; export class ModalBackdropOptions { public animate:boolean = true; public
(options:ModalBackdropOptions) { Object.assign(this, options); } } /** This component will be added as background layout for modals if enabled */ @Component({ selector: 'bs-modal-backdrop', template: '', // tslint:disable-next-line host: {'class': ClassName.BACKDROP} }) export class ModalBackdropComponen...
constructor
identifier_name
OeDataTime.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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, incl...
}); // Metadata, describes the data columns, and provides the visual with hints // so it can decide how to best represent the data var dataViewMetadata: powerbi.DataViewMetadata = { columns: [ { displayN...
var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value)); return powerbi.data.createDataViewScopeIdentity(expr);
random_line_split
OeDataTime.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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, incl...
public getDataViews(): DataView[] { var fieldExpr = powerbi.data.SQExprBuilder.fieldDef({ schema: 's', entity: "table1", column: "country" }); var dataStartYear = 1980; var years = _.range(2010, 2021); //var categoryValues = ["Australia", "Canada", "France", "...
{ super(); console.log(variables[0].Sector); }
identifier_body
OeDataTime.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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, incl...
extends SampleDataViews implements ISampleDataViewsMethods { public name: string = "OE Data (time series)"; public displayName: string = "OE Data (time series)"; public visuals: string[] = ['default']; //private sampleData = [ // [742731.43, 162066.43, 283085.78, 300263.49...
OeDataTime
identifier_name
srp.ts
import * as BigNum from 'bignum'; import * as crypto from 'crypto'; import { SRPConfiguration } from './configurations'; export class SecureRemotePassword { private multiplier: BigNum; private privateKey: BigNum; private passwordVerifier: BigNum; private clientPublicKey: BigNum; private clientProo...
return BigNum.fromBuffer(hash.digest()); } }
{ const item = args[i]; if (Buffer.isBuffer(item) || typeof item === 'string') { hash.update(item); } else { hash.update(item.toBuffer()); } }
conditional_block
srp.ts
import * as BigNum from 'bignum'; import * as crypto from 'crypto'; import { SRPConfiguration } from './configurations'; export class SecureRemotePassword { private multiplier: BigNum; private privateKey: BigNum; private passwordVerifier: BigNum; private clientPublicKey: BigNum; private clientProo...
this.passwordVerifier = configuration.generator.powm(this.privateKey, configuration.safePrime); this.serverPrivateKey = BigNum.fromBuffer(priv); } setClientPublicKey(clientPublicKey: Buffer) { this.clientPublicKey = BigNum.fromBuffer(clientPublicKey); } getServerPublicKey(): B...
private configuration: SRPConfiguration, priv: Buffer) { const size = configuration.safePrime.bitLength() / 8; this.multiplier = this.hash(configuration.safePrime, configuration.generator.toBuffer({ endian: 'big', size })); this.privateKey = this.hash(salt, this.hash(`${username...
random_line_split
srp.ts
import * as BigNum from 'bignum'; import * as crypto from 'crypto'; import { SRPConfiguration } from './configurations'; export class SecureRemotePassword { private multiplier: BigNum; private privateKey: BigNum; private passwordVerifier: BigNum; private clientPublicKey: BigNum; private clientProo...
(...args: (Buffer | string | BigNum)[]) { const hash = crypto.createHash(this.configuration.hashAlgorithm); for (let i = 0; i < args.length; i++) { const item = args[i]; if (Buffer.isBuffer(item) || typeof item === 'string') { hash.update(item); } el...
hash
identifier_name
mnist_model.py
""" CNN on mnist data using fluid api of paddlepaddle """ import paddle import paddle.fluid as fluid def mnist_cnn_model(img): """ Mnist cnn model Args: img(Varaible): the input image to be recognized Returns: Variable: the label prediction """ conv_pool_1 = fluid.nets.simple...
main()
conditional_block
mnist_model.py
""" CNN on mnist data using fluid api of paddlepaddle """ import paddle import paddle.fluid as fluid def mnist_cnn_model(img): """ Mnist cnn model Args: img(Varaible): the input image to be recognized Returns: Variable: the label prediction """ conv_pool_1 = fluid.nets.simple...
(): """ Train the cnn model on mnist datasets """ img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32') label = fluid.layers.data(name='label', shape=[1], dtype='int64') logits = mnist_cnn_model(img) cost = fluid.layers.cross_entropy(input=logits, label=label) avg_cost ...
main
identifier_name
mnist_model.py
""" CNN on mnist data using fluid api of paddlepaddle """ import paddle import paddle.fluid as fluid def mnist_cnn_model(img):
filter_size=5, pool_size=2, pool_stride=2, act='relu') fc = fluid.layers.fc(input=conv_pool_2, size=50, act='relu') logits = fluid.layers.fc(input=fc, size=10, act='softmax') return logits def main(): """ Train the cnn model on mnist datasets """ img = flu...
""" Mnist cnn model Args: img(Varaible): the input image to be recognized Returns: Variable: the label prediction """ conv_pool_1 = fluid.nets.simple_img_conv_pool( input=img, num_filters=20, filter_size=5, pool_size=2, pool_stride=2, ...
identifier_body
mnist_model.py
""" CNN on mnist data using fluid api of paddlepaddle """ import paddle import paddle.fluid as fluid def mnist_cnn_model(img): """ Mnist cnn model Args: img(Varaible): the input image to be recognized Returns: Variable: the label prediction """ conv_pool_1 = fluid.nets.simple...
paddle.dataset.mnist.train(), buf_size=500), batch_size=BATCH_SIZE) # use CPU place = fluid.CPUPlace() # use GPU # place = fluid.CUDAPlace(0) exe = fluid.Executor(place) feeder = fluid.DataFeeder(feed_list=[img, label], place=place) exe.run(fluid.default_startup_program(...
ACC_THRESHOLD = 0.98 LOSS_THRESHOLD = 10.0 train_reader = paddle.batch( paddle.reader.shuffle(
random_line_split
FactoryReset.py
from Screens.MessageBox import MessageBox from boxbranding import getMachineBrand, getMachineName from Screens.ParentalControlSetup import ProtectedScreen from Components.config import config from Tools.BoundFunction import boundFunction from Screens.InputBox import PinInput class FactoryReset(MessageBox, ProtectedScr...
def pinEntered(self, result): if result is None: self.closeProtectedScreen() elif not result: self.session.openWithCallback(self.close(), MessageBox, _("The pin code you entered is wrong."), MessageBox.TYPE_ERROR, timeout=3) def closeProtectedScreen(self, result=None): self.close(None)
def isProtected(self): return config.ParentalControl.setuppinactive.value and (not config.ParentalControl.config_sections.main_menu.value or hasattr(self.session, 'infobar') and self.session.infobar is None) and config.ParentalControl.config_sections.manufacturer_reset.value
random_line_split
FactoryReset.py
from Screens.MessageBox import MessageBox from boxbranding import getMachineBrand, getMachineName from Screens.ParentalControlSetup import ProtectedScreen from Components.config import config from Tools.BoundFunction import boundFunction from Screens.InputBox import PinInput class FactoryReset(MessageBox, ProtectedScr...
elif not result: self.session.openWithCallback(self.close(), MessageBox, _("The pin code you entered is wrong."), MessageBox.TYPE_ERROR, timeout=3) def closeProtectedScreen(self, result=None): self.close(None)
self.closeProtectedScreen()
conditional_block
FactoryReset.py
from Screens.MessageBox import MessageBox from boxbranding import getMachineBrand, getMachineName from Screens.ParentalControlSetup import ProtectedScreen from Components.config import config from Tools.BoundFunction import boundFunction from Screens.InputBox import PinInput class FactoryReset(MessageBox, ProtectedScr...
def isProtected(self): return config.ParentalControl.setuppinactive.value and (not config.ParentalControl.config_sections.main_menu.value or hasattr(self.session, 'infobar') and self.session.infobar is None) and config.ParentalControl.config_sections.manufacturer_reset.value def pinEntered(self, result): if re...
MessageBox.__init__(self, session, _("When you do a factory reset, you will lose ALL your configuration data\n" "(including bouquets, services, satellite data ...)\n" "After completion of factory reset, your %s %s will restart automatically!\n\n" "Really do a factory reset?") % (getMachineBrand(), getMachineNa...
identifier_body
FactoryReset.py
from Screens.MessageBox import MessageBox from boxbranding import getMachineBrand, getMachineName from Screens.ParentalControlSetup import ProtectedScreen from Components.config import config from Tools.BoundFunction import boundFunction from Screens.InputBox import PinInput class FactoryReset(MessageBox, ProtectedScr...
(self): return config.ParentalControl.setuppinactive.value and (not config.ParentalControl.config_sections.main_menu.value or hasattr(self.session, 'infobar') and self.session.infobar is None) and config.ParentalControl.config_sections.manufacturer_reset.value def pinEntered(self, result): if result is None: s...
isProtected
identifier_name
test_run.py
import tempfile import shutil import sys from unittest import mock import pytest from tools.wpt import run from tools import localpaths # noqa: F401 from wptrunner.browsers import product_list @pytest.fixture(scope="module") def
(): from tools.wpt import virtualenv class Virtualenv(virtualenv.Virtualenv): def __init__(self): self.path = tempfile.mkdtemp() self.skip_virtualenv_setup = False def create(self): return def activate(self): return def start(se...
venv
identifier_name
test_run.py
import tempfile import shutil import sys from unittest import mock import pytest from tools.wpt import run from tools import localpaths # noqa: F401 from wptrunner.browsers import product_list @pytest.fixture(scope="module") def venv(): from tools.wpt import virtualenv class Virtualenv(virtualenv.Virtuale...
run.setup_wptrunner(venv, **kwargs)
kwargs["sauce_browser"] = "firefox" kwargs["sauce_version"] = "63"
conditional_block
test_run.py
import tempfile import shutil import sys from unittest import mock import pytest from tools.wpt import run from tools import localpaths # noqa: F401 from wptrunner.browsers import product_list @pytest.fixture(scope="module") def venv(): from tools.wpt import virtualenv class Virtualenv(virtualenv.Virtuale...
def install(self, *requirements): return def install_requirements(self, requirements_path): return venv = Virtualenv() yield venv shutil.rmtree(venv.path) @pytest.fixture(scope="module") def logger(): run.setup_logging({}) @pytest.mark.parametrize("platform...
return
random_line_split
test_run.py
import tempfile import shutil import sys from unittest import mock import pytest from tools.wpt import run from tools import localpaths # noqa: F401 from wptrunner.browsers import product_list @pytest.fixture(scope="module") def venv(): from tools.wpt import virtualenv class Virtualenv(virtualenv.Virtuale...
def create(self): return def activate(self): return def start(self): return def install(self, *requirements): return def install_requirements(self, requirements_path): return venv = Virtualenv() yield venv...
self.path = tempfile.mkdtemp() self.skip_virtualenv_setup = False
identifier_body
gruntfile.js
/* global module, require */ module.exports = function (grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), banner: '/*!\n * <%= pkg.name %> - <%= pkg.description %>\n' + ' * Copyright (c) 2010 <%= pkg.author.name %> <<%= pkg.author.email %>>\n' + ...
}, watch: { configFile: '<%= jshint.karmafile.src %>', browsers: ['Firefox'], background: true, singleRun: false, reporters: ['mocha', 'coverage'] } }, watch: { gruntfile: { ...
unit: { configFile: '<%= jshint.karmafile.src %>', browsers: ['Firefox']
random_line_split
dimension.py
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # # 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...
else: setattr(self, name, value)
self[self._name] = [value]
conditional_block
dimension.py
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # # 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...
# The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOS...
# tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: #
random_line_split
dimension.py
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # # 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...
(self, name, value, connection): if name == 'Name': self._name = value elif name == 'Value': if self._name in self: self[self._name].append(value) else: self[self._name] = [value] else: setattr(self, name, value)
endElement
identifier_name
dimension.py
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # # 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...
def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connection): if name == 'Name': self._name = value elif name == 'Value': if self._name in self: self[self._name].append(value) else: se...
identifier_body
index.d.ts
qf> // pofider <https://github.com/pofider> // Keith Kikta <https://github.com/newbish> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="node" /> import * as fs from 'fs'; declare namespace JsReport { type Helpers ...
max: number; enabled: boolean; }; }; store?: { provider?: ReporterOptionsStoreProvider; }; blobStorge?: { provider?: ReporterOptionsBlobStorageProvider; }; extensions?: any; extensionsList?: strin...
templateCache?: {
random_line_split
tags-repository.ts
import { uniqBy } from 'ramda'; import Transactor from '../utils/transactor'; import GitRepository from './git-repository'; const TagsFile = 'tags.json'; export default class TagsRepository { constructor(private _gitTransactionManager: Transactor<GitRepository>)
async getTags() { return await this._gitTransactionManager.with(async gitRepo => JSON.parse(await gitRepo.readFile(TagsFile))); } async mergeTags(tagsToSave, author) { return await this._gitTransactionManager.write(async gitRepo => { const currentTags = JSON.parse(await gitRepo.readFile(TagsFile)...
{}
identifier_body
tags-repository.ts
import { uniqBy } from 'ramda'; import Transactor from '../utils/transactor'; import GitRepository from './git-repository'; const TagsFile = 'tags.json'; export default class TagsRepository {
async mergeTags(tagsToSave, author) { return await this._gitTransactionManager.write(async gitRepo => { const currentTags = JSON.parse(await gitRepo.readFile(TagsFile)); const changedTags = tagsToSave.map(x => ({ name: x })); const newTags = uniqBy(x => x.name, [...currentTags, ...changedTags]...
constructor(private _gitTransactionManager: Transactor<GitRepository>) {} async getTags() { return await this._gitTransactionManager.with(async gitRepo => JSON.parse(await gitRepo.readFile(TagsFile))); }
random_line_split
tags-repository.ts
import { uniqBy } from 'ramda'; import Transactor from '../utils/transactor'; import GitRepository from './git-repository'; const TagsFile = 'tags.json'; export default class TagsRepository {
(private _gitTransactionManager: Transactor<GitRepository>) {} async getTags() { return await this._gitTransactionManager.with(async gitRepo => JSON.parse(await gitRepo.readFile(TagsFile))); } async mergeTags(tagsToSave, author) { return await this._gitTransactionManager.write(async gitRepo => { c...
constructor
identifier_name
parser_utils.rs
use std::collections::LinkedList; use std::iter::Iterator; use std::vec::Vec; use lexer::Token; use interpreter::ProgramStore; use interpreter::FunctionInfo; /// This function filters out comments and doubled newlines /// It also registers the functions with the program store pub fn filter_pass(tokens: Vec<Token>, m...
} else { return Err(format!("expected function name but found {:?}", next_token)); } } } // simply copy all other tokens _ => { output_tokens.push(token.clone()); tok_it.n...
program = try!(program.add_function(name.clone(), FunctionInfo::named_new(name)));
random_line_split
parser_utils.rs
use std::collections::LinkedList; use std::iter::Iterator; use std::vec::Vec; use lexer::Token; use interpreter::ProgramStore; use interpreter::FunctionInfo; /// This function filters out comments and doubled newlines /// It also registers the functions with the program store pub fn filter_pass(tokens: Vec<Token>, m...
(tokens: Vec<Token>) -> Result<LinkedList<Vec<Token>>, String> { let mut tok_it = tokens.into_iter(); let mut block = Vec::new(); let mut block_list = LinkedList::new(); while let Some(token) = tok_it.next() { match token { Token::Define => { if block.len() != 0 && b...
blockify_pass
identifier_name
parser_utils.rs
use std::collections::LinkedList; use std::iter::Iterator; use std::vec::Vec; use lexer::Token; use interpreter::ProgramStore; use interpreter::FunctionInfo; /// This function filters out comments and doubled newlines /// It also registers the functions with the program store pub fn filter_pass(tokens: Vec<Token>, m...
Ok(block_list) }
{ let mut tok_it = tokens.into_iter(); let mut block = Vec::new(); let mut block_list = LinkedList::new(); while let Some(token) = tok_it.next() { match token { Token::Define => { if block.len() != 0 && block[0] == Token::Define { block_list.push_...
identifier_body