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
windowproxy.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::WindowProxyBinding; use dom::bindings::js::JS; use dom::bindings::utils::{Reflectable,...
{ reflector_: Reflector } impl WindowProxy { pub fn new(owner: &JS<Window>) -> JS<WindowProxy> { let proxy = ~WindowProxy { reflector_: Reflector::new() }; reflect_dom_object(proxy, owner, WindowProxyBinding::Wrap) } } impl Reflectable for WindowProxy { fn reflecto...
WindowProxy
identifier_name
windowproxy.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::WindowProxyBinding; use dom::bindings::js::JS; use dom::bindings::utils::{Reflectable,...
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } }
{ &self.reflector_ }
identifier_body
peas.js
// // peas.js // // tree data structure in javascript // ////////////////////////// var peas = function() { // "sub" here is used as an object container for // operations related to sub nodes. // Each pea node will have a "sub" property // with an instance of "sub" var sub = function() {} // the current node...
} /////////////////////////// // constructor function for pea nodes peas = function( item ) { this.sub = new sub() this.sub.pea = this this.item = item } peas.prototype.item = null // top node peas.prototype.top = null // prev peas.prototype.prev = null // next peas.prototype.next = null...
{ action( node ) node = node.next }
conditional_block
peas.js
// // peas.js // // tree data structure in javascript // ////////////////////////// var peas = function() { // "sub" here is used as an object container for // operations related to sub nodes. // Each pea node will have a "sub" property // with an instance of "sub" var sub = function() {} // the current node...
if( index == this.pea.sub.n ) { this.pea.add( spare ) return } pik = this.pea.sub.at( index ) spare.prev = pik.prev spare.next = pik // if not inserting at first if( pik.prev ) { pik.prev.next = spare } else { // inserting as first pik.top.sub.first = spare } pik.prev = spare ...
// if insert at last+1, then just add
random_line_split
test_schemas_csl.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later v...
def test_type(db, minimal_record, recid_pid): """"Test type.""" minimal_record.update({ 'resource_type': {'type': 'publication', 'subtype': 'thesis'} }) obj = csl_v1.transform_record(recid_pid, Record(minimal_record)) assert obj['type'] == 'thesis' minimal_record.update({ 're...
"""Test minimal record.""" obj = csl_v1.transform_record(recid_pid, Record(minimal_record)) d = datetime.utcnow().date() assert obj == { 'id': '123', 'type': 'article', 'title': 'Test', 'abstract': 'My description', 'author': [ {'family': 'Test'}, ...
identifier_body
test_schemas_csl.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later v...
(db, minimal_record, recid_pid): """Test journal record.""" minimal_record['part_of'] = { 'title': 'Conference proceedings title', 'pages': '10-20', } minimal_record['imprint'] = { 'publisher': 'The Good Publisher', 'place': 'Somewhere', } obj = csl_v1.transform_r...
test_part_of
identifier_name
test_schemas_csl.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later v...
from datetime import datetime from invenio_records.api import Record from zenodo.modules.records.serializers import csl_v1 def test_minimal(db, minimal_record, recid_pid): """Test minimal record.""" obj = csl_v1.transform_record(recid_pid, Record(minimal_record)) d = datetime.utcnow().date() assert...
from __future__ import absolute_import, print_function
random_line_split
trendline.src.js
/** * @license Highstock JS v8.1.0 (2020-05-05) * * Indicator series type for Highstock * * (c) 2010-2019 Sebastian Bochan * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.e...
_registerModule(_modules, 'indicators/trendline.src.js', [_modules['parts/Utilities.js']], function (U) { /* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var isAr...
{ if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } }
identifier_body
trendline.src.js
/** * @license Highstock JS v8.1.0 (2020-05-05) * * Indicator series type for Highstock * * (c) 2010-2019 Sebastian Bochan * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.e...
else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); ...
{ define('highcharts/indicators/trendline', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); }
conditional_block
trendline.src.js
/** * @license Highstock JS v8.1.0 (2020-05-05) * * Indicator series type for Highstock * * (c) 2010-2019 Sebastian Bochan * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.e...
(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'indicators/trendline.src.js', [_modules['parts/Utilities.js']], function (U) { /* * * * License: www.highcharts.com/license * ...
_registerModule
identifier_name
trendline.src.js
/** * @license Highstock JS v8.1.0 (2020-05-05) * * Indicator series type for Highstock * * (c) 2010-2019 Sebastian Bochan * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.e...
* @private * @class * @name Highcharts.seriesTypes.trendline * * @augments Highcharts.Series */ seriesType('trendline', 'sma', /** * Trendline (linear regression) fits a straight line to the selected data * using a method called th...
random_line_split
min_const_unsafe_fn_libstd_stability2.rs
// Copyright 2018 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 ...
//~ ERROR can only call other `min_const_fn` // check whether this function cannot be called even with the feature gate active #[unstable(feature = "foo2", issue="0")] const fn foo2_gated() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn const unsafe fn bar2_gated() -> u32 ...
{ foo2() }
identifier_body
min_const_unsafe_fn_libstd_stability2.rs
// Copyright 2018 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 ...
const fn foo() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] // can't call non-min_const_fn const unsafe fn bar() -> u32 { foo() } //~ ERROR can only call other `min_const_fn` #[unstable(feature = "rust1", issue="0")] const fn foo2() -> u32 { 42 } #[stable(feature = "rust1", since = "1.0.0")] // can't ...
random_line_split
min_const_unsafe_fn_libstd_stability2.rs
// Copyright 2018 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 ...
() {}
main
identifier_name
vege-table-leaf.js
/* globals Polymer:false, console:false */ 'use strict'; Polymer('vege-table-leaf', { value: null, stringValue: null, type: '', specialType: true, specialTypes: ['json', 'html', 'xml', 'url', 'object', 'image', 'element', 'counts'], typeChanged: function() { this.specialType = (this.specialTypes.index...
}, convert: function() { if (this.value === null || this.value === undefined) { return null; } switch (this.type) { //case 'json': //return JSON.stringify(this.value, null, ' '); case 'number': return Math.round(this.value); case 'list': return this.value ?...
{ this.$.element.innerHTML = ''; this.$.element.appendChild(this.stringValue); }
conditional_block
vege-table-leaf.js
/* globals Polymer:false, console:false */ 'use strict'; Polymer('vege-table-leaf', { value: null, stringValue: null, type: '', specialType: true, specialTypes: ['json', 'html', 'xml', 'url', 'object', 'image', 'element', 'counts'], typeChanged: function() { this.specialType = (this.specialTypes.index...
var attributes = this.value[1]; Object.keys(attributes).forEach(function(key) { element[key] = attributes[key]; }); return element; //case 'url': //return this.value.href; //this.$.element.appendChild(element); //return; //var blob = new Blob([div.innerH...
case 'element': var element = document.createElement(this.value[0]);
random_line_split
__init__.py
""" Tools for sending email. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module # Imported for backwards compatibility, and for the sake # of a cleaner namespace. These symbols used to be in # django/core/mail.py before the int...
mail.send(fail_silently=fail_silently) class SMTPConnection(_SMTPConnection): def __init__(self, *args, **kwds): import warnings warnings.warn( 'mail.SMTPConnection is deprecated; use mail.get_connection() instead.', DeprecationWarning ) super(SMTPConne...
mail.attach_alternative(html_message, 'text/html')
conditional_block
__init__.py
""" Tools for sending email. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module # Imported for backwards compatibility, and for the sake # of a cleaner namespace. These symbols used to be in # django/core/mail.py before the int...
(subject, message, fail_silently=False, connection=None, html_message=None): """Sends a message to the admins, as defined by the ADMINS setting.""" if not settings.ADMINS: return mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message...
mail_admins
identifier_name
__init__.py
""" Tools for sending email. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module # Imported for backwards compatibility, and for the sake # of a cleaner namespace. These symbols used to be in # django/core/mail.py before the int...
'mail.SMTPConnection is deprecated; use mail.get_connection() instead.', DeprecationWarning ) super(SMTPConnection, self).__init__(*args, **kwds)
random_line_split
__init__.py
""" Tools for sending email. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module # Imported for backwards compatibility, and for the sake # of a cleaner namespace. These symbols used to be in # django/core/mail.py before the int...
def send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Given a datatuple of (subject, message, from_email, recipient_list), sends each message to each recipient list. Returns the number of e-mails sent. If from_email is None, t...
""" Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this...
identifier_body
cc_keys_to_console.py
# vi: ts=4 expandtab # # Copyright (C) 2011 Canonical Ltd. # Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # # Author: Scott Moser <scott.moser@canonical.com> # Author: Juerg Haefliger <juerg.haefliger@hp.com> # # This program is free software: you can redistribute it and/or modify # it...
def handle(name, cfg, cloud, log, _args): helper_path = _get_helper_tool_path(cloud.distro) if not os.path.exists(helper_path): log.warn(("Unable to activate module %s," " helper tool not found at %s"), name, helper_path) return fp_blacklist = util.get_cfg_option_list(c...
try: base_lib = distro.usr_lib_exec except AttributeError: base_lib = '/usr/lib' return HELPER_TOOL_TPL % base_lib
identifier_body
cc_keys_to_console.py
# vi: ts=4 expandtab # # Copyright (C) 2011 Canonical Ltd. # Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # # Author: Scott Moser <scott.moser@canonical.com> # Author: Juerg Haefliger <juerg.haefliger@hp.com> # # This program is free software: you can redistribute it and/or modify # it...
fp_blacklist = util.get_cfg_option_list(cfg, "ssh_fp_console_blacklist", []) key_blacklist = util.get_cfg_option_list(cfg, "ssh_key_console_blacklist", ["ssh-dss"]) try: ...
log.warn(("Unable to activate module %s," " helper tool not found at %s"), name, helper_path) return
conditional_block
cc_keys_to_console.py
# vi: ts=4 expandtab # # Copyright (C) 2011 Canonical Ltd. # Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # # Author: Scott Moser <scott.moser@canonical.com> # Author: Juerg Haefliger <juerg.haefliger@hp.com> # # This program is free software: you can redistribute it and/or modify # it...
(name, cfg, cloud, log, _args): helper_path = _get_helper_tool_path(cloud.distro) if not os.path.exists(helper_path): log.warn(("Unable to activate module %s," " helper tool not found at %s"), name, helper_path) return fp_blacklist = util.get_cfg_option_list(cfg, ...
handle
identifier_name
cc_keys_to_console.py
# vi: ts=4 expandtab # # Copyright (C) 2011 Canonical Ltd. # Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# Author: Juerg Haefliger <juerg.haefliger@hp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful,...
# # Author: Scott Moser <scott.moser@canonical.com>
random_line_split
tests.py
#* PYTHON EMAIL PROJECT *# #* tests.py *# #* Fordham CSS September 25 *# #* ------------------------------------ *# #* Unit tests for PyDate program *# from Email_Object import Email from Get_Emails import Set_Priority import unittest # Unit Tests for Set_Priorit...
unittest.main()
conditional_block
tests.py
#* PYTHON EMAIL PROJECT *# #* tests.py *# #* Fordham CSS September 25 *# #* ------------------------------------ *# #* Unit tests for PyDate program *# from Email_Object import Email from Get_Emails import Set_Priority import unittest # Unit Tests for Set_Priorit...
hi,lo = Set_Priority(EMAILS) self.assertEqual(len(hi),1) self.assertFalse(lo) # Test subject check def test_high_subject(self): email = Email('test@test.com', '', 'Important', '', '') EMAILS = [email] hi,lo = Set_Priority(EMAILS) self.assertEqual(len(hi),1) ...
email = Email('test@fordham.edu', '', 'Blah', '', '') EMAILS = [email]
random_line_split
tests.py
#* PYTHON EMAIL PROJECT *# #* tests.py *# #* Fordham CSS September 25 *# #* ------------------------------------ *# #* Unit tests for PyDate program *# from Email_Object import Email from Get_Emails import Set_Priority import unittest # Unit Tests for Set_Priorit...
def test_low_default(self): email = Email('test@test.com', '', 'None', '', '') EMAILS = [email] hi,lo = Set_Priority(EMAILS) self.assertEqual(len(lo),1) self.assertFalse(hi) # Test Multiple cases def test_multi_cases(self): #Important by sender email_sender = Email('...
def test_high_domain(self): email = Email('test@fordham.edu', '', 'Blah', '', '') EMAILS = [email] hi,lo = Set_Priority(EMAILS) self.assertEqual(len(hi),1) self.assertFalse(lo) # Test subject check def test_high_subject(self): email = Email('test@test.com', '', 'I...
identifier_body
tests.py
#* PYTHON EMAIL PROJECT *# #* tests.py *# #* Fordham CSS September 25 *# #* ------------------------------------ *# #* Unit tests for PyDate program *# from Email_Object import Email from Get_Emails import Set_Priority import unittest # Unit Tests for Set_Priorit...
(self): #Important by sender email_sender = Email('test@fordham.edu', '', 'Blah', '', '') #Important by subject email_subject = Email('test@test.com', '', 'Important', '', '') #Not Important email_lo = Email('test@test.com', '', 'None', '', '') EMAILS = [email_sende...
test_multi_cases
identifier_name
f31-sigtstp-handler.rs
/// Figure 10.31 How to handle SIGTSTP /// /// Added a println to sig_tstp to show that the signal /// is really caught #[macro_use(as_void)] extern crate apue; extern crate libc; use std::mem::uninitialized; use std::ptr::null_mut; use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO}...
() { unsafe { if signal(SIGTSTP, SIG_IGN) == SIG_DFL { signal(SIGTSTP, sig_tstp as usize); } let buf = vec![0; BUFFSIZE]; while let Ok(n) = read(STDIN_FILENO, as_void!(buf), BUFFSIZE).check_positive() { if write(STDOUT_FILENO, as_void!(buf), n as _) != n { ...
main
identifier_name
f31-sigtstp-handler.rs
/// Figure 10.31 How to handle SIGTSTP /// /// Added a println to sig_tstp to show that the signal /// is really caught #[macro_use(as_void)] extern crate apue; extern crate libc; use std::mem::uninitialized; use std::ptr::null_mut; use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO}...
fn main() { unsafe { if signal(SIGTSTP, SIG_IGN) == SIG_DFL { signal(SIGTSTP, sig_tstp as usize); } let buf = vec![0; BUFFSIZE]; while let Ok(n) = read(STDIN_FILENO, as_void!(buf), BUFFSIZE).check_positive() { if write(STDOUT_FILENO, as_void!(buf), n as _) !...
{ // move cursor to lower left corner, reset tty mode // unblock SIGTSTP, since it's blocked while we're reading it println!("last cleanup before SIGTSTP"); let mut mask = uninitialized(); sigemptyset(&mut mask); sigaddset(&mut mask, SIGTSTP); sigprocmask(SIG_UNBLOCK, &mask, null_mut()); ...
identifier_body
f31-sigtstp-handler.rs
/// Figure 10.31 How to handle SIGTSTP /// /// Added a println to sig_tstp to show that the signal /// is really caught #[macro_use(as_void)] extern crate apue; extern crate libc; use std::mem::uninitialized; use std::ptr::null_mut; use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO}...
let buf = vec![0; BUFFSIZE]; while let Ok(n) = read(STDIN_FILENO, as_void!(buf), BUFFSIZE).check_positive() { if write(STDOUT_FILENO, as_void!(buf), n as _) != n { err_sys("write error"); } } } }
{ signal(SIGTSTP, sig_tstp as usize); }
conditional_block
f31-sigtstp-handler.rs
/// Figure 10.31 How to handle SIGTSTP /// /// Added a println to sig_tstp to show that the signal /// is really caught #[macro_use(as_void)] extern crate apue; extern crate libc; use std::mem::uninitialized;
use std::ptr::null_mut; use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO}; use libc::{sigemptyset, sigaddset, signal, kill, getpid, read, write}; use apue::my_libc::sigprocmask; use apue::{LibcResult, err_sys}; const BUFFSIZE: usize = 1024; unsafe fn sig_tstp(_: c_int) { // mo...
random_line_split
cleanup.py
#!/usr/bin/env python3 import os import sys import redis app_path = os.path.realpath('%s/../../..' % os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, '%s/lib' % app_path) import settings def get_db(conf): return redis.StrictRedis(host=conf['host'], port=int(conf['port']), db=int(conf['id'])) i...
db.delete(key) print(('deleted: %s' % key)) i += 1 print(('Finished deleting %d keys' % i))
import argparse argparser = argparse.ArgumentParser(description="RedisDB clean-up utility") argparser.add_argument('clean_what', metavar="ACTION", help="what item group should be cleaned (session, concordance)") args = argparser.parse_args() patterns = { 'session': '...
conditional_block
cleanup.py
#!/usr/bin/env python3 import os import sys import redis app_path = os.path.realpath('%s/../../..' % os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, '%s/lib' % app_path) import settings def get_db(conf):
if __name__ == '__main__': import argparse argparser = argparse.ArgumentParser(description="RedisDB clean-up utility") argparser.add_argument('clean_what', metavar="ACTION", help="what item group should be cleaned (session, concordance)") args = argparser.parse_args() ...
return redis.StrictRedis(host=conf['host'], port=int(conf['port']), db=int(conf['id']))
identifier_body
cleanup.py
#!/usr/bin/env python3 import os import sys import redis app_path = os.path.realpath('%s/../../..' % os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, '%s/lib' % app_path) import settings def
(conf): return redis.StrictRedis(host=conf['host'], port=int(conf['port']), db=int(conf['id'])) if __name__ == '__main__': import argparse argparser = argparse.ArgumentParser(description="RedisDB clean-up utility") argparser.add_argument('clean_what', metavar="ACTION", help...
get_db
identifier_name
cleanup.py
#!/usr/bin/env python3 import os import sys import redis app_path = os.path.realpath('%s/../../..' % os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, '%s/lib' % app_path) import settings def get_db(conf): return redis.StrictRedis(host=conf['host'], port=int(conf['port']), db=int(conf['id'])) i...
db = get_db(settings.get('plugins', 'db')) keys = db.keys(patterns[args.clean_what]) i = 0 for key in keys: db.delete(key) print(('deleted: %s' % key)) i += 1 print(('Finished deleting %d keys' % i))
random_line_split
modules_handler.py
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
(self): values = {'modules': self.dispatcher.modules} self.response.write(self.render('modules.html', values))
get
identifier_name
modules_handler.py
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def get(self): values = {'modules': self.dispatcher.modules} self.response.write(self.render('modules.html', values))
identifier_body
main.py
import sys import re def decompress(data):
decompressed = "" d = ''.join(data.split('\n')) while len(d): s = re.match(r'^.*?(\((\d+?)x(\d+?)\))(.*)', d) if s is None: decompressed += d break dec, marker, d = d.partition(s.group(1)) decompressed += dec for i in range(int(s.group(3))): ...
random_line_split
main.py
import sys import re def decompress(data): decompressed = "" d = ''.join(data.split('\n')) while len(d): s = re.match(r'^.*?(\((\d+?)x(\d+?)\))(.*)', d) if s is None: decompressed += d break dec, marker, d = d.partition(s.group(1)) decompressed += dec...
d = d[int(s.group(2)):] return decompressed def dec(d): length = 0 while len(d): s = re.match(r'^.*?(\((\d+?)x(\d+?)\))(.*)', d) if s is None: return length + len(d) decomp, marker, d = d.partition(s.group(1)) length += len(decomp) + int(s.group(3)) * de...
decompressed += d[:int(s.group(2))]
conditional_block
main.py
import sys import re def decompress(data): decompressed = "" d = ''.join(data.split('\n')) while len(d): s = re.match(r'^.*?(\((\d+?)x(\d+?)\))(.*)', d) if s is None: decompressed += d break dec, marker, d = d.partition(s.group(1)) decompressed += dec...
(): if (len(sys.argv) < 2): print("Usage python3 %s <input>" % sys.argv[0]) exit(-1) with open(sys.argv[1], 'r') as input: data = input.read() print("Char count:", len(decompress(data))) print("Char count:", full_decompress(data)) if __name__ == '__main__': main()
main
identifier_name
main.py
import sys import re def decompress(data): decompressed = "" d = ''.join(data.split('\n')) while len(d): s = re.match(r'^.*?(\((\d+?)x(\d+?)\))(.*)', d) if s is None: decompressed += d break dec, marker, d = d.partition(s.group(1)) decompressed += dec...
def main(): if (len(sys.argv) < 2): print("Usage python3 %s <input>" % sys.argv[0]) exit(-1) with open(sys.argv[1], 'r') as input: data = input.read() print("Char count:", len(decompress(data))) print("Char count:", full_decompress(data)) if __name__ == '__main__': main()
length = 0 d = ''.join(data.split('\n')) return dec(d)
identifier_body
voting.py
#!/usr/bin/python from commands.utilities import register import asyncio import re class Voting(): def __init__(self, config=None): # regex to match a number at the start of the message. # Being a float is optional. self.length_re = r'--((\d*)?(\.\d*)?)' # regex to atch and capture...
# start at the second index to avoid the -- at the start # of the time parameter. vote_length = float(matched_length[2:]) else: vote_length = self.vote_length # Check if the user supplied extra parameters regex_result = self.apply_regex(msg, self....
if regex_result: msg, matched_length = regex_result
random_line_split
voting.py
#!/usr/bin/python from commands.utilities import register import asyncio import re class Voting(): def __init__(self, config=None): # regex to match a number at the start of the message. # Being a float is optional. self.length_re = r'--((\d*)?(\.\d*)?)' # regex to atch and capture...
(self, msg, user, channel, client, *args, **kwargs): ''' Main function that handles the vote function. Makes sure that only vote is going at a time in a channel. Calls from a channel that has a vote going on are considered to be a vote for the ongoing vote. dict entry: ...
start_vote
identifier_name
voting.py
#!/usr/bin/python from commands.utilities import register import asyncio import re class Voting(): def __init__(self, config=None): # regex to match a number at the start of the message. # Being a float is optional. self.length_re = r'--((\d*)?(\.\d*)?)' # regex to atch and capture...
msg, extra_options = regex_result # remove square brackets, split on comma and strip whitespace extra_options = extra_options.replace('[', '').replace(']', '') options = extra_options.lower().split(',') options = [word.strip() for word in options] ...
''' Parses the supplied message to determine the vote length and supplied parameteres(if any). Expected vote format: !vote[--time] String of the vote [[parameter1, parm2]] ''' # Check if the user supplied a length regex_result = self.apply_regex(msg, self.len...
identifier_body
voting.py
#!/usr/bin/python from commands.utilities import register import asyncio import re class Voting(): def __init__(self, config=None): # regex to match a number at the start of the message. # Being a float is optional. self.length_re = r'--((\d*)?(\.\d*)?)' # regex to atch and capture...
error_str = 'Invalid vote option %s. ' % user error_str += 'The options are ' + str(tuple(valid_options.keys())) return error_str
conditional_block
passport.js
const passport = require('passport'); const JwtStrategy = require('passport-jwt').Strategy; const { ExtractJwt } = require('passport-jwt'); const LocalStrategy = require('passport-local'); const { JWT_SECRET } = require('./configuration'); const User = require('./models/user') //Se busca al usuraio que tenga el token ...
//check if the password is correct. const isMatch = await user.isValidPassword(password); //if not, handle it if(!isMatch){ return done(null, false,{ message: 'Incorrecto Password.' }); } //otherwise, return the user. done(null, user); }catch(error){ done(error,false); } }));
{ return done(null, false, { message: 'Incorrect username.' }); }
conditional_block
passport.js
const passport = require('passport'); const JwtStrategy = require('passport-jwt').Strategy; const { ExtractJwt } = require('passport-jwt'); const LocalStrategy = require('passport-local'); const { JWT_SECRET } = require('./configuration'); const User = require('./models/user') //Se busca al usuraio que tenga el token ...
if(!user){ return done(null, false,{ "info": 'No tiene autorizacion de admin.' }); } // Retornar el usuario done(null, user); }catch(error){ done(error, false,{ "info": 'No se tiene autorizacion!!!!!' }); } })); // Verificacion de usuario por medio de email and password. //LOCAL STRATEGY passport.use(ne...
console.log('Se muestra al usuario token :', user); //Si el usuario no existe, lo tomara.
random_line_split
sound_engine.py
# # YetAnotherPythonSnake 0.94 # Author: Simone Cingano (simonecingano@gmail.com) # Web: http://simonecingano.it # Licence: MIT # import pygame import os # YASP common imports import data if pygame.mixer: pygame.mixer.init() class dummysound: def play(self): pass class SoundPlayer: def __init__(...
def load(self, key, filename): self.sounds[key] = self.load_sound(filename) def load_sound(self, filename): if not pygame.mixer: return dummysound() filepath = data.filepath("sfx", filename) if filepath: sound = pygame.mixer.Sound(filepath) r...
self.load(*s) def play(self, sound): self.sounds[sound].play()
random_line_split
sound_engine.py
# # YetAnotherPythonSnake 0.94 # Author: Simone Cingano (simonecingano@gmail.com) # Web: http://simonecingano.it # Licence: MIT # import pygame import os # YASP common imports import data if pygame.mixer: pygame.mixer.init() class dummysound: def play(self): pass class SoundPlayer: def __init__(...
def play(self): pygame.mixer.music.play(-1) def once(self): pygame.mixer.music.play() def stop(self): pygame.mixer.music.stop()
pygame.mixer.music.load(data.filepath("music", track + EXTENSION))
identifier_body
sound_engine.py
# # YetAnotherPythonSnake 0.94 # Author: Simone Cingano (simonecingano@gmail.com) # Web: http://simonecingano.it # Licence: MIT # import pygame import os # YASP common imports import data if pygame.mixer: pygame.mixer.init() class dummysound: def play(self): pass class SoundPlayer: def __init__(...
else: return dummysound() EXTENSION = os.name == 'nt' and '.mp3' or '.ogg' class MusicPlayer: def __init__(self, track=None): if track is not None: self.load(track) def load(self, track): pygame.mixer.music.load(data.filepath("music", track + EXTENSION)) ...
sound = pygame.mixer.Sound(filepath) return sound
conditional_block
sound_engine.py
# # YetAnotherPythonSnake 0.94 # Author: Simone Cingano (simonecingano@gmail.com) # Web: http://simonecingano.it # Licence: MIT # import pygame import os # YASP common imports import data if pygame.mixer: pygame.mixer.init() class dummysound: def play(self): pass class SoundPlayer: def __init__(...
(self): pygame.mixer.music.play(-1) def once(self): pygame.mixer.music.play() def stop(self): pygame.mixer.music.stop()
play
identifier_name
file.service.ts
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/forkJoin'; import {ApplicationStatusService} from '../application-status/application-status.service'; import {ImportedImage} from '../../model/imported-image'; import {Subscriber} from 'rxjs/Subscriber'; im...
/** * * @param array * @param acceptedImageFormat * @returns {boolean} */ static checkFilesMimeTypes(array: Array<File>, acceptedImageFormat: string): boolean { if (!acceptedImageFormat) { return false; } const formats = acceptedImageFormat.split(',').map(format => format.trim());...
{ const result: Array<File> = []; for (let i = 0; i < files.length; i++) { result.push(files[i]); } return result; }
identifier_body
file.service.ts
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/forkJoin'; import {ApplicationStatusService} from '../application-status/application-status.service'; import {ImportedImage} from '../../model/imported-image'; import {Subscriber} from 'rxjs/Subscriber'; im...
(private appStatusService: ApplicationStatusService) { } static fileListToArray(files: FileList): Array<File> { const result: Array<File> = []; for (let i = 0; i < files.length; i++) { result.push(files[i]); } return result; } /** * * @param array * @param acceptedImageFormat ...
constructor
identifier_name
file.service.ts
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/forkJoin'; import {ApplicationStatusService} from '../application-status/application-status.service'; import {ImportedImage} from '../../model/imported-image'; import {Subscriber} from 'rxjs/Subscriber'; im...
} ); return observable; } }
}, () => { this.appStatusService.addStatus(filesArray.length + ' new file(s) added');
random_line_split
file.service.ts
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/forkJoin'; import {ApplicationStatusService} from '../application-status/application-status.service'; import {ImportedImage} from '../../model/imported-image'; import {Subscriber} from 'rxjs/Subscriber'; im...
return result; } /** * * @param array * @param acceptedImageFormat * @returns {boolean} */ static checkFilesMimeTypes(array: Array<File>, acceptedImageFormat: string): boolean { if (!acceptedImageFormat) { return false; } const formats = acceptedImageFormat.split(',').map(fo...
{ result.push(files[i]); }
conditional_block
index.d.ts
// Type definitions for non-npm package amap-js-api-autocomplete 1.4 // Project: https://lbs.amap.com/api/javascript-api/reference/search#m_AMap.Autocomplete // Definitions by: breeze9527 <https://github.com/breeze9527> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <...
*/ search( keyword: string, callback: (status: Autocomplete.SearchStatus, result: Autocomplete.SearchResult | string) => void ): void; /** * 设置提示Poi类型,多个类型用“|”分隔 * @param type Poi类型 */ setType(type?: string): void; /** *...
回调
identifier_name
index.d.ts
// Type definitions for non-npm package amap-js-api-autocomplete 1.4 // Project: https://lbs.amap.com/api/javascript-api/reference/search#m_AMap.Autocomplete // Definitions by: breeze9527 <https://github.com/breeze9527> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <...
}
*/ getLang(): Lang | undefined; }
random_line_split
extract_lang.py
""" Created on Dec 19, 2014 @author: rgeorgi This script is used to point at a dump of the ODIN database and extract the specified language from it. """ # Built-in imports ------------------------------------------------------------- import argparse, re, logging import sys EXTR_LOG = logging.getLogger('LANG_EXTRACT...
args = p.parse_args() extract_lang(args.dir, args.lang, args.outfile)
random_line_split
extract_lang.py
""" Created on Dec 19, 2014 @author: rgeorgi This script is used to point at a dump of the ODIN database and extract the specified language from it. """ # Built-in imports ------------------------------------------------------------- import argparse, re, logging import sys EXTR_LOG = logging.getLogger('LANG_EXTRACT...
# And get the list of instances. instances = re.split('\n\n+', data) # Remove blank "instances" instances = [i for i in instances if i.strip()] # Now, for each instance, look for the language. for instance in instances[1:]: # <-- skip the first p...
i = 0 EXTR_LOG.info('Extracting language "%s" from ODIN...' % lang) # Iterate through each ".check" file in the given directory. try: matching_paths = matching_files(dir, '.*\.check$', recursive=True) except FileNotFoundError as fnfe: EXTR_LOG.critical("Path {} was not found.".format(di...
identifier_body
extract_lang.py
""" Created on Dec 19, 2014 @author: rgeorgi This script is used to point at a dump of the ODIN database and extract the specified language from it. """ # Built-in imports ------------------------------------------------------------- import argparse, re, logging import sys EXTR_LOG = logging.getLogger('LANG_EXTRACT...
(dir, lang, outfile, limit=None): i = 0 EXTR_LOG.info('Extracting language "%s" from ODIN...' % lang) # Iterate through each ".check" file in the given directory. try: matching_paths = matching_files(dir, '.*\.check$', recursive=True) except FileNotFoundError as fnfe: EXTR_LOG.crit...
extract_lang
identifier_name
extract_lang.py
""" Created on Dec 19, 2014 @author: rgeorgi This script is used to point at a dump of the ODIN database and extract the specified language from it. """ # Built-in imports ------------------------------------------------------------- import argparse, re, logging import sys EXTR_LOG = logging.getLogger('LANG_EXTRACT...
if limit and i == limit: break print("{} instances written.".format(i)) if __name__ == '__main__': p = argparse.ArgumentParser() p.add_argument('-c', '--config', type=configfile) p.add_argument('-d', '--dir', help="Path to the ODIN database directory.", required=True) p.add_arg...
break
conditional_block
i18n-inlining.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { BuilderContext } from '@angular-devkit/architect'; import { EmittedFiles } from '@angular-devkit/build-webpa...
}
return !hasErrors;
random_line_split
i18n-inlining.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { BuilderContext } from '@angular-devkit/architect'; import { EmittedFiles } from '@angular-devkit/build-webpa...
}; originalFiles.push(originalPath); try { const originalMapPath = originalPath + '.map'; action.map = fs.readFileSync(originalMapPath, 'utf8'); originalFiles.push(originalMapPath); } catch (err) { if (err.code !== 'ENOENT') { throw err; } } options.push(a...
{ const options: InlineOptions[] = []; const originalFiles: string[] = []; for (const emittedFile of emittedFiles) { if ( emittedFile.asset || emittedFile.extension !== '.js' || (emittedFile.name && scriptsEntryPointName.includes(emittedFile.name)) ) { continue; } const or...
identifier_body
i18n-inlining.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { BuilderContext } from '@angular-devkit/architect'; import { EmittedFiles } from '@angular-devkit/build-webpa...
else { context.logger.warn(diagnostic.message); } spinner.start(); } } // Copy any non-processed files into the output locations await copyAssets( [ { glob: '**/*', input: emittedPath, output: '', ignore: [...processedFi...
{ hasErrors = true; context.logger.error(diagnostic.message); }
conditional_block
i18n-inlining.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { BuilderContext } from '@angular-devkit/architect'; import { EmittedFiles } from '@angular-devkit/build-webpa...
( context: BuilderContext, emittedFiles: EmittedFiles[], i18n: I18nOptions, baseOutputPath: string, outputPaths: string[], scriptsEntryPointName: string[], emittedPath: string, es5: boolean, missingTranslation: 'error' | 'warning' | 'ignore' | undefined, ): Promise<boolean> { const executor = new Bu...
i18nInlineEmittedFiles
identifier_name
response.rs
} } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; self.description().fmt(f) } } impl error::Error for Error { fn description(&self) -> &str { match self.message { None => "<no description available>", ...
<S: Into<String>>(&mut self, url: S) -> &mut Self { self.headers.set(header::Location(url.into())); self } /// Sends the given file, setting the Content-Type based on the file's extension. /// /// Known extensions are: /// - application: js, m3u8, mpd, xml /// - image: gif, ...
location
identifier_name
response.rs
} } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; self.description().fmt(f) } } impl error::Error for Error { fn description(&self) -> &str { match self.message { None => "<no description available>", ...
impl From<(Status, &'static str)> for Error { fn from(pair: (Status, &'static str)) -> Error { Error::new(pair.0, Some(Cow::Borrowed(pair.1))) } } impl From<(Status, String)> for Error { fn from(pair: (Status, String)) -> Error { Error::new(pair.0, Some(Cow::Owned(pair.1))) } } /// De...
}
random_line_split
response.rs
} } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; self.description().fmt(f) } } impl error::Error for Error { fn description(&self) -> &str { match self.message { None => "<no description available>", ...
} /// Conversion from `json::Value` into `Action::Send(bytes)`. impl From<json::Value> for Action { fn from(json: json::Value) -> Action { From::from(json.to_string()) } } /// Wraps the given closure in a box and returns `Ok(Action::Stream(box))`. /// /// The closure will be called with a writer impl...
{ Action::Send(string.into_bytes()) }
identifier_body
ext.rs
// Copyright (C) 2016, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of libpm, distributed under the // BSD 3-clause license. For full terms please see the LICENSE file. extern crate toml; use error::PkgError; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::{...
#[test] fn test_clean_path() { let test_path = PathBuf::from("test/pkg/dir"); assert_eq!(clean_path(test_path), PathBuf::from("test/dir")); }
{ let mut buff = String::new(); let mut file = match File::open(file) { Ok(s) => s, Err(e) => { return Err(PkgError::Io(e)); } }; match file.read_to_string(&mut buff) { Ok(s) => s, Err(e) => { return Err(PkgError::Io(e)); } }; ...
identifier_body
ext.rs
// Copyright (C) 2016, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of libpm, distributed under the // BSD 3-clause license. For full terms please see the LICENSE file. extern crate toml; use error::PkgError; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::{...
let test_path = PathBuf::from("test/pkg/dir"); assert_eq!(clean_path(test_path), PathBuf::from("test/dir")); }
} #[test] fn test_clean_path() {
random_line_split
ext.rs
// Copyright (C) 2016, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of libpm, distributed under the // BSD 3-clause license. For full terms please see the LICENSE file. extern crate toml; use error::PkgError; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::{...
<T: AsRef<Path>>(file: T) -> Result<toml::Value, PkgError> { let mut buff = String::new(); let mut file = match File::open(file) { Ok(s) => s, Err(e) => { return Err(PkgError::Io(e)); } }; match file.read_to_string(&mut buff) { Ok(s) => s, Err(e) => { ...
parse_toml_file
identifier_name
list.py
import logging from borgmatic.borg.flags import make_flags, make_flags_from_arguments from borgmatic.execute import execute_command logger = logging.getLogger(__name__) # A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a # non-checkpoint archive name ends in a digit (e.g. from...
(repository, storage_config, list_arguments, local_path='borg', remote_path=None): ''' Given a local or remote repository path, a storage config dict, and the arguments to the list action, display the output of listing Borg archives in the repository or return JSON output. Or, if an archive name is give...
list_archives
identifier_name
list.py
import logging from borgmatic.borg.flags import make_flags, make_flags_from_arguments from borgmatic.execute import execute_command logger = logging.getLogger(__name__) # A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a # non-checkpoint archive name ends in a digit (e.g. from...
) + make_flags('remote-path', remote_path) + make_flags('lock-wait', lock_wait) + make_flags_from_arguments( list_arguments, excludes=('repository', 'archive', 'paths', 'successful') ) + ( '::'.join((repository, list_arguments.archive)) ...
''' Given a local or remote repository path, a storage config dict, and the arguments to the list action, display the output of listing Borg archives in the repository or return JSON output. Or, if an archive name is given, listing the files in that archive. ''' lock_wait = storage_config.get('lock_...
identifier_body
list.py
import logging from borgmatic.borg.flags import make_flags, make_flags_from_arguments from borgmatic.execute import execute_command logger = logging.getLogger(__name__) # A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a # non-checkpoint archive name ends in a digit (e.g. from...
''' lock_wait = storage_config.get('lock_wait', None) if list_arguments.successful: list_arguments.glob_archives = BORG_EXCLUDE_CHECKPOINTS_GLOB full_command = ( (local_path, 'list') + ( ('--info',) if logger.getEffectiveLevel() == logging.INFO and not li...
Given a local or remote repository path, a storage config dict, and the arguments to the list action, display the output of listing Borg archives in the repository or return JSON output. Or, if an archive name is given, listing the files in that archive.
random_line_split
list.py
import logging from borgmatic.borg.flags import make_flags, make_flags_from_arguments from borgmatic.execute import execute_command logger = logging.getLogger(__name__) # A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a # non-checkpoint archive name ends in a digit (e.g. from...
lock_wait = storage_config.get('lock_wait', None) full_command = ( (local_path, 'list') + (('--info',) if logger.getEffectiveLevel() == logging.INFO else ()) + (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ()) + make_flags('remote-path', remote_path) ...
return archive
conditional_block
views.py
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
return port def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) port = self.get_data() table = project_tables.PortsTable(self.request, network_id=port.network_id) context["port"] = por...
port.mac_state = api.neutron.OFF_STATE
conditional_block
views.py
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
return reverse(self.success_url, args=(self.kwargs['network_id'],)) @memoized.memoized_method def _get_object(self, *args, **kwargs): port_id = self.kwargs['port_id'] try: return api.neutron.port_get(self.request, port_id) except Exception: ...
def get_success_url(self):
random_line_split
views.py
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) port = self.get_data() table = project_tables.PortsTable(self.request, network_id=port.network_id) context["port"] = port context["ur...
port_id = self.kwargs['port_id'] try: port = api.neutron.port_get(self.request, port_id) port.admin_state_label = STATE_DICT.get(port.admin_state, port.admin_state) port.status_label = STATUS_DICT.get(port.status, ...
identifier_body
views.py
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
(self): return reverse(self.success_url, args=(self.kwargs['network_id'],)) @memoized.memoized_method def _get_object(self, *args, **kwargs): port_id = self.kwargs['port_id'] try: return api.neutron.port_get(self.request, port_id) except Except...
get_success_url
identifier_name
urls.py
"""kuoteng_bot URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf ...
random_line_split
test_api.py
""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestC...
(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is ap...
test_no_user
identifier_name
test_api.py
""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestC...
def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.u...
Tests for the get_blocks function """ @classmethod
random_line_split
test_api.py
""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestC...
blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.cou...
""" Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) ...
identifier_body
identify.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of overview archive. # Copyright © 2015 seamus tuohy, <stuohy@internews.org> # # 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...
else: log.error("{0} is not a valid path to a file".format(file_path)) raise IOError("{0} is not a valid path to a file".format(file_path)) log.debug("filetype for {0} identified as {1}".format(file_path, file_type)) return file_type def is_url(link): try: site = urlopen(link) ...
ry: file_type = magic.from_file(abspath(file_path), mime=True) except IOError: log.error("{0} is not a valid file".format(file_path)) raise IOError("{0} is not a valid file".format(file_path))
conditional_block
identify.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of overview archive. # Copyright © 2015 seamus tuohy, <stuohy@internews.org> # # 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...
try: file_type = magic.from_file(abspath(file_path), mime=True) except IOError: log.error("{0} is not a valid file".format(file_path)) raise IOError("{0} is not a valid file".format(file_path)) else: log.error("{0} is not a valid path to a file".format(fil...
def filetype(file_path): if path.exists(file_path) and path.isfile(file_path):
random_line_split
identify.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of overview archive. # Copyright © 2015 seamus tuohy, <stuohy@internews.org> # # 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...
link): try: parsed_url = urlparse(link) if parsed_url.netloc == 'web.archive.org': return True except ValueError: return False return False
s_archive(
identifier_name
identify.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of overview archive. # Copyright © 2015 seamus tuohy, <stuohy@internews.org> # # 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...
ry: parsed_url = urlparse(link) if parsed_url.netloc == 'web.archive.org': return True except ValueError: return False return False
identifier_body
api.ck.js
/** * api 接口请求 */ C.api = function(url,get,post,callback,errorback){ //gost_loading.show(); if(post!=null){ var geturl = ''; for(var p in get){ geturl += p+'='+get[p]+'&'; } url += '?' + geturl.substring(0,geturl.length-1);//去掉末尾的 & 字符 C.ajax.post(url,post,f...
errorback?errorback(JsonOb):0; //错误处理 } } };
//{"code":"","msg":"","data":[]} if(JsonOb.code==200){ callback?callback(JsonOb):0;//正常状态调用回调 }else{
random_line_split
api.ck.js
/** * api 接口请求 */ C.api = function(url,get,post,callback,errorback){ //gost_loading.show(); if(post!=null){ var geturl = ''; for(var p in get){ geturl += p+'='+get[p]+'&'; } url += '?' + geturl.substring(0,geturl.length-1);//去掉末尾的 & 字符 C.ajax.post(url,post,f...
onOb = '+DATA+';'); //{"code":"","msg":"","data":[]} if(JsonOb.code==200){ callback?callback(JsonOb):0;//正常状态调用回调 }else{ errorback?errorback(JsonOb):0; //错误处理 } } };
val(' var Js
identifier_name
api.ck.js
/** * api 接口请求 */ C.api = function(url,get,post,callback,errorback){ //gost_loading.show(); if(post!=null){ var geturl = ''; for(var p in get){ geturl += p+'='+get[p]+'&'; } url += '?' + geturl.substring(0,geturl.length-1);//去掉末尾的 & 字符 C.ajax.post(url,post,f...
ata(DATA,callback,errorback); },'html'); }else{ //没有post参数 C.ajax.get(url,get,function(err,DATA){ if(err){ return errorback?errorback():0; } dealBackData(DATA,callback,errorback); },'html'); } //处理接口返回的数据 function dealBackData(...
rn errorback?errorback():0; } dealBackD
conditional_block
api.ck.js
/** * api 接口请求 */ C.api = function(url,get,post,callback,errorback){ //gost_loading.show(); if(post!=null){ var geturl = ''; for(var p in get){ geturl += p+'='+get[p]+'&'; } url += '?' + geturl.substring(0,geturl.length-1);//去掉末尾的 & 字符 C.ajax.post(url,post,f...
//{"code":"","msg":"","data":[]} if(JsonOb.code==200){ callback?callback(JsonOb):0;//正常状态调用回调 }else{ errorback?errorback(JsonOb):0; //错误处理 } } };
identifier_body
vz-projector-bookmark-panel.ts
"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDIT...
this._expandLess(); } } /** Handles a click on show bookmarks tray button. */ _expandMore() { (this.$.panel as any).show(); this.expandMoreButton.style.display = 'none'; this.expandLessButton.style.display = ''; } /** Handles a click on hide bookmarks tray button. */ _expandLess() { ...
random_line_split
vz-projector-bookmark-panel.ts
"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDIT...
} return -1; } /** Handles a clear button click on a bookmark. */ _clearButtonHandler(evt: Event) { let index = this.getParentDataIndex(evt); this.splice('savedStates', index, 1); this.updateHasStates(); } /** Handles a label change event on a bookmark. */ _labelChange(evt: Event) { ...
{ let dataIndex = elem.getAttribute('data-index'); if (dataIndex != null) { return +dataIndex; } }
conditional_block
vz-projector-bookmark-panel.ts
"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDIT...
setSelectedTensor( run: string, tensorInfo: EmbeddingInfo, dataProvider: DataProvider ) { // Clear any existing bookmarks. this.addStates(null); if (tensorInfo && tensorInfo.bookmarksPath) { // Get any bookmarks that may come when the projector starts up. dataProvider.getBookmar...
{ this.projector = projector; projectorEventContext.registerProjectionChangedListener(() => { if (this.ignoreNextProjectionEvent) { this.ignoreNextProjectionEvent = false; } else { this.clearStateSelection(); } }); }
identifier_body
vz-projector-bookmark-panel.ts
"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDIT...
(savedStates?: State[]) { if (savedStates == null) { this.savedStates = []; } else { for (let i = 0; i < savedStates.length; i++) { savedStates[i].isSelected = false; this.push('savedStates', savedStates[i] as any); } } this.updateHasStates(); } /** Deselects any se...
addStates
identifier_name
SpeakPythonMakeDB.py
import antlr3; import sqlite3; import pickle; import sys, os; import re; from SpeakPython.SpeakPython import SpeakPython; from SpeakPython.SpeakPythonLexer import SpeakPythonLexer; from SpeakPython.SpeakPythonParser import SpeakPythonParser; #sort results based on length of labels def sortResults(results): l = len(r...
return globalTests; def main(argv): name = argv[1] + '.db'; conn = sqlite3.connect(name); makeDB(conn); globalTests = parse(conn, [argv[2]], ''); for gt in globalTests: sp = SpeakPython(name); r = sp.matchResult(gt); resultStr = ''; if r != None: resultStr = r.getResult(); if resultStr != gl...
random_line_split
SpeakPythonMakeDB.py
import antlr3; import sqlite3; import pickle; import sys, os; import re; from SpeakPython.SpeakPython import SpeakPython; from SpeakPython.SpeakPythonLexer import SpeakPythonLexer; from SpeakPython.SpeakPythonParser import SpeakPythonParser; #sort results based on length of labels def sortResults(results): l = len(r...
if si2 == sl2: res.extend(s1[si1:]); break; if len(s1[si1].labels) > len(s2[si2].labels): res.append( s1[si1] ); si1 += 1; else: res.append( s2[si2] ); si2 += 1; return res; def makeDB(conn): c = conn.cursor(); try: c.execute("DROP TABLE matches"); c.execute("DROP TABLE functions"); ...
res.extend(s2[si2:]); break;
conditional_block
SpeakPythonMakeDB.py
import antlr3; import sqlite3; import pickle; import sys, os; import re; from SpeakPython.SpeakPython import SpeakPython; from SpeakPython.SpeakPythonLexer import SpeakPythonLexer; from SpeakPython.SpeakPythonParser import SpeakPythonParser; #sort results based on length of labels def sortResults(results): l = len(r...
insertIntoDB(conn, parser.matches, parser.aliases); #if f is a dir, pass list of files into recursive call if os.path.isdir(fileName): subFiles = os.listdir(fileName); otherGlobalTests = parse(conn, subFiles, fileName); globalTests = {}; if parser == None: print "Parser not defined." else: globa...
parser = None; otherGlobalTests = {}; for f in fileList: #join filename with current directory path fileName = os.path.join(dirName, f); #if f is a file, parse and insert into db if os.path.isfile(fileName): char_stream = antlr3.ANTLRFileStream(fileName); lexer = SpeakPythonLexer(char_stream); ...
identifier_body
SpeakPythonMakeDB.py
import antlr3; import sqlite3; import pickle; import sys, os; import re; from SpeakPython.SpeakPython import SpeakPython; from SpeakPython.SpeakPythonLexer import SpeakPythonLexer; from SpeakPython.SpeakPythonParser import SpeakPythonParser; #sort results based on length of labels def sortResults(results): l = len(r...
(conn, fileList, dirName): parser = None; otherGlobalTests = {}; for f in fileList: #join filename with current directory path fileName = os.path.join(dirName, f); #if f is a file, parse and insert into db if os.path.isfile(fileName): char_stream = antlr3.ANTLRFileStream(fileName); lexer = Speak...
parse
identifier_name