file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
middleware.py
""" Middleware to auto-expire inactive sessions after N seconds, which is configurable in settings. To enable this feature, set in a settings.py: SESSION_INACTIVITY_TIMEOUT_IN_SECS = 300 This was taken from StackOverflow (http://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes) """ from datetime import datetime, timedelta from django.conf import settings from django.contrib import auth from django.utils.deprecation import MiddlewareMixin LAST_TOUCH_KEYNAME = 'SessionInactivityTimeout:last_touch' class SessionInactivityTimeout(MiddlewareMixin): """ Middleware class to keep track of activity on a given session """ def process_request(self, request):
""" Standard entry point for processing requests in Django """ if not hasattr(request, "user") or not request.user.is_authenticated: #Can't log out if not logged in return timeout_in_seconds = getattr(settings, "SESSION_INACTIVITY_TIMEOUT_IN_SECONDS", None) # Do we have this feature enabled? if timeout_in_seconds: # what time is it now? utc_now = datetime.utcnow() # Get the last time user made a request to server, which is stored in session data last_touch = request.session.get(LAST_TOUCH_KEYNAME) # have we stored a 'last visited' in session? NOTE: first time access after login # this key will not be present in the session data if last_touch: # compute the delta since last time user came to the server time_since_last_activity = utc_now - last_touch # did we exceed the timeout limit? if time_since_last_activity > timedelta(seconds=timeout_in_seconds): # yes? Then log the user out del request.session[LAST_TOUCH_KEYNAME] auth.logout(request) return request.session[LAST_TOUCH_KEYNAME] = utc_now
identifier_body
middleware.py
""" Middleware to auto-expire inactive sessions after N seconds, which is configurable in settings. To enable this feature, set in a settings.py: SESSION_INACTIVITY_TIMEOUT_IN_SECS = 300 This was taken from StackOverflow (http://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes) """ from datetime import datetime, timedelta from django.conf import settings from django.contrib import auth from django.utils.deprecation import MiddlewareMixin LAST_TOUCH_KEYNAME = 'SessionInactivityTimeout:last_touch' class SessionInactivityTimeout(MiddlewareMixin): """ Middleware class to keep track of activity on a given session """ def
(self, request): """ Standard entry point for processing requests in Django """ if not hasattr(request, "user") or not request.user.is_authenticated: #Can't log out if not logged in return timeout_in_seconds = getattr(settings, "SESSION_INACTIVITY_TIMEOUT_IN_SECONDS", None) # Do we have this feature enabled? if timeout_in_seconds: # what time is it now? utc_now = datetime.utcnow() # Get the last time user made a request to server, which is stored in session data last_touch = request.session.get(LAST_TOUCH_KEYNAME) # have we stored a 'last visited' in session? NOTE: first time access after login # this key will not be present in the session data if last_touch: # compute the delta since last time user came to the server time_since_last_activity = utc_now - last_touch # did we exceed the timeout limit? if time_since_last_activity > timedelta(seconds=timeout_in_seconds): # yes? Then log the user out del request.session[LAST_TOUCH_KEYNAME] auth.logout(request) return request.session[LAST_TOUCH_KEYNAME] = utc_now
process_request
identifier_name
middleware.py
""" Middleware to auto-expire inactive sessions after N seconds, which is configurable in settings. To enable this feature, set in a settings.py: SESSION_INACTIVITY_TIMEOUT_IN_SECS = 300 This was taken from StackOverflow (http://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes) """ from datetime import datetime, timedelta
LAST_TOUCH_KEYNAME = 'SessionInactivityTimeout:last_touch' class SessionInactivityTimeout(MiddlewareMixin): """ Middleware class to keep track of activity on a given session """ def process_request(self, request): """ Standard entry point for processing requests in Django """ if not hasattr(request, "user") or not request.user.is_authenticated: #Can't log out if not logged in return timeout_in_seconds = getattr(settings, "SESSION_INACTIVITY_TIMEOUT_IN_SECONDS", None) # Do we have this feature enabled? if timeout_in_seconds: # what time is it now? utc_now = datetime.utcnow() # Get the last time user made a request to server, which is stored in session data last_touch = request.session.get(LAST_TOUCH_KEYNAME) # have we stored a 'last visited' in session? NOTE: first time access after login # this key will not be present in the session data if last_touch: # compute the delta since last time user came to the server time_since_last_activity = utc_now - last_touch # did we exceed the timeout limit? if time_since_last_activity > timedelta(seconds=timeout_in_seconds): # yes? Then log the user out del request.session[LAST_TOUCH_KEYNAME] auth.logout(request) return request.session[LAST_TOUCH_KEYNAME] = utc_now
from django.conf import settings from django.contrib import auth from django.utils.deprecation import MiddlewareMixin
random_line_split
middleware.py
""" Middleware to auto-expire inactive sessions after N seconds, which is configurable in settings. To enable this feature, set in a settings.py: SESSION_INACTIVITY_TIMEOUT_IN_SECS = 300 This was taken from StackOverflow (http://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes) """ from datetime import datetime, timedelta from django.conf import settings from django.contrib import auth from django.utils.deprecation import MiddlewareMixin LAST_TOUCH_KEYNAME = 'SessionInactivityTimeout:last_touch' class SessionInactivityTimeout(MiddlewareMixin): """ Middleware class to keep track of activity on a given session """ def process_request(self, request): """ Standard entry point for processing requests in Django """ if not hasattr(request, "user") or not request.user.is_authenticated: #Can't log out if not logged in return timeout_in_seconds = getattr(settings, "SESSION_INACTIVITY_TIMEOUT_IN_SECONDS", None) # Do we have this feature enabled? if timeout_in_seconds: # what time is it now? utc_now = datetime.utcnow() # Get the last time user made a request to server, which is stored in session data last_touch = request.session.get(LAST_TOUCH_KEYNAME) # have we stored a 'last visited' in session? NOTE: first time access after login # this key will not be present in the session data if last_touch: # compute the delta since last time user came to the server
request.session[LAST_TOUCH_KEYNAME] = utc_now
time_since_last_activity = utc_now - last_touch # did we exceed the timeout limit? if time_since_last_activity > timedelta(seconds=timeout_in_seconds): # yes? Then log the user out del request.session[LAST_TOUCH_KEYNAME] auth.logout(request) return
conditional_block
defaults-vi_VN.js
/*! * Bootstrap-select v1.13.9 (https://developer.snapappointments.com/bootstrap-select) *
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Chưa chọn', noneResultsText: 'Không có kết quả cho {0}', countSelectedText: function (numSelected, numTotal) { return '{0} mục đã chọn'; }, maxOptionsText: function (numAll, numGroup) { return [ 'Không thể chọn (giới hạn {n} mục)', 'Không thể chọn (giới hạn {n} mục)' ]; }, selectAllText: 'Chọn tất cả', deselectAllText: 'Bỏ chọn', multipleSeparator: ', ' }; })(jQuery); })); //# sourceMappingURL=defaults-vi_VN.js.map
* Copyright 2012-2019 SnapAppointments, LLC
random_line_split
lib.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![feature(plugin_registrar)] #![feature(slice_patterns, box_syntax, rustc_private)] #[macro_use(walk_list)] extern crate syntax; extern crate rustc_serialize; // Load rustc as a plugin to get macros. #[macro_use] extern crate rustc; extern crate rustc_plugin; #[macro_use] extern crate log; mod kythe; mod pass; mod visitor; use kythe::writer::JsonEntryWriter; use rustc_plugin::Registry; use rustc::lint::LateLintPassObject; // Informs the compiler of the existence and implementation of our plugin. #[plugin_registrar] pub fn
(reg: &mut Registry) { let pass = box pass::KytheLintPass::new(box JsonEntryWriter); reg.register_late_lint_pass(pass as LateLintPassObject); }
plugin_registrar
identifier_name
lib.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![feature(plugin_registrar)] #![feature(slice_patterns, box_syntax, rustc_private)] #[macro_use(walk_list)] extern crate syntax;
// Load rustc as a plugin to get macros. #[macro_use] extern crate rustc; extern crate rustc_plugin; #[macro_use] extern crate log; mod kythe; mod pass; mod visitor; use kythe::writer::JsonEntryWriter; use rustc_plugin::Registry; use rustc::lint::LateLintPassObject; // Informs the compiler of the existence and implementation of our plugin. #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { let pass = box pass::KytheLintPass::new(box JsonEntryWriter); reg.register_late_lint_pass(pass as LateLintPassObject); }
extern crate rustc_serialize;
random_line_split
lib.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![feature(plugin_registrar)] #![feature(slice_patterns, box_syntax, rustc_private)] #[macro_use(walk_list)] extern crate syntax; extern crate rustc_serialize; // Load rustc as a plugin to get macros. #[macro_use] extern crate rustc; extern crate rustc_plugin; #[macro_use] extern crate log; mod kythe; mod pass; mod visitor; use kythe::writer::JsonEntryWriter; use rustc_plugin::Registry; use rustc::lint::LateLintPassObject; // Informs the compiler of the existence and implementation of our plugin. #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry)
{ let pass = box pass::KytheLintPass::new(box JsonEntryWriter); reg.register_late_lint_pass(pass as LateLintPassObject); }
identifier_body
issue-24081.rs
// Copyright 2015 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::ops::Add; use std::ops::Sub; use std::ops::Mul; use std::ops::Div; use std::ops::Rem; type Add = bool; //~ ERROR the name `Add` is defined multiple times //~| `Add` redefined here struct Sub { x: f32 } //~ ERROR the name `Sub` is defined multiple times //~| `Sub` redefined here enum Mul { A, B } //~ ERROR the name `Mul` is defined multiple times //~| `Mul` redefined here mod Div { } //~ ERROR the name `Div` is defined multiple times //~| `Div` redefined here trait Rem { } //~ ERROR the name `Rem` is defined multiple times //~| `Rem` redefined here fn
() {}
main
identifier_name
issue-24081.rs
// Copyright 2015 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
use std::ops::Mul; use std::ops::Div; use std::ops::Rem; type Add = bool; //~ ERROR the name `Add` is defined multiple times //~| `Add` redefined here struct Sub { x: f32 } //~ ERROR the name `Sub` is defined multiple times //~| `Sub` redefined here enum Mul { A, B } //~ ERROR the name `Mul` is defined multiple times //~| `Mul` redefined here mod Div { } //~ ERROR the name `Div` is defined multiple times //~| `Div` redefined here trait Rem { } //~ ERROR the name `Rem` is defined multiple times //~| `Rem` redefined here fn main() {}
use std::ops::Add; use std::ops::Sub;
random_line_split
angular-locale_pa-arab.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "\u0627\u062a\u0648\u0627\u0631", "\u067e\u06cc\u0631", "\u0645\u0646\u06af\u0644", "\u0628\u064f\u062f\u06be", "\u062c\u0645\u0639\u0631\u0627\u062a", "\u062c\u0645\u0639\u06c1", "\u06c1\u0641\u062a\u06c1" ], "MONTH": [ "\u062c\u0646\u0648\u0631\u06cc", "\u0641\u0631\u0648\u0631\u06cc", "\u0645\u0627\u0631\u0686", "\u0627\u067e\u0631\u06cc\u0644", "\u0645\u0626", "\u062c\u0648\u0646", "\u062c\u0648\u0644\u0627\u0626\u06cc", "\u0627\u06af\u0633\u062a", "\u0633\u062a\u0645\u0628\u0631", "\u0627\u06a9\u062a\u0648\u0628\u0631", "\u0646\u0648\u0645\u0628\u0631", "\u062f\u0633\u0645\u0628\u0631" ], "SHORTDAY": [ "\u0a10\u0a24.", "\u0a38\u0a4b\u0a2e.", "\u0a2e\u0a70\u0a17\u0a32.", "\u0a2c\u0a41\u0a27.", "\u0a35\u0a40\u0a30.", "\u0a38\u0a3c\u0a41\u0a71\u0a15\u0a30.", "\u0a38\u0a3c\u0a28\u0a40." ], "SHORTMONTH": [ "\u0a1c\u0a28\u0a35\u0a30\u0a40", "\u0a2b\u0a3c\u0a30\u0a35\u0a30\u0a40", "\u0a2e\u0a3e\u0a30\u0a1a", "\u0a05\u0a2a\u0a4d\u0a30\u0a48\u0a32", "\u0a2e\u0a08", "\u0a1c\u0a42\u0a28", "\u0a1c\u0a41\u0a32\u0a3e\u0a08", "\u0a05\u0a17\u0a38\u0a24", "\u0a38\u0a24\u0a70\u0a2c\u0a30", "\u0a05\u0a15\u0a24\u0a42\u0a2c\u0a30", "\u0a28\u0a35\u0a70\u0a2c\u0a30", "\u0a26\u0a38\u0a70\u0a2c\u0a30" ], "fullDate": "EEEE, dd MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20b9", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 2, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 2, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "pa-arab", "pluralCat": function (n, opt_precision) { if (n >= 0 && n <= 1)
return PLURAL_CATEGORY.OTHER;} }); }]);
{ return PLURAL_CATEGORY.ONE; }
conditional_block
angular-locale_pa-arab.js
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "\u0627\u062a\u0648\u0627\u0631", "\u067e\u06cc\u0631", "\u0645\u0646\u06af\u0644", "\u0628\u064f\u062f\u06be", "\u062c\u0645\u0639\u0631\u0627\u062a", "\u062c\u0645\u0639\u06c1", "\u06c1\u0641\u062a\u06c1" ], "MONTH": [ "\u062c\u0646\u0648\u0631\u06cc", "\u0641\u0631\u0648\u0631\u06cc", "\u0645\u0627\u0631\u0686", "\u0627\u067e\u0631\u06cc\u0644", "\u0645\u0626", "\u062c\u0648\u0646", "\u062c\u0648\u0644\u0627\u0626\u06cc", "\u0627\u06af\u0633\u062a", "\u0633\u062a\u0645\u0628\u0631", "\u0627\u06a9\u062a\u0648\u0628\u0631", "\u0646\u0648\u0645\u0628\u0631", "\u062f\u0633\u0645\u0628\u0631" ], "SHORTDAY": [ "\u0a10\u0a24.", "\u0a38\u0a4b\u0a2e.", "\u0a2e\u0a70\u0a17\u0a32.", "\u0a2c\u0a41\u0a27.", "\u0a35\u0a40\u0a30.", "\u0a38\u0a3c\u0a41\u0a71\u0a15\u0a30.", "\u0a38\u0a3c\u0a28\u0a40." ], "SHORTMONTH": [ "\u0a1c\u0a28\u0a35\u0a30\u0a40", "\u0a2b\u0a3c\u0a30\u0a35\u0a30\u0a40", "\u0a2e\u0a3e\u0a30\u0a1a", "\u0a05\u0a2a\u0a4d\u0a30\u0a48\u0a32", "\u0a2e\u0a08", "\u0a1c\u0a42\u0a28", "\u0a1c\u0a41\u0a32\u0a3e\u0a08", "\u0a05\u0a17\u0a38\u0a24", "\u0a38\u0a24\u0a70\u0a2c\u0a30", "\u0a05\u0a15\u0a24\u0a42\u0a2c\u0a30", "\u0a28\u0a35\u0a70\u0a2c\u0a30", "\u0a26\u0a38\u0a70\u0a2c\u0a30" ], "fullDate": "EEEE, dd MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20b9", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 2, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 2, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "pa-arab", "pluralCat": function (n, opt_precision) { if (n >= 0 && n <= 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
random_line_split
regress-474771.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-474771.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 474771; var summary = 'TM: do not halt execution with gczeal, prototype mangling, for..in'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test()
{ enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'PASS'; jit(true); if (typeof gczeal != 'undefined') { gczeal(2); } Object.prototype.q = 3; for each (let x in [6, 7]) { } print(actual = "PASS"); jit(false); delete Object.prototype.q; reportCompare(expect, actual, summary); exitFunc ('test'); }
identifier_body
regress-474771.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-474771.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 474771; var summary = 'TM: do not halt execution with gczeal, prototype mangling, for..in'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function
() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'PASS'; jit(true); if (typeof gczeal != 'undefined') { gczeal(2); } Object.prototype.q = 3; for each (let x in [6, 7]) { } print(actual = "PASS"); jit(false); delete Object.prototype.q; reportCompare(expect, actual, summary); exitFunc ('test'); }
test
identifier_name
regress-474771.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-474771.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 474771; var summary = 'TM: do not halt execution with gczeal, prototype mangling, for..in'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'PASS'; jit(true); if (typeof gczeal != 'undefined')
gczeal(2); } Object.prototype.q = 3; for each (let x in [6, 7]) { } print(actual = "PASS"); jit(false); delete Object.prototype.q; reportCompare(expect, actual, summary); exitFunc ('test'); }
{
random_line_split
regress-474771.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-474771.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 474771; var summary = 'TM: do not halt execution with gczeal, prototype mangling, for..in'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'PASS'; jit(true); if (typeof gczeal != 'undefined')
Object.prototype.q = 3; for each (let x in [6, 7]) { } print(actual = "PASS"); jit(false); delete Object.prototype.q; reportCompare(expect, actual, summary); exitFunc ('test'); }
{ gczeal(2); }
conditional_block
nullable-pointer-size.rs
// Copyright 2013 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(macro_rules)] use std::mem; use std::gc::Gc; enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8, ..0]) } struct S<T>(int, T); // These are macros so we get useful assert messages. macro_rules! check_option { ($T:ty) => { assert_eq!(mem::size_of::<Option<$T>>(), mem::size_of::<$T>()); } } macro_rules! check_fancy { ($T:ty) => { assert_eq!(mem::size_of::<E<$T>>(), mem::size_of::<S<$T>>()); } } macro_rules! check_type {
check_option!($T); check_fancy!($T); }} } pub fn main() { check_type!(&'static int); check_type!(Box<int>); check_type!(Gc<int>); check_type!(extern fn()); }
($T:ty) => {{
random_line_split
nullable-pointer-size.rs
// Copyright 2013 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(macro_rules)] use std::mem; use std::gc::Gc; enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8, ..0]) } struct S<T>(int, T); // These are macros so we get useful assert messages. macro_rules! check_option { ($T:ty) => { assert_eq!(mem::size_of::<Option<$T>>(), mem::size_of::<$T>()); } } macro_rules! check_fancy { ($T:ty) => { assert_eq!(mem::size_of::<E<$T>>(), mem::size_of::<S<$T>>()); } } macro_rules! check_type { ($T:ty) => {{ check_option!($T); check_fancy!($T); }} } pub fn
() { check_type!(&'static int); check_type!(Box<int>); check_type!(Gc<int>); check_type!(extern fn()); }
main
identifier_name
urls.py
# -*- coding: utf-8 -*- from rest_framework.routers import (Route, DynamicDetailRoute, SimpleRouter, DynamicListRoute) from app.api.account.views import AccountViewSet from app.api.podcast.views import PodcastViewSet, EpisodeViewSet class CustomRouter(SimpleRouter): """ A router for read-only APIs, which doesn't use trailing slashes. """ routes = [ Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create' }, name='{basename}-list', initkwargs={'suffix': 'List'} ), # Dynamically generated list routes. # Generated using @list_route decorator # on methods of the viewset. DynamicListRoute(
name='{basename}-{methodnamehyphen}', initkwargs={} ), # Detail route. Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name='{basename}-detail', initkwargs={'suffix': 'Instance'} ), # Dynamically generated detail routes. # Generated using @detail_route decorator on methods of the viewset. DynamicDetailRoute( url=r'^{prefix}/{lookup}/{methodnamehyphen}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={} ), ] router = CustomRouter() router.register(r'accounts', AccountViewSet) router.register(r'podcasts', PodcastViewSet) router.register(r'episodes', EpisodeViewSet) urlpatterns = router.urls
url=r'^{prefix}/{methodnamehyphen}{trailing_slash}$',
random_line_split
urls.py
# -*- coding: utf-8 -*- from rest_framework.routers import (Route, DynamicDetailRoute, SimpleRouter, DynamicListRoute) from app.api.account.views import AccountViewSet from app.api.podcast.views import PodcastViewSet, EpisodeViewSet class
(SimpleRouter): """ A router for read-only APIs, which doesn't use trailing slashes. """ routes = [ Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create' }, name='{basename}-list', initkwargs={'suffix': 'List'} ), # Dynamically generated list routes. # Generated using @list_route decorator # on methods of the viewset. DynamicListRoute( url=r'^{prefix}/{methodnamehyphen}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={} ), # Detail route. Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name='{basename}-detail', initkwargs={'suffix': 'Instance'} ), # Dynamically generated detail routes. # Generated using @detail_route decorator on methods of the viewset. DynamicDetailRoute( url=r'^{prefix}/{lookup}/{methodnamehyphen}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={} ), ] router = CustomRouter() router.register(r'accounts', AccountViewSet) router.register(r'podcasts', PodcastViewSet) router.register(r'episodes', EpisodeViewSet) urlpatterns = router.urls
CustomRouter
identifier_name
urls.py
# -*- coding: utf-8 -*- from rest_framework.routers import (Route, DynamicDetailRoute, SimpleRouter, DynamicListRoute) from app.api.account.views import AccountViewSet from app.api.podcast.views import PodcastViewSet, EpisodeViewSet class CustomRouter(SimpleRouter):
router = CustomRouter() router.register(r'accounts', AccountViewSet) router.register(r'podcasts', PodcastViewSet) router.register(r'episodes', EpisodeViewSet) urlpatterns = router.urls
""" A router for read-only APIs, which doesn't use trailing slashes. """ routes = [ Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create' }, name='{basename}-list', initkwargs={'suffix': 'List'} ), # Dynamically generated list routes. # Generated using @list_route decorator # on methods of the viewset. DynamicListRoute( url=r'^{prefix}/{methodnamehyphen}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={} ), # Detail route. Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name='{basename}-detail', initkwargs={'suffix': 'Instance'} ), # Dynamically generated detail routes. # Generated using @detail_route decorator on methods of the viewset. DynamicDetailRoute( url=r'^{prefix}/{lookup}/{methodnamehyphen}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={} ), ]
identifier_body
graphs_9_hdfs_indices.py
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib from pylab import * import numpy from copy_reg import remove_extension from heapq import heappush from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA colors = ["red", "green", "blue", "orange", "brown", "black", "silver", "aqua", "purple"] suffix = "" file_type = "" def draw_scatter_plot(ii_trends, other_trends): fig = figure(figsize=(8, 6), dpi=80) grid(b=True, which='major', color='gray', axis="both", linestyle='--', zorder=-1) font_size = 20 algos = [algo for algo in ii_trends.keys()] algos.sort() plt.ylim([0, 100]) for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y,y_err in ii_trends[algo]] y_values = [y for x,y,y_err in ii_trends[algo]] err_values = [y_err for x,y,y_err in ii_trends[algo]] line, = plt.plot(x_values, y_values, lw=3, color="red") y_values = [y_values[index] for index in xrange(0, len(x_values), 2)] err_values = [err_values[index] for index in xrange(0, len(x_values), 2)] x_values = [x_values[index] for index in xrange(0, len(x_values), 2)] bar, _, _ = plt.errorbar(x_values, y_values, yerr=err_values, lw=1, linestyle='-', color="black") line.set_zorder(1) bar.set_zorder(2) plt.ylim([0, 80]) plt.xlim([0, 80000]) algos = [algo for algo in other_trends.keys()] algos.sort() for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y in other_trends[algo]] y_values = [y for x,y in other_trends[algo]] line_style = "-" marker = "x" if "mapred" in algo: line_style = "-" marker= "^" line, = plt.plot(x_values, y_values, lw=2, linestyle=line_style, marker=marker, color="black") line.set_zorder(1) ylabel = plt.ylabel("Time per one query [ms]") ylabel.set_fontsize(font_size) xlabel = plt.xlabel("Queries count x1000") xlabel.set_fontsize(font_size) for ytick in plt.yticks()[1]: ytick.set_fontsize(font_size) for xtick in plt.xticks()[1]: xtick.set_fontsize(font_size) if 1: print plt.xticks() xticks = [item for item in plt.xticks()[0]] xticks_labels = [str(int(item / 1000)) for item in xticks] plt.xticks(xticks, xticks_labels) plt.tight_layout() savefig("../paper/imgs/9_time_distrib_hdfs_indices.eps", transparent="True", pad_inches=0) plt.show() def
(): font_size= 20 fig = figure(figsize=(8, 6), dpi=80) p1 = plt.bar(range(len(algo2index)), range(len(algo2index)), 1.0, color="#7FCA9F") for algo_index in xrange(len(algos)): p1[algo_index].set_color(colors[algo_index]) fig = figure(figsize=(12, 6), dpi=80) desc = [algo for algo in algos] legend = plt.legend( p1, desc, shadow=False, loc=1, fontsize=font_size) legend.draw_frame(True) savefig("../graphs/test_results/legend" + file_type, transparent="True", pad_inches=0) def calc_avg_minus_extremes(values): values.sort() quartile = len(values) / 4 values = values[3:-3] import numpy, math margin_err = 1.96 * numpy.std(values) / math.sqrt(len(values)) return float(sum(values)) / len(values), margin_err RESPONSE_SIZE_POS = 0 TIME_RESULT_POS = 3 MEM_CONSUMPTION_POS = 1 QUERIES_COUNT = 200000 if 1: ii_trends = {} for line in open("../test_results/9_hdfs_iindex_read_size.txt"): if not "read_size" in line: continue chunks = line.split() algo = chunks[0] if chunks[1] == "read_size": algo += "_" + chunks[2].zfill(5) x = int(chunks[-9]) y = float(chunks[-1]) ii_trends.setdefault(algo, []).append((x, y / x)) trend = [] for key in ii_trends.keys(): ii_trends[key].sort() by_x = {} for x, y in ii_trends[key]: by_x.setdefault(x, []).append(y) trend = [] for x, y_vals in by_x.items(): y_vals.sort() initial = [item for item in y_vals] y_mean, y_err = 0, 0 while True: y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) if y_err / y_mean < 0.2: break if len(y_vals) < 6: y_vals = initial y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) print x, y_err / y_mean, initial, y_vals break y_vals = y_vals[1:-1] print y_err/ y_mean trend += [(x, y_mean, y_err)] trend.sort() ii_trends[key] = trend other_trends = {} for line in open("../test_results/7_hdfs_indices.txt"): chunks = line.split() algo = chunks[0] if not "spatial" in algo and not "mapred" in algo: continue if chunks[1] == "read_size": algo += "_" + chunks[2].zfill(5) x = int(chunks[-5]) y = float(chunks[-1]) other_trends.setdefault(algo, []).append((x, y / x)) for key in other_trends.keys(): other_trends[key].sort() draw_scatter_plot(ii_trends, other_trends)
draw_legend
identifier_name
graphs_9_hdfs_indices.py
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib from pylab import * import numpy from copy_reg import remove_extension from heapq import heappush from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA colors = ["red", "green", "blue", "orange", "brown", "black", "silver", "aqua", "purple"] suffix = "" file_type = "" def draw_scatter_plot(ii_trends, other_trends): fig = figure(figsize=(8, 6), dpi=80) grid(b=True, which='major', color='gray', axis="both", linestyle='--', zorder=-1) font_size = 20 algos = [algo for algo in ii_trends.keys()] algos.sort() plt.ylim([0, 100]) for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y,y_err in ii_trends[algo]] y_values = [y for x,y,y_err in ii_trends[algo]] err_values = [y_err for x,y,y_err in ii_trends[algo]] line, = plt.plot(x_values, y_values, lw=3, color="red") y_values = [y_values[index] for index in xrange(0, len(x_values), 2)] err_values = [err_values[index] for index in xrange(0, len(x_values), 2)] x_values = [x_values[index] for index in xrange(0, len(x_values), 2)] bar, _, _ = plt.errorbar(x_values, y_values, yerr=err_values, lw=1, linestyle='-', color="black") line.set_zorder(1) bar.set_zorder(2) plt.ylim([0, 80]) plt.xlim([0, 80000]) algos = [algo for algo in other_trends.keys()] algos.sort() for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y in other_trends[algo]] y_values = [y for x,y in other_trends[algo]] line_style = "-" marker = "x" if "mapred" in algo: line_style = "-" marker= "^" line, = plt.plot(x_values, y_values, lw=2, linestyle=line_style, marker=marker, color="black") line.set_zorder(1) ylabel = plt.ylabel("Time per one query [ms]") ylabel.set_fontsize(font_size) xlabel = plt.xlabel("Queries count x1000") xlabel.set_fontsize(font_size) for ytick in plt.yticks()[1]: ytick.set_fontsize(font_size) for xtick in plt.xticks()[1]: xtick.set_fontsize(font_size) if 1: print plt.xticks() xticks = [item for item in plt.xticks()[0]] xticks_labels = [str(int(item / 1000)) for item in xticks] plt.xticks(xticks, xticks_labels) plt.tight_layout() savefig("../paper/imgs/9_time_distrib_hdfs_indices.eps", transparent="True", pad_inches=0) plt.show() def draw_legend(): font_size= 20 fig = figure(figsize=(8, 6), dpi=80) p1 = plt.bar(range(len(algo2index)), range(len(algo2index)), 1.0, color="#7FCA9F") for algo_index in xrange(len(algos)): p1[algo_index].set_color(colors[algo_index]) fig = figure(figsize=(12, 6), dpi=80) desc = [algo for algo in algos] legend = plt.legend( p1, desc, shadow=False, loc=1, fontsize=font_size) legend.draw_frame(True) savefig("../graphs/test_results/legend" + file_type, transparent="True", pad_inches=0) def calc_avg_minus_extremes(values): values.sort() quartile = len(values) / 4 values = values[3:-3] import numpy, math margin_err = 1.96 * numpy.std(values) / math.sqrt(len(values)) return float(sum(values)) / len(values), margin_err RESPONSE_SIZE_POS = 0 TIME_RESULT_POS = 3 MEM_CONSUMPTION_POS = 1 QUERIES_COUNT = 200000 if 1: ii_trends = {} for line in open("../test_results/9_hdfs_iindex_read_size.txt"): if not "read_size" in line: continue chunks = line.split() algo = chunks[0] if chunks[1] == "read_size": algo += "_" + chunks[2].zfill(5) x = int(chunks[-9]) y = float(chunks[-1]) ii_trends.setdefault(algo, []).append((x, y / x)) trend = [] for key in ii_trends.keys(): ii_trends[key].sort() by_x = {} for x, y in ii_trends[key]: by_x.setdefault(x, []).append(y) trend = [] for x, y_vals in by_x.items(): y_vals.sort() initial = [item for item in y_vals] y_mean, y_err = 0, 0 while True: y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) if y_err / y_mean < 0.2: break if len(y_vals) < 6: y_vals = initial y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) print x, y_err / y_mean, initial, y_vals break y_vals = y_vals[1:-1] print y_err/ y_mean trend += [(x, y_mean, y_err)] trend.sort() ii_trends[key] = trend other_trends = {} for line in open("../test_results/7_hdfs_indices.txt"): chunks = line.split() algo = chunks[0] if not "spatial" in algo and not "mapred" in algo: continue if chunks[1] == "read_size":
x = int(chunks[-5]) y = float(chunks[-1]) other_trends.setdefault(algo, []).append((x, y / x)) for key in other_trends.keys(): other_trends[key].sort() draw_scatter_plot(ii_trends, other_trends)
algo += "_" + chunks[2].zfill(5)
conditional_block
graphs_9_hdfs_indices.py
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib from pylab import * import numpy from copy_reg import remove_extension from heapq import heappush from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA colors = ["red", "green", "blue", "orange", "brown", "black", "silver", "aqua", "purple"] suffix = "" file_type = "" def draw_scatter_plot(ii_trends, other_trends): fig = figure(figsize=(8, 6), dpi=80) grid(b=True, which='major', color='gray', axis="both", linestyle='--', zorder=-1) font_size = 20 algos = [algo for algo in ii_trends.keys()] algos.sort() plt.ylim([0, 100]) for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y,y_err in ii_trends[algo]] y_values = [y for x,y,y_err in ii_trends[algo]] err_values = [y_err for x,y,y_err in ii_trends[algo]] line, = plt.plot(x_values, y_values, lw=3, color="red") y_values = [y_values[index] for index in xrange(0, len(x_values), 2)] err_values = [err_values[index] for index in xrange(0, len(x_values), 2)] x_values = [x_values[index] for index in xrange(0, len(x_values), 2)] bar, _, _ = plt.errorbar(x_values, y_values, yerr=err_values, lw=1, linestyle='-', color="black") line.set_zorder(1) bar.set_zorder(2) plt.ylim([0, 80]) plt.xlim([0, 80000]) algos = [algo for algo in other_trends.keys()] algos.sort() for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y in other_trends[algo]] y_values = [y for x,y in other_trends[algo]] line_style = "-" marker = "x" if "mapred" in algo: line_style = "-" marker= "^" line, = plt.plot(x_values, y_values, lw=2, linestyle=line_style, marker=marker, color="black") line.set_zorder(1) ylabel = plt.ylabel("Time per one query [ms]") ylabel.set_fontsize(font_size) xlabel = plt.xlabel("Queries count x1000") xlabel.set_fontsize(font_size) for ytick in plt.yticks()[1]: ytick.set_fontsize(font_size) for xtick in plt.xticks()[1]: xtick.set_fontsize(font_size) if 1: print plt.xticks() xticks = [item for item in plt.xticks()[0]] xticks_labels = [str(int(item / 1000)) for item in xticks] plt.xticks(xticks, xticks_labels) plt.tight_layout() savefig("../paper/imgs/9_time_distrib_hdfs_indices.eps", transparent="True", pad_inches=0) plt.show() def draw_legend(): font_size= 20 fig = figure(figsize=(8, 6), dpi=80) p1 = plt.bar(range(len(algo2index)), range(len(algo2index)), 1.0, color="#7FCA9F") for algo_index in xrange(len(algos)): p1[algo_index].set_color(colors[algo_index]) fig = figure(figsize=(12, 6), dpi=80) desc = [algo for algo in algos] legend = plt.legend( p1, desc, shadow=False, loc=1, fontsize=font_size) legend.draw_frame(True) savefig("../graphs/test_results/legend" + file_type, transparent="True", pad_inches=0) def calc_avg_minus_extremes(values): values.sort()
values = values[3:-3] import numpy, math margin_err = 1.96 * numpy.std(values) / math.sqrt(len(values)) return float(sum(values)) / len(values), margin_err RESPONSE_SIZE_POS = 0 TIME_RESULT_POS = 3 MEM_CONSUMPTION_POS = 1 QUERIES_COUNT = 200000 if 1: ii_trends = {} for line in open("../test_results/9_hdfs_iindex_read_size.txt"): if not "read_size" in line: continue chunks = line.split() algo = chunks[0] if chunks[1] == "read_size": algo += "_" + chunks[2].zfill(5) x = int(chunks[-9]) y = float(chunks[-1]) ii_trends.setdefault(algo, []).append((x, y / x)) trend = [] for key in ii_trends.keys(): ii_trends[key].sort() by_x = {} for x, y in ii_trends[key]: by_x.setdefault(x, []).append(y) trend = [] for x, y_vals in by_x.items(): y_vals.sort() initial = [item for item in y_vals] y_mean, y_err = 0, 0 while True: y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) if y_err / y_mean < 0.2: break if len(y_vals) < 6: y_vals = initial y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) print x, y_err / y_mean, initial, y_vals break y_vals = y_vals[1:-1] print y_err/ y_mean trend += [(x, y_mean, y_err)] trend.sort() ii_trends[key] = trend other_trends = {} for line in open("../test_results/7_hdfs_indices.txt"): chunks = line.split() algo = chunks[0] if not "spatial" in algo and not "mapred" in algo: continue if chunks[1] == "read_size": algo += "_" + chunks[2].zfill(5) x = int(chunks[-5]) y = float(chunks[-1]) other_trends.setdefault(algo, []).append((x, y / x)) for key in other_trends.keys(): other_trends[key].sort() draw_scatter_plot(ii_trends, other_trends)
quartile = len(values) / 4
random_line_split
graphs_9_hdfs_indices.py
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib from pylab import * import numpy from copy_reg import remove_extension from heapq import heappush from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA colors = ["red", "green", "blue", "orange", "brown", "black", "silver", "aqua", "purple"] suffix = "" file_type = "" def draw_scatter_plot(ii_trends, other_trends):
def draw_legend(): font_size= 20 fig = figure(figsize=(8, 6), dpi=80) p1 = plt.bar(range(len(algo2index)), range(len(algo2index)), 1.0, color="#7FCA9F") for algo_index in xrange(len(algos)): p1[algo_index].set_color(colors[algo_index]) fig = figure(figsize=(12, 6), dpi=80) desc = [algo for algo in algos] legend = plt.legend( p1, desc, shadow=False, loc=1, fontsize=font_size) legend.draw_frame(True) savefig("../graphs/test_results/legend" + file_type, transparent="True", pad_inches=0) def calc_avg_minus_extremes(values): values.sort() quartile = len(values) / 4 values = values[3:-3] import numpy, math margin_err = 1.96 * numpy.std(values) / math.sqrt(len(values)) return float(sum(values)) / len(values), margin_err RESPONSE_SIZE_POS = 0 TIME_RESULT_POS = 3 MEM_CONSUMPTION_POS = 1 QUERIES_COUNT = 200000 if 1: ii_trends = {} for line in open("../test_results/9_hdfs_iindex_read_size.txt"): if not "read_size" in line: continue chunks = line.split() algo = chunks[0] if chunks[1] == "read_size": algo += "_" + chunks[2].zfill(5) x = int(chunks[-9]) y = float(chunks[-1]) ii_trends.setdefault(algo, []).append((x, y / x)) trend = [] for key in ii_trends.keys(): ii_trends[key].sort() by_x = {} for x, y in ii_trends[key]: by_x.setdefault(x, []).append(y) trend = [] for x, y_vals in by_x.items(): y_vals.sort() initial = [item for item in y_vals] y_mean, y_err = 0, 0 while True: y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) if y_err / y_mean < 0.2: break if len(y_vals) < 6: y_vals = initial y_mean, y_err = sum(y_vals) / len(y_vals), 1.96 * numpy.std(y_vals) / math.sqrt(len(y_vals)) print x, y_err / y_mean, initial, y_vals break y_vals = y_vals[1:-1] print y_err/ y_mean trend += [(x, y_mean, y_err)] trend.sort() ii_trends[key] = trend other_trends = {} for line in open("../test_results/7_hdfs_indices.txt"): chunks = line.split() algo = chunks[0] if not "spatial" in algo and not "mapred" in algo: continue if chunks[1] == "read_size": algo += "_" + chunks[2].zfill(5) x = int(chunks[-5]) y = float(chunks[-1]) other_trends.setdefault(algo, []).append((x, y / x)) for key in other_trends.keys(): other_trends[key].sort() draw_scatter_plot(ii_trends, other_trends)
fig = figure(figsize=(8, 6), dpi=80) grid(b=True, which='major', color='gray', axis="both", linestyle='--', zorder=-1) font_size = 20 algos = [algo for algo in ii_trends.keys()] algos.sort() plt.ylim([0, 100]) for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y,y_err in ii_trends[algo]] y_values = [y for x,y,y_err in ii_trends[algo]] err_values = [y_err for x,y,y_err in ii_trends[algo]] line, = plt.plot(x_values, y_values, lw=3, color="red") y_values = [y_values[index] for index in xrange(0, len(x_values), 2)] err_values = [err_values[index] for index in xrange(0, len(x_values), 2)] x_values = [x_values[index] for index in xrange(0, len(x_values), 2)] bar, _, _ = plt.errorbar(x_values, y_values, yerr=err_values, lw=1, linestyle='-', color="black") line.set_zorder(1) bar.set_zorder(2) plt.ylim([0, 80]) plt.xlim([0, 80000]) algos = [algo for algo in other_trends.keys()] algos.sort() for algo_index in xrange(len(algos)): algo = algos[algo_index] x_values = [x for x,y in other_trends[algo]] y_values = [y for x,y in other_trends[algo]] line_style = "-" marker = "x" if "mapred" in algo: line_style = "-" marker= "^" line, = plt.plot(x_values, y_values, lw=2, linestyle=line_style, marker=marker, color="black") line.set_zorder(1) ylabel = plt.ylabel("Time per one query [ms]") ylabel.set_fontsize(font_size) xlabel = plt.xlabel("Queries count x1000") xlabel.set_fontsize(font_size) for ytick in plt.yticks()[1]: ytick.set_fontsize(font_size) for xtick in plt.xticks()[1]: xtick.set_fontsize(font_size) if 1: print plt.xticks() xticks = [item for item in plt.xticks()[0]] xticks_labels = [str(int(item / 1000)) for item in xticks] plt.xticks(xticks, xticks_labels) plt.tight_layout() savefig("../paper/imgs/9_time_distrib_hdfs_indices.eps", transparent="True", pad_inches=0) plt.show()
identifier_body
unboxed-closures-call-sugar-autoderef.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that the call operator autoderefs when calling a bounded type parameter. #![feature(unboxed_closures)] use std::ops::FnMut; fn call_with_2<F>(x: &mut F) -> isize where F : FnMut(isize) -> isize
pub fn main() { let z = call_with_2(&mut |x| x - 22); assert_eq!(z, -20); }
{ x(2) // look ma, no `*` }
identifier_body
unboxed-closures-call-sugar-autoderef.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that the call operator autoderefs when calling a bounded type parameter. #![feature(unboxed_closures)] use std::ops::FnMut; fn call_with_2<F>(x: &mut F) -> isize where F : FnMut(isize) -> isize { x(2) // look ma, no `*` } pub fn
() { let z = call_with_2(&mut |x| x - 22); assert_eq!(z, -20); }
main
identifier_name
unboxed-closures-call-sugar-autoderef.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that the call operator autoderefs when calling a bounded type parameter. #![feature(unboxed_closures)] use std::ops::FnMut; fn call_with_2<F>(x: &mut F) -> isize where F : FnMut(isize) -> isize { x(2) // look ma, no `*` }
}
pub fn main() { let z = call_with_2(&mut |x| x - 22); assert_eq!(z, -20);
random_line_split
FindTile.js
/** * @author Richard Davey <[email protected]> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var GetTilesWithin = require('./GetTilesWithin'); /** * @callback FindTileCallback * * @param {Phaser.Tilemaps.Tile} value - The Tile. * @param {integer} index - The index of the tile. * @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects. * * @return {boolean} Return `true` if the callback should run, otherwise `false`. */ /** * Find the first tile in the given rectangular area (in tile coordinates) of the layer that * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns * true. Similar to Array.prototype.find in vanilla JS. * * @function Phaser.Tilemaps.Components.FindTile * @private * @since 3.0.0 * * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. * @param {object} [context] - The context under which the callback should be run. * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be.
* @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. * * @return {?Phaser.Tilemaps.Tile} A Tile that matches the search, or null if no Tile found */ var FindTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); return tiles.find(callback, context) || null; }; module.exports = FindTile;
* @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face.
random_line_split
lab5-b.js
var view = Ti.UI.createView({     backgroundColor:'#000',     top:0,     left:0,     width:'100%',     height:'100%',     layout:'vertical' }); // create labels, buttons, text fields var helpLabel = Titanium.UI.createLabel({ color:'#abcdef', highlightedColor:'#0f0', backgroundColor:'transparent', width:'auto', height:'auto', text:'Pick your selection and touch submit' }); var submitButton = Titanium.UI.createButton({ color:'#abcdef', top: 20, width:200, height:40, font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'}, title:'Submit' }); submitButton.addEventListener('click', function() { // do nothing right now, next lab will submit via xhr }); var radioGroup = []; var radioGroupIndex = 0; var radioSelected; function createRadioGroupButton(itemName) { var buttonView1 = Tit
iew.add(createRadioGroupButton('Fish').radioButton); view.add(createRadioGroupButton('Vegetarian').radioButton); view.add(createRadioGroupButton('Chicken').radioButton); view.add(submitButton); Ti.UI.currentWindow.add(view);
anium.UI.createView({ top: 10, left: 0, height: 50, width: 200, borderRadius: 10, backgroundColor: '#fff', index: radioGroupIndex }); var selection1 = Titanium.UI.createLabel({ text : itemName, color : '#f79e18', font : {fontSize : 40}, textAlign: 'center' }); buttonView1.add(selection1); buttonView1.addEventListener('click', function() { buttonView1.backgroundColor = '#cef7ff'; radioSelected = selection1.text; Ti.API.log("DEBUG",'selection1.text'+selection1.text); for (var i=0; i < radioGroup.length; i++) { deselect(i,index); }; }); var index = radioGroupIndex; deselect = function (i,j) { //Ti.API.log("DEBUG",'deselect:'+radioGroup[i].index); if (radioGroup[i].index != j) { radioGroup[i].radioButton.backgroundColor = '#fff'; } } radioGroupIndex = radioGroupIndex +1; var exportWidget = { radioButton: buttonView1, deselect: deselect, index: index}; radioGroup.push(exportWidget); return exportWidget; } view.add(helpLabel); v
identifier_body
lab5-b.js
var view = Ti.UI.createView({     backgroundColor:'#000',     top:0,     left:0,     width:'100%',     height:'100%',     layout:'vertical' }); // create labels, buttons, text fields var helpLabel = Titanium.UI.createLabel({ color:'#abcdef', highlightedColor:'#0f0', backgroundColor:'transparent', width:'auto', height:'auto', text:'Pick your selection and touch submit' }); var submitButton = Titanium.UI.createButton({ color:'#abcdef', top: 20, width:200, height:40, font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'}, title:'Submit' }); submitButton.addEventListener('click', function() { // do nothing right now, next lab will submit via xhr }); var radioGroup = []; var radioGroupIndex = 0; var radioSelected; function createRadioGroupButton(itemName) { var buttonView1 = Titanium.UI.createView({ top: 10, left: 0, height: 50, width: 200, borderRadius: 10, backgroundColor: '#fff', index: radioGroupIndex }); var selection1 = Titanium.UI.createLabel({ text : itemName, color : '#f79e18', font : {fontSize : 40}, textAlign: 'center' }); buttonView1.add(selection1); buttonView1.addEventListener('click', function() {
}; }); var index = radioGroupIndex; deselect = function (i,j) { //Ti.API.log("DEBUG",'deselect:'+radioGroup[i].index); if (radioGroup[i].index != j) { radioGroup[i].radioButton.backgroundColor = '#fff'; } } radioGroupIndex = radioGroupIndex +1; var exportWidget = { radioButton: buttonView1, deselect: deselect, index: index}; radioGroup.push(exportWidget); return exportWidget; } view.add(helpLabel); view.add(createRadioGroupButton('Fish').radioButton); view.add(createRadioGroupButton('Vegetarian').radioButton); view.add(createRadioGroupButton('Chicken').radioButton); view.add(submitButton); Ti.UI.currentWindow.add(view);
buttonView1.backgroundColor = '#cef7ff'; radioSelected = selection1.text; Ti.API.log("DEBUG",'selection1.text'+selection1.text); for (var i=0; i < radioGroup.length; i++) { deselect(i,index);
random_line_split
lab5-b.js
var view = Ti.UI.createView({     backgroundColor:'#000',     top:0,     left:0,     width:'100%',     height:'100%',     layout:'vertical' }); // create labels, buttons, text fields var helpLabel = Titanium.UI.createLabel({ color:'#abcdef', highlightedColor:'#0f0', backgroundColor:'transparent', width:'auto', height:'auto', text:'Pick your selection and touch submit' }); var submitButton = Titanium.UI.createButton({ color:'#abcdef', top: 20, width:200, height:40, font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'}, title:'Submit' }); submitButton.addEventListener('click', function() { // do nothing right now, next lab will submit via xhr }); var radioGroup = []; var radioGroupIndex = 0; var radioSelected; function createRadioGroupButton(itemName) { var buttonView1 = Titanium.UI.createView({ top: 10, left: 0, height: 50, width: 200, borderRadius: 10, backgroundColor: '#fff', index: radioGroupIndex }); var selection1 = Titanium.UI.createLabel({ text : itemName, color : '#f79e18', font : {fontSize : 40}, textAlign: 'center' }); buttonView1.add(selection1); buttonView1.addEventListener('click', function() { buttonView1.backgroundColor = '#cef7ff'; radioSelected = selection1.text; Ti.API.log("DEBUG",'selection1.text'+selection1.text); for (var i=0; i < radioGroup.length; i++) { deselect(i,index); }; }); var index = radioGroupIndex; deselect = function (i,j) { //Ti.API.log("DEBUG",'deselect:'+radioGroup[i].index); if (radioGroup[i].index != j) { radioGroup[i].radio
adioGroupIndex +1; var exportWidget = { radioButton: buttonView1, deselect: deselect, index: index}; radioGroup.push(exportWidget); return exportWidget; } view.add(helpLabel); view.add(createRadioGroupButton('Fish').radioButton); view.add(createRadioGroupButton('Vegetarian').radioButton); view.add(createRadioGroupButton('Chicken').radioButton); view.add(submitButton); Ti.UI.currentWindow.add(view);
Button.backgroundColor = '#fff'; } } radioGroupIndex = r
conditional_block
lab5-b.js
var view = Ti.UI.createView({     backgroundColor:'#000',     top:0,     left:0,     width:'100%',     height:'100%',     layout:'vertical' }); // create labels, buttons, text fields var helpLabel = Titanium.UI.createLabel({ color:'#abcdef', highlightedColor:'#0f0', backgroundColor:'transparent', width:'auto', height:'auto', text:'Pick your selection and touch submit' }); var submitButton = Titanium.UI.createButton({ color:'#abcdef', top: 20, width:200, height:40, font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'}, title:'Submit' }); submitButton.addEventListener('click', function() { // do nothing right now, next lab will submit via xhr }); var radioGroup = []; var radioGroupIndex = 0; var radioSelected; function createRadioGroupButton(i
View1 = Titanium.UI.createView({ top: 10, left: 0, height: 50, width: 200, borderRadius: 10, backgroundColor: '#fff', index: radioGroupIndex }); var selection1 = Titanium.UI.createLabel({ text : itemName, color : '#f79e18', font : {fontSize : 40}, textAlign: 'center' }); buttonView1.add(selection1); buttonView1.addEventListener('click', function() { buttonView1.backgroundColor = '#cef7ff'; radioSelected = selection1.text; Ti.API.log("DEBUG",'selection1.text'+selection1.text); for (var i=0; i < radioGroup.length; i++) { deselect(i,index); }; }); var index = radioGroupIndex; deselect = function (i,j) { //Ti.API.log("DEBUG",'deselect:'+radioGroup[i].index); if (radioGroup[i].index != j) { radioGroup[i].radioButton.backgroundColor = '#fff'; } } radioGroupIndex = radioGroupIndex +1; var exportWidget = { radioButton: buttonView1, deselect: deselect, index: index}; radioGroup.push(exportWidget); return exportWidget; } view.add(helpLabel); view.add(createRadioGroupButton('Fish').radioButton); view.add(createRadioGroupButton('Vegetarian').radioButton); view.add(createRadioGroupButton('Chicken').radioButton); view.add(submitButton); Ti.UI.currentWindow.add(view);
temName) { var button
identifier_name
evol.colorpicker.js
/* evol.colorpicker 3.2.1 ColorPicker widget for jQuery UI https://github.com/evoluteur/colorpicker (c) 2015 Olivier Giulieri * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var _idx=0, ua=window.navigator.userAgent, isIE=ua.indexOf("MSIE ")>0, _ie=isIE?'-ie':'', isMoz=isIE?false:/mozilla/.test(ua.toLowerCase()) && !/webkit/.test(ua.toLowerCase()), history=[], baseThemeColors=['ffffff','000000','eeece1','1f497d','4f81bd','c0504d','9bbb59','8064a2','4bacc6','f79646'], subThemeColors=['f2f2f2','7f7f7f','ddd9c3','c6d9f0','dbe5f1','f2dcdb','ebf1dd','e5e0ec','dbeef3','fdeada', 'd8d8d8','595959','c4bd97','8db3e2','b8cce4','e5b9b7','d7e3bc','ccc1d9','b7dde8','fbd5b5', 'bfbfbf','3f3f3f','938953','548dd4','95b3d7','d99694','c3d69b','b2a2c7','92cddc','fac08f', 'a5a5a5','262626','494429','17365d','366092','953734','76923c','5f497a','31859b','e36c09', '7f7f7f','0c0c0c','1d1b10','0f243e','244061','632423','4f6128','3f3151','205867','974806'], standardColors=['c00000','ff0000','ffc000','ffff00','92d050','00b050','00b0f0','0070c0','002060','7030a0'], webColors=[ ['003366','336699','3366cc','003399','000099','0000cc','000066'], ['006666','006699','0099cc','0066cc','0033cc','0000ff','3333ff','333399'], ['669999','009999','33cccc','00ccff','0099ff','0066ff','3366ff','3333cc','666699'], ['339966','00cc99','00ffcc','00ffff','33ccff','3399ff','6699ff','6666ff','6600ff','6600cc'], ['339933','00cc66','00ff99','66ffcc','66ffff','66ccff','99ccff','9999ff','9966ff','9933ff','9900ff'], ['006600','00cc00','00ff00','66ff99','99ffcc','ccffff','ccccff','cc99ff','cc66ff','cc33ff','cc00ff','9900cc'], ['003300','009933','33cc33','66ff66','99ff99','ccffcc','ffffff','ffccff','ff99ff','ff66ff','ff00ff','cc00cc','660066'], ['333300','009900','66ff33','99ff66','ccff99','ffffcc','ffcccc','ff99cc','ff66cc','ff33cc','cc0099','993399'], ['336600','669900','99ff33','ccff66','ffff99','ffcc99','ff9999','ff6699','ff3399','cc3399','990099'], ['666633','99cc00','ccff33','ffff66','ffcc66','ff9966','ff6666','ff0066','d60094','993366'], ['a58800','cccc00','ffff00','ffcc00','ff9933','ff6600','ff0033','cc0066','660033'], ['996633','cc9900','ff9900','cc6600','ff3300','ff0000','cc0000','990033'], ['663300','996600','cc3300','993300','990000','800000','993333'] ], transColor='#0000ffff', int2Hex=function(i){ var h=i.toString(16); if(h.length==1){ h='0'+h; } return h; }, st2Hex=function(s){ return int2Hex(Number(s)); }, int2Hex3=function(i){ var h=int2Hex(i); return h+h+h; }, toHex3=function(c){ if(c.length>10){ // IE9 var p1=1+c.indexOf('('), p2=c.indexOf(')'), cs=c.substring(p1,p2).split(','); return ['#',st2Hex(cs[0]),st2Hex(cs[1]),st2Hex(cs[2])].join(''); }else{ return c; } }; $.widget( "evol.colorpicker", { version: '3.2.1', options: { color: null, // example:'#31859B' showOn: 'both', // possible values: 'focus','button','both' hideButton: false, displayIndicator: true, transparentColor: false, history: true, defaultPalette: 'theme', // possible values: 'theme', 'web' strings: 'Theme Colors,Standard Colors,Web Colors,Theme Colors,Back to Palette,History,No history yet.' }, // this is only true while showing the palette until color is chosen _active: false, _create: function() { var that=this; this._paletteIdx=this.options.defaultPalette=='theme'?1:2; this._id='evo-cp'+_idx++; this._enabled=true; this.options.showOn=this.options.hideButton?'focus':this.options.showOn; switch(this.element.get(0).tagName){ case 'INPUT': var color=this.options.color, e=this.element, css=((this.options.showOn==='focus')?'':'evo-pointer ')+'evo-colorind'+(isMoz?'-ff':_ie)+(this.options.hideButton?' evo-hidden-button':''), style=''; this._isPopup=true; this._palette=null; if(color!==null){ e.val(color); }else{ var v=e.val(); if(v!==''){ color=this.options.color=v; } } if(color===transColor){ css+=' evo-transparent'; }else{ style=(color!==null)?('background-color:'+color):''; } e.addClass('colorPicker '+this._id) .wrap('<div style="width:'+(this.options.hideButton?this.element.width():this.element.width()+32)+'px;'+ (isIE?'margin-bottom:-21px;':'')+ (isMoz?'padding:1px 0;':'')+ '"></div>') .after('<div class="'+css+'" style="'+style+'"></div>') .on('keyup onpaste', function(evt){ var c=$(this).val(); if(c!=that.options.color){ that._setValue(c, true); } }); var showOn=this.options.showOn; if(showOn==='both' || showOn==='focus'){ e.on('focus', function(){ that.showPalette(); }); } if(showOn==='both' || showOn==='button'){ e.next().on('click', function(evt){ evt.stopPropagation(); that.showPalette(); }); } break; default: this._isPopup=false; this._palette=this.element.html(this._paletteHTML()) .attr('aria-haspopup','true'); this._bindColors(); } if(this.options.history){ if(color){ this._add2History(color); } if (this.options.initialHistory) { var c = this.options.initialHistory; for (var i in c){ this._add2History(c[i]); } } } }, _paletteHTML: function() { var pIdx=this._paletteIdx=Math.abs(this._paletteIdx), opts=this.options, labels=opts.strings.split(','); var h='<div class="evo-pop'+_ie+' ui-widget ui-widget-content ui-corner-all"'+ (this._isPopup?' style="position:absolute"':'')+'>'+ // palette '<span>'+this['_paletteHTML'+pIdx]()+'</span>'+ // links '<div class="evo-more"><a href="javascript:void(0)">'+labels[1+pIdx]+'</a>'; if(opts.history){ h+='<a href="javascript:void(0)" class="evo-hist">'+labels[5]+'</a>'; } h+='</div>'; // indicator if(opts.displayIndicator){ h+=this._colorIndHTML(this.options.color)+this._colorIndHTML(''); } h+='</div>'; return h; }, _colorIndHTML: function(c) { var css=isIE?'evo-colorbox-ie ':'', style=''; if(c){ if(c===transColor){ css+='evo-transparent'; }else{ style='background-color:'+c; } }else{ style='display:none'; } return '<div class="evo-color" style="float:left">'+ '<div style="'+style+'" class="'+css+'"></div><span>'+ // class="evo-colortxt-ie" (c?c:'')+'</span></div>'; }, _paletteHTML1: function() { var opts=this.options, labels=opts.strings.split(','), oTD='<td style="background-color:#', cTD=isIE?'"><div style="width:2px;"></div></td>':'"><span/></td>', oTRTH='<tr><th colspan="10" class="ui-widget-content">'; // base theme colors var h='<table class="evo-palette'+_ie+'">'+oTRTH+labels[0]+'</th></tr><tr>'; for(var i=0;i<10;i++){ h+=oTD+baseThemeColors[i]+cTD; } h+='</tr>'; if(!isIE){ h+='<tr><th colspan="10"></th></tr>'; } h+='<tr class="top">'; // theme colors for(i=0;i<10;i++){ h+=oTD+subThemeColors[i]+cTD; } for(var r=1;r<4;r++){ h+='</tr><tr class="in">'; for(i=0;i<10;i++){ h+=oTD+subThemeColors[r*10+i]+cTD; } } h+='</tr><tr class="bottom">'; for(i=40;i<50;i++){ h+=oTD+subThemeColors[i]+cTD; } h+='</tr>'+oTRTH; // transparent color if(opts.transparentColor){ h+='<div class="evo-transparent evo-tr-box"></div>'; } h+=labels[1]+'</th></tr><tr>'; // standard colors for(i=0;i<10;i++){ h+=oTD+standardColors[i]+cTD; } h+='</tr></table>'; return h; }, _paletteHTML2: function() { var i, iMax, oTD='<td style="background-color:#', cTD=isIE?'"><div style="width:5px;"></div></td>':'"><span/></td>', oTableTR='<table class="evo-palette2'+_ie+'"><tr>', cTableTR='</tr></table>'; var h='<div class="evo-palcenter">'; // hexagon colors for(var r=0,rMax=webColors.length;r<rMax;r++){ h+=oTableTR; var cs=webColors[r]; for(i=0,iMax=cs.length;i<iMax;i++){ h+=oTD+cs[i]+cTD; } h+=cTableTR; } h+='<div class="evo-sep"/>'; // gray scale colors var h2=''; h+=oTableTR; for(i=255;i>10;i-=10){ h+=oTD+int2Hex3(i)+cTD; i-=10; h2+=oTD+int2Hex3(i)+cTD; } h+=cTableTR+oTableTR+h2+cTableTR+'</div>'; return h; }, _switchPalette: function(link) { if(this._enabled){ var idx, content, label, labels=this.options.strings.split(','); if($(link).hasClass('evo-hist')){ // history var h=['<table class="evo-palette"><tr><th class="ui-widget-content">', labels[5], '</th></tr></tr></table>', '<div class="evo-cHist">']; if(history.length===0){ h.push('<p>&nbsp;',labels[6],'</p>'); }else{ for(var i=history.length-1;i>-1;i--){ if(history[i].length===9){ h.push('<div class="evo-transparent"></div>'); }else{ h.push('<div style="background-color:',history[i],'"></div>'); } } } h.push('</div>'); idx=-this._paletteIdx; content=h.join(''); label=labels[4]; }else{ // palette if(this._paletteIdx<0){ idx=-this._paletteIdx; this._palette.find('.evo-hist').show(); }else{ idx=(this._paletteIdx==2)?1:2; } content=this['_paletteHTML'+idx](); label=labels[idx+1]; this._paletteIdx=idx; } this._paletteIdx=idx; var e=this._palette.find('.evo-more') .prev().html(content).end() .children().eq(0).html(label); if(idx<0){ e.next().hide(); } } }, showPalette: function() { if(this._enabled){ this._active=true; $('.colorPicker').not('.'+this._id).colorpicker('hidePalette'); if(this._palette===null){ this._palette=this.element.next() .after(this._paletteHTML()).next() .on('click',function(evt){ evt.stopPropagation(); }); this._bindColors(); var that=this; if(this._isPopup){ $(document.body).on('click.'+that._id, function(evt){ if(evt.target!=that.element.get(0)){ that.hidePalette(); } }).on('keyup.'+that._id, function(evt){ if(evt.keyCode===27){ that.hidePalette(); } }); } } } return this; }, hidePalette: function() { if(this._isPopup && this._palette){ $(document.body).off('click.'+this._id); var that=this; this._palette.off('mouseover click', 'td,.evo-transparent') .fadeOut(function(){ that._palette.remove(); that._palette=that._cTxt=null; }) .find('.evo-more a').off('click'); } return this; }, _bindColors: function() { var that=this, opts=this.options, es=this._palette.find('div.evo-color'), sel=opts.history?'td,.evo-cHist>div':'td'; if(opts.transparentColor){ sel+=',.evo-transparent'; } this._cTxt1=es.eq(0).children().eq(0); this._cTxt2=es.eq(1).children().eq(0); this._palette .on('click', sel, function(evt){ if(that._enabled){ var $this=$(this); that._setValue($this.hasClass('evo-transparent')?transColor:toHex3($this.attr('style').substring(17))); that._active=false; } }) .on('mouseover', sel, function(evt){ if(that._enabled){ var $this=$(this), c=$this.hasClass('evo-transparent')?transColor:toHex3($this.attr('style').substring(17)); if(that.options.displayIndicator){ that._setColorInd(c,2); } if(that._active){ that.element.trigger('mouseover.color', c); } } }) .find('.evo-more a').on('click', function(){ that._switchPalette(this); }); }, val: function(value) { if (typeof value=='undefined') { return this.options.color; }else{ this._setValue(value); return this; } }, _setValue: function(c, noHide) { c = c.replace(/ /g,''); this.options.color=c; if(this._isPopup){ if(!noHide){ this.hidePalette(); } this._setBoxColor(this.element.val(c).next(), c); }else{ this._setColorInd(c,1); } if(this.options.history && this._paletteIdx>0){ this._add2History(c); } this.element.trigger('change.color', c); }, _setColorInd: function(c, idx) { var $box=this['_cTxt'+idx]; this._setBoxColor($box, c); $box.next().html(c); }, _setBoxColor: function($box, c) { if(c===transColor){ $box.addClass('evo-transparent') .removeAttr('style'); }else{ $box.removeClass('evo-transparent')
}, _setOption: function(key, value) { if(key=='color'){ this._setValue(value, true); }else{ this.options[key]=value; } }, _add2History: function(c) { var iMax=history.length; // skip color if already in history for(var i=0;i<iMax;i++){ if(c==history[i]){ return; } } // limit of 28 colors in history if(iMax>27){ history.shift(); } // add to history history.push(c); }, clear: function(){ this.hidePalette().val(''); }, enable: function() { var e=this.element; if(this._isPopup){ e.removeAttr('disabled'); }else{ e.css({ 'opacity': '1', 'pointer-events': 'auto' }); } if(this.options.showOn!=='focus'){ this.element.next().addClass('evo-pointer'); } e.removeAttr('aria-disabled'); this._enabled=true; return this; }, disable: function() { var e=this.element; if(this._isPopup){ e.attr('disabled', 'disabled'); }else{ this.hidePalette(); e.css({ 'opacity': '0.3', 'pointer-events': 'none' }); } if(this.options.showOn!=='focus'){ this.element.next().removeClass('evo-pointer'); } e.attr('aria-disabled','true'); this._enabled=false; return this; }, isDisabled: function() { return !this._enabled; }, destroy: function() { $(document.body).off('click.'+this._id); if(this._palette){ this._palette.off('mouseover click', 'td,.evo-cHist>div,.evo-transparent') .find('.evo-more a').off('click'); if(this._isPopup){ this._palette.remove(); } this._palette=this._cTxt=null; } if(this._isPopup){ this.element .next().off('click').remove() .end().off('focus').unwrap(); } this.element.removeClass('colorPicker '+this.id).empty(); $.Widget.prototype.destroy.call(this); } }); })(jQuery);
.attr('style','background-color:'+c); }
random_line_split
evol.colorpicker.js
/* evol.colorpicker 3.2.1 ColorPicker widget for jQuery UI https://github.com/evoluteur/colorpicker (c) 2015 Olivier Giulieri * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var _idx=0, ua=window.navigator.userAgent, isIE=ua.indexOf("MSIE ")>0, _ie=isIE?'-ie':'', isMoz=isIE?false:/mozilla/.test(ua.toLowerCase()) && !/webkit/.test(ua.toLowerCase()), history=[], baseThemeColors=['ffffff','000000','eeece1','1f497d','4f81bd','c0504d','9bbb59','8064a2','4bacc6','f79646'], subThemeColors=['f2f2f2','7f7f7f','ddd9c3','c6d9f0','dbe5f1','f2dcdb','ebf1dd','e5e0ec','dbeef3','fdeada', 'd8d8d8','595959','c4bd97','8db3e2','b8cce4','e5b9b7','d7e3bc','ccc1d9','b7dde8','fbd5b5', 'bfbfbf','3f3f3f','938953','548dd4','95b3d7','d99694','c3d69b','b2a2c7','92cddc','fac08f', 'a5a5a5','262626','494429','17365d','366092','953734','76923c','5f497a','31859b','e36c09', '7f7f7f','0c0c0c','1d1b10','0f243e','244061','632423','4f6128','3f3151','205867','974806'], standardColors=['c00000','ff0000','ffc000','ffff00','92d050','00b050','00b0f0','0070c0','002060','7030a0'], webColors=[ ['003366','336699','3366cc','003399','000099','0000cc','000066'], ['006666','006699','0099cc','0066cc','0033cc','0000ff','3333ff','333399'], ['669999','009999','33cccc','00ccff','0099ff','0066ff','3366ff','3333cc','666699'], ['339966','00cc99','00ffcc','00ffff','33ccff','3399ff','6699ff','6666ff','6600ff','6600cc'], ['339933','00cc66','00ff99','66ffcc','66ffff','66ccff','99ccff','9999ff','9966ff','9933ff','9900ff'], ['006600','00cc00','00ff00','66ff99','99ffcc','ccffff','ccccff','cc99ff','cc66ff','cc33ff','cc00ff','9900cc'], ['003300','009933','33cc33','66ff66','99ff99','ccffcc','ffffff','ffccff','ff99ff','ff66ff','ff00ff','cc00cc','660066'], ['333300','009900','66ff33','99ff66','ccff99','ffffcc','ffcccc','ff99cc','ff66cc','ff33cc','cc0099','993399'], ['336600','669900','99ff33','ccff66','ffff99','ffcc99','ff9999','ff6699','ff3399','cc3399','990099'], ['666633','99cc00','ccff33','ffff66','ffcc66','ff9966','ff6666','ff0066','d60094','993366'], ['a58800','cccc00','ffff00','ffcc00','ff9933','ff6600','ff0033','cc0066','660033'], ['996633','cc9900','ff9900','cc6600','ff3300','ff0000','cc0000','990033'], ['663300','996600','cc3300','993300','990000','800000','993333'] ], transColor='#0000ffff', int2Hex=function(i){ var h=i.toString(16); if(h.length==1){ h='0'+h; } return h; }, st2Hex=function(s){ return int2Hex(Number(s)); }, int2Hex3=function(i){ var h=int2Hex(i); return h+h+h; }, toHex3=function(c){ if(c.length>10){ // IE9 var p1=1+c.indexOf('('), p2=c.indexOf(')'), cs=c.substring(p1,p2).split(','); return ['#',st2Hex(cs[0]),st2Hex(cs[1]),st2Hex(cs[2])].join(''); }else{ return c; } }; $.widget( "evol.colorpicker", { version: '3.2.1', options: { color: null, // example:'#31859B' showOn: 'both', // possible values: 'focus','button','both' hideButton: false, displayIndicator: true, transparentColor: false, history: true, defaultPalette: 'theme', // possible values: 'theme', 'web' strings: 'Theme Colors,Standard Colors,Web Colors,Theme Colors,Back to Palette,History,No history yet.' }, // this is only true while showing the palette until color is chosen _active: false, _create: function() { var that=this; this._paletteIdx=this.options.defaultPalette=='theme'?1:2; this._id='evo-cp'+_idx++; this._enabled=true; this.options.showOn=this.options.hideButton?'focus':this.options.showOn; switch(this.element.get(0).tagName){ case 'INPUT': var color=this.options.color, e=this.element, css=((this.options.showOn==='focus')?'':'evo-pointer ')+'evo-colorind'+(isMoz?'-ff':_ie)+(this.options.hideButton?' evo-hidden-button':''), style=''; this._isPopup=true; this._palette=null; if(color!==null){ e.val(color); }else{ var v=e.val(); if(v!==''){ color=this.options.color=v; } } if(color===transColor)
else{ style=(color!==null)?('background-color:'+color):''; } e.addClass('colorPicker '+this._id) .wrap('<div style="width:'+(this.options.hideButton?this.element.width():this.element.width()+32)+'px;'+ (isIE?'margin-bottom:-21px;':'')+ (isMoz?'padding:1px 0;':'')+ '"></div>') .after('<div class="'+css+'" style="'+style+'"></div>') .on('keyup onpaste', function(evt){ var c=$(this).val(); if(c!=that.options.color){ that._setValue(c, true); } }); var showOn=this.options.showOn; if(showOn==='both' || showOn==='focus'){ e.on('focus', function(){ that.showPalette(); }); } if(showOn==='both' || showOn==='button'){ e.next().on('click', function(evt){ evt.stopPropagation(); that.showPalette(); }); } break; default: this._isPopup=false; this._palette=this.element.html(this._paletteHTML()) .attr('aria-haspopup','true'); this._bindColors(); } if(this.options.history){ if(color){ this._add2History(color); } if (this.options.initialHistory) { var c = this.options.initialHistory; for (var i in c){ this._add2History(c[i]); } } } }, _paletteHTML: function() { var pIdx=this._paletteIdx=Math.abs(this._paletteIdx), opts=this.options, labels=opts.strings.split(','); var h='<div class="evo-pop'+_ie+' ui-widget ui-widget-content ui-corner-all"'+ (this._isPopup?' style="position:absolute"':'')+'>'+ // palette '<span>'+this['_paletteHTML'+pIdx]()+'</span>'+ // links '<div class="evo-more"><a href="javascript:void(0)">'+labels[1+pIdx]+'</a>'; if(opts.history){ h+='<a href="javascript:void(0)" class="evo-hist">'+labels[5]+'</a>'; } h+='</div>'; // indicator if(opts.displayIndicator){ h+=this._colorIndHTML(this.options.color)+this._colorIndHTML(''); } h+='</div>'; return h; }, _colorIndHTML: function(c) { var css=isIE?'evo-colorbox-ie ':'', style=''; if(c){ if(c===transColor){ css+='evo-transparent'; }else{ style='background-color:'+c; } }else{ style='display:none'; } return '<div class="evo-color" style="float:left">'+ '<div style="'+style+'" class="'+css+'"></div><span>'+ // class="evo-colortxt-ie" (c?c:'')+'</span></div>'; }, _paletteHTML1: function() { var opts=this.options, labels=opts.strings.split(','), oTD='<td style="background-color:#', cTD=isIE?'"><div style="width:2px;"></div></td>':'"><span/></td>', oTRTH='<tr><th colspan="10" class="ui-widget-content">'; // base theme colors var h='<table class="evo-palette'+_ie+'">'+oTRTH+labels[0]+'</th></tr><tr>'; for(var i=0;i<10;i++){ h+=oTD+baseThemeColors[i]+cTD; } h+='</tr>'; if(!isIE){ h+='<tr><th colspan="10"></th></tr>'; } h+='<tr class="top">'; // theme colors for(i=0;i<10;i++){ h+=oTD+subThemeColors[i]+cTD; } for(var r=1;r<4;r++){ h+='</tr><tr class="in">'; for(i=0;i<10;i++){ h+=oTD+subThemeColors[r*10+i]+cTD; } } h+='</tr><tr class="bottom">'; for(i=40;i<50;i++){ h+=oTD+subThemeColors[i]+cTD; } h+='</tr>'+oTRTH; // transparent color if(opts.transparentColor){ h+='<div class="evo-transparent evo-tr-box"></div>'; } h+=labels[1]+'</th></tr><tr>'; // standard colors for(i=0;i<10;i++){ h+=oTD+standardColors[i]+cTD; } h+='</tr></table>'; return h; }, _paletteHTML2: function() { var i, iMax, oTD='<td style="background-color:#', cTD=isIE?'"><div style="width:5px;"></div></td>':'"><span/></td>', oTableTR='<table class="evo-palette2'+_ie+'"><tr>', cTableTR='</tr></table>'; var h='<div class="evo-palcenter">'; // hexagon colors for(var r=0,rMax=webColors.length;r<rMax;r++){ h+=oTableTR; var cs=webColors[r]; for(i=0,iMax=cs.length;i<iMax;i++){ h+=oTD+cs[i]+cTD; } h+=cTableTR; } h+='<div class="evo-sep"/>'; // gray scale colors var h2=''; h+=oTableTR; for(i=255;i>10;i-=10){ h+=oTD+int2Hex3(i)+cTD; i-=10; h2+=oTD+int2Hex3(i)+cTD; } h+=cTableTR+oTableTR+h2+cTableTR+'</div>'; return h; }, _switchPalette: function(link) { if(this._enabled){ var idx, content, label, labels=this.options.strings.split(','); if($(link).hasClass('evo-hist')){ // history var h=['<table class="evo-palette"><tr><th class="ui-widget-content">', labels[5], '</th></tr></tr></table>', '<div class="evo-cHist">']; if(history.length===0){ h.push('<p>&nbsp;',labels[6],'</p>'); }else{ for(var i=history.length-1;i>-1;i--){ if(history[i].length===9){ h.push('<div class="evo-transparent"></div>'); }else{ h.push('<div style="background-color:',history[i],'"></div>'); } } } h.push('</div>'); idx=-this._paletteIdx; content=h.join(''); label=labels[4]; }else{ // palette if(this._paletteIdx<0){ idx=-this._paletteIdx; this._palette.find('.evo-hist').show(); }else{ idx=(this._paletteIdx==2)?1:2; } content=this['_paletteHTML'+idx](); label=labels[idx+1]; this._paletteIdx=idx; } this._paletteIdx=idx; var e=this._palette.find('.evo-more') .prev().html(content).end() .children().eq(0).html(label); if(idx<0){ e.next().hide(); } } }, showPalette: function() { if(this._enabled){ this._active=true; $('.colorPicker').not('.'+this._id).colorpicker('hidePalette'); if(this._palette===null){ this._palette=this.element.next() .after(this._paletteHTML()).next() .on('click',function(evt){ evt.stopPropagation(); }); this._bindColors(); var that=this; if(this._isPopup){ $(document.body).on('click.'+that._id, function(evt){ if(evt.target!=that.element.get(0)){ that.hidePalette(); } }).on('keyup.'+that._id, function(evt){ if(evt.keyCode===27){ that.hidePalette(); } }); } } } return this; }, hidePalette: function() { if(this._isPopup && this._palette){ $(document.body).off('click.'+this._id); var that=this; this._palette.off('mouseover click', 'td,.evo-transparent') .fadeOut(function(){ that._palette.remove(); that._palette=that._cTxt=null; }) .find('.evo-more a').off('click'); } return this; }, _bindColors: function() { var that=this, opts=this.options, es=this._palette.find('div.evo-color'), sel=opts.history?'td,.evo-cHist>div':'td'; if(opts.transparentColor){ sel+=',.evo-transparent'; } this._cTxt1=es.eq(0).children().eq(0); this._cTxt2=es.eq(1).children().eq(0); this._palette .on('click', sel, function(evt){ if(that._enabled){ var $this=$(this); that._setValue($this.hasClass('evo-transparent')?transColor:toHex3($this.attr('style').substring(17))); that._active=false; } }) .on('mouseover', sel, function(evt){ if(that._enabled){ var $this=$(this), c=$this.hasClass('evo-transparent')?transColor:toHex3($this.attr('style').substring(17)); if(that.options.displayIndicator){ that._setColorInd(c,2); } if(that._active){ that.element.trigger('mouseover.color', c); } } }) .find('.evo-more a').on('click', function(){ that._switchPalette(this); }); }, val: function(value) { if (typeof value=='undefined') { return this.options.color; }else{ this._setValue(value); return this; } }, _setValue: function(c, noHide) { c = c.replace(/ /g,''); this.options.color=c; if(this._isPopup){ if(!noHide){ this.hidePalette(); } this._setBoxColor(this.element.val(c).next(), c); }else{ this._setColorInd(c,1); } if(this.options.history && this._paletteIdx>0){ this._add2History(c); } this.element.trigger('change.color', c); }, _setColorInd: function(c, idx) { var $box=this['_cTxt'+idx]; this._setBoxColor($box, c); $box.next().html(c); }, _setBoxColor: function($box, c) { if(c===transColor){ $box.addClass('evo-transparent') .removeAttr('style'); }else{ $box.removeClass('evo-transparent') .attr('style','background-color:'+c); } }, _setOption: function(key, value) { if(key=='color'){ this._setValue(value, true); }else{ this.options[key]=value; } }, _add2History: function(c) { var iMax=history.length; // skip color if already in history for(var i=0;i<iMax;i++){ if(c==history[i]){ return; } } // limit of 28 colors in history if(iMax>27){ history.shift(); } // add to history history.push(c); }, clear: function(){ this.hidePalette().val(''); }, enable: function() { var e=this.element; if(this._isPopup){ e.removeAttr('disabled'); }else{ e.css({ 'opacity': '1', 'pointer-events': 'auto' }); } if(this.options.showOn!=='focus'){ this.element.next().addClass('evo-pointer'); } e.removeAttr('aria-disabled'); this._enabled=true; return this; }, disable: function() { var e=this.element; if(this._isPopup){ e.attr('disabled', 'disabled'); }else{ this.hidePalette(); e.css({ 'opacity': '0.3', 'pointer-events': 'none' }); } if(this.options.showOn!=='focus'){ this.element.next().removeClass('evo-pointer'); } e.attr('aria-disabled','true'); this._enabled=false; return this; }, isDisabled: function() { return !this._enabled; }, destroy: function() { $(document.body).off('click.'+this._id); if(this._palette){ this._palette.off('mouseover click', 'td,.evo-cHist>div,.evo-transparent') .find('.evo-more a').off('click'); if(this._isPopup){ this._palette.remove(); } this._palette=this._cTxt=null; } if(this._isPopup){ this.element .next().off('click').remove() .end().off('focus').unwrap(); } this.element.removeClass('colorPicker '+this.id).empty(); $.Widget.prototype.destroy.call(this); } }); })(jQuery);
{ css+=' evo-transparent'; }
conditional_block
pokelists.py
rare_pokemon = ( "Dragonite", "Flareon", "Exeggutor", "Arcanine", "Victreebel", "Magmar", "Charizard", "Nidoking", "Gengar", "Vileplume", "Rapidash", "Raichu", "Machamp", "Venusaur", "Electabuzz", "Cloyster", "Golduck", "Starmie", "Gyarados", "Jolteon", "Weezing", "Weepinbell", "Kabutops", "Vaporeon", "Lapras", "Blastoise", "Alakazam", "Magneton", "Slowbro", "Nidoqueen", "Pinsir", "Aerodactyl", "Dodrio", "Snorlax", "Muk", "Poliwrath", "Omastar", "Clefable", "Primeape", "Kingler", "Golem", "Ninetales", "Scyther", "Seadra", "Seaking", "Venomoth", "Jynx", "Haunter", "Pidgeot", "Tentacruel", "Dragonair", "Wigglytuff", "Fearow", "Ponyta", "Rhydon", "Arbok", "Golbat", "Tangela", "Hypno", "Parasect", "Gloom", "Charmeleon", "Bellsprout", "Dewgong", "Persian", "Porygon", "Ivysaur", "Growlithe", "Machoke", "Mr. Mime", "Sandslash", "Electrode", "Kadabra", "Tauros", "Hitmonlee", "Dugtrio", "Kabuto", "Beedrill", "Butterfree", "Wartortle", "Kangaskhan", "Graveler", "Marowak", "Farfetch'd", "Hitmonchan", "Koffing", "Gastly", "Omanyte", "Staryu", "Dratini", "Charmander", "Magnemite", "Lickitung", "Bulbasaur", "Grimer", "Pikachu", "Mankey", "Horsea", "Shellder", "Machop", "Slowpoke", "Rhyhorn",
"Alakazam", "Magneton", "Nidoqueen", "Aerodactyl", "Snorlax", "Muk", "Poliwrath", "Omastar", "Primeape", "Kingler", "Golem", "Ninetales", "Jynx", "Haunter", "Tentacruel", "Dragonair", "Wigglytuff", "Tangela", "Ponyta", "Hypno", "Charmeleon", "Dewgong", "Persian", "Porygon", "Ivysaur", "Machoke", "Mr. Mime", "Sandslash", "Kadabra", "Hitmonlee", "Dugtrio", "Kabuto", "Butterfree", "Kangaskhan", "Graveler", "Marowak", "Farfetch'd", "Hitmonchan", "Omanyte", "Magnemite", "Lickitung", "Grimer", "Mankey", "Shellder", "Abra", "Onix", "Chansey")
"Exeggcute", "Abra", "Diglett", "Tentacool", "Geodude", "Vulpix", "Seel", "Drowzee", "Sandshrew", "Onix", "Chansey") ultra_rare_pokemon = ( "Dragonite", "Flareon", "Exeggutor", "Arcanine", "Victreebel", "Magmar", "Charizard", "Nidoking", "Gengar", "Vileplume", "Rapidash", "Raichu", "Machamp", "Venusaur", "Electabuzz", "Cloyster", "Gyarados", "Kabutops", "Lapras", "Blastoise",
random_line_split
SaveAsDialog.tsx
/* * 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/. */ import * as React from 'react'; import { styled } from '@csegames/linaria/react'; import * as CONFIG from 'shared/config'; import { TabbedDialog, DialogTab, DialogButton } from 'shared/TabbedDialog'; import { Box } from 'shared/Box'; import { PopupDialog, Container } from './PopupDialog'; const DIALOG_SIZE: React.CSSProperties = { width: '400px', height: '230px', top: '0', bottom: '0', left: '0', right: '0', margin: 'auto', }; const Input = styled.input` background-color: transparent; width: 100%; border: 1px solid #333; padding: 5px; outline: none; &:focus { box-shadow: 0 0 2px ${CONFIG.MENU_HIGHLIGHT_BORDER_COLOR}; } `; interface SaveAsProps { label: string; saveAs: (name: string) => void; onClose: () => void; style?: any; } interface SaveAsState { name: string; } const SAVE: DialogButton = { label: 'Save' }; export class SaveAsDialog extends React.PureComponent<SaveAsProps, SaveAsState> { constructor(props: SaveAsProps)
public render() { return ( <PopupDialog style={DIALOG_SIZE}> <TabbedDialog title='save as' heading={false} onClose={this.onClose}> {(tab: DialogButton) => <DialogTab buttons={[SAVE]} onAction={this.onAction}> <Container> {this.props.label}: <Box padding={false} style={{ margin: 0 }}> <Input value={this.state.name} onChange={this.onChange}/> </Box> </Container> </DialogTab> } </TabbedDialog> </PopupDialog> ); } private onChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ name: e.currentTarget.value }); } private onAction = (action: DialogButton) => { switch (action) { case SAVE: this.props.saveAs(this.state.name); break; } } private onClose = () => { this.props.onClose(); } } export default SaveAsDialog;
{ super(props); this.state = { name: '' }; }
identifier_body
SaveAsDialog.tsx
/* * 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/. */ import * as React from 'react'; import { styled } from '@csegames/linaria/react'; import * as CONFIG from 'shared/config'; import { TabbedDialog, DialogTab, DialogButton } from 'shared/TabbedDialog'; import { Box } from 'shared/Box'; import { PopupDialog, Container } from './PopupDialog'; const DIALOG_SIZE: React.CSSProperties = { width: '400px', height: '230px', top: '0',
bottom: '0', left: '0', right: '0', margin: 'auto', }; const Input = styled.input` background-color: transparent; width: 100%; border: 1px solid #333; padding: 5px; outline: none; &:focus { box-shadow: 0 0 2px ${CONFIG.MENU_HIGHLIGHT_BORDER_COLOR}; } `; interface SaveAsProps { label: string; saveAs: (name: string) => void; onClose: () => void; style?: any; } interface SaveAsState { name: string; } const SAVE: DialogButton = { label: 'Save' }; export class SaveAsDialog extends React.PureComponent<SaveAsProps, SaveAsState> { constructor(props: SaveAsProps) { super(props); this.state = { name: '' }; } public render() { return ( <PopupDialog style={DIALOG_SIZE}> <TabbedDialog title='save as' heading={false} onClose={this.onClose}> {(tab: DialogButton) => <DialogTab buttons={[SAVE]} onAction={this.onAction}> <Container> {this.props.label}: <Box padding={false} style={{ margin: 0 }}> <Input value={this.state.name} onChange={this.onChange}/> </Box> </Container> </DialogTab> } </TabbedDialog> </PopupDialog> ); } private onChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ name: e.currentTarget.value }); } private onAction = (action: DialogButton) => { switch (action) { case SAVE: this.props.saveAs(this.state.name); break; } } private onClose = () => { this.props.onClose(); } } export default SaveAsDialog;
random_line_split
SaveAsDialog.tsx
/* * 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/. */ import * as React from 'react'; import { styled } from '@csegames/linaria/react'; import * as CONFIG from 'shared/config'; import { TabbedDialog, DialogTab, DialogButton } from 'shared/TabbedDialog'; import { Box } from 'shared/Box'; import { PopupDialog, Container } from './PopupDialog'; const DIALOG_SIZE: React.CSSProperties = { width: '400px', height: '230px', top: '0', bottom: '0', left: '0', right: '0', margin: 'auto', }; const Input = styled.input` background-color: transparent; width: 100%; border: 1px solid #333; padding: 5px; outline: none; &:focus { box-shadow: 0 0 2px ${CONFIG.MENU_HIGHLIGHT_BORDER_COLOR}; } `; interface SaveAsProps { label: string; saveAs: (name: string) => void; onClose: () => void; style?: any; } interface SaveAsState { name: string; } const SAVE: DialogButton = { label: 'Save' }; export class SaveAsDialog extends React.PureComponent<SaveAsProps, SaveAsState> {
(props: SaveAsProps) { super(props); this.state = { name: '' }; } public render() { return ( <PopupDialog style={DIALOG_SIZE}> <TabbedDialog title='save as' heading={false} onClose={this.onClose}> {(tab: DialogButton) => <DialogTab buttons={[SAVE]} onAction={this.onAction}> <Container> {this.props.label}: <Box padding={false} style={{ margin: 0 }}> <Input value={this.state.name} onChange={this.onChange}/> </Box> </Container> </DialogTab> } </TabbedDialog> </PopupDialog> ); } private onChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ name: e.currentTarget.value }); } private onAction = (action: DialogButton) => { switch (action) { case SAVE: this.props.saveAs(this.state.name); break; } } private onClose = () => { this.props.onClose(); } } export default SaveAsDialog;
constructor
identifier_name
test_repositories.py
import pytest from cfme.infrastructure import repositories from utils.update import update from utils.wait import TimedOutError, wait_for @pytest.mark.tier(2) @pytest.mark.meta(blockers=[1188427]) def test_repository_crud(soft_assert, random_string, request):
repo_name = 'Test Repo {}'.format(random_string) repo = repositories.Repository(repo_name, '//testhost/share/path') request.addfinalizer(repo.delete) # create repo.create() # read assert repo.exists # update with update(repo): repo.name = 'Updated {}'.format(repo_name) with soft_assert.catch_assert(): assert repo.exists, 'Repository rename failed' # Only change the name back if renaming succeeded with update(repo): repo.name = repo_name # delete repo.delete() try: wait_for(lambda: not repo.exists) except TimedOutError: raise AssertionError('failed to delete repository')
identifier_body
test_repositories.py
import pytest from cfme.infrastructure import repositories from utils.update import update from utils.wait import TimedOutError, wait_for @pytest.mark.tier(2) @pytest.mark.meta(blockers=[1188427]) def test_repository_crud(soft_assert, random_string, request): repo_name = 'Test Repo {}'.format(random_string) repo = repositories.Repository(repo_name, '//testhost/share/path') request.addfinalizer(repo.delete) # create repo.create()
# read assert repo.exists # update with update(repo): repo.name = 'Updated {}'.format(repo_name) with soft_assert.catch_assert(): assert repo.exists, 'Repository rename failed' # Only change the name back if renaming succeeded with update(repo): repo.name = repo_name # delete repo.delete() try: wait_for(lambda: not repo.exists) except TimedOutError: raise AssertionError('failed to delete repository')
random_line_split
test_repositories.py
import pytest from cfme.infrastructure import repositories from utils.update import update from utils.wait import TimedOutError, wait_for @pytest.mark.tier(2) @pytest.mark.meta(blockers=[1188427]) def
(soft_assert, random_string, request): repo_name = 'Test Repo {}'.format(random_string) repo = repositories.Repository(repo_name, '//testhost/share/path') request.addfinalizer(repo.delete) # create repo.create() # read assert repo.exists # update with update(repo): repo.name = 'Updated {}'.format(repo_name) with soft_assert.catch_assert(): assert repo.exists, 'Repository rename failed' # Only change the name back if renaming succeeded with update(repo): repo.name = repo_name # delete repo.delete() try: wait_for(lambda: not repo.exists) except TimedOutError: raise AssertionError('failed to delete repository')
test_repository_crud
identifier_name
aarch64.rs
use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use std::{io, slice, mem}; use std::io::Write; fn main() { let mut ops = dynasmrt::aarch64::Assembler::new().unwrap(); let string = "Hello World!"; dynasm!(ops ; .arch aarch64 ; ->hello: ; .bytes string.as_bytes() ; .align 4 ; ->print: ; .qword print as _ ); let hello = ops.offset(); dynasm!(ops ; .arch aarch64 ; adr x0, ->hello ; movz x1, string.len() as u32 ; ldr x9, ->print ; str x30, [sp, #-16]! ; blr x9 ; ldr x30, [sp], #16 ; ret ); let buf = ops.finalize().unwrap(); let hello_fn: extern "C" fn() -> bool = unsafe { mem::transmute(buf.ptr(hello)) }; assert!(hello_fn()); } pub extern "C" fn print(buffer: *const u8, length: u64) -> bool
{ io::stdout() .write_all(unsafe { slice::from_raw_parts(buffer, length as usize) }) .is_ok() }
identifier_body
aarch64.rs
use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use std::{io, slice, mem}; use std::io::Write; fn main() { let mut ops = dynasmrt::aarch64::Assembler::new().unwrap(); let string = "Hello World!"; dynasm!(ops ; .arch aarch64 ; ->hello: ; .bytes string.as_bytes() ; .align 4 ; ->print: ; .qword print as _ ); let hello = ops.offset(); dynasm!(ops ; .arch aarch64 ; adr x0, ->hello ; movz x1, string.len() as u32 ; ldr x9, ->print ; str x30, [sp, #-16]! ; blr x9 ; ldr x30, [sp], #16 ; ret ); let buf = ops.finalize().unwrap(); let hello_fn: extern "C" fn() -> bool = unsafe { mem::transmute(buf.ptr(hello)) }; assert!(hello_fn()); } pub extern "C" fn
(buffer: *const u8, length: u64) -> bool { io::stdout() .write_all(unsafe { slice::from_raw_parts(buffer, length as usize) }) .is_ok() }
print
identifier_name
aarch64.rs
use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use std::{io, slice, mem}; use std::io::Write; fn main() { let mut ops = dynasmrt::aarch64::Assembler::new().unwrap(); let string = "Hello World!"; dynasm!(ops ; .arch aarch64 ; ->hello: ; .bytes string.as_bytes() ; .align 4 ; ->print: ; .qword print as _ ); let hello = ops.offset(); dynasm!(ops ; .arch aarch64 ; adr x0, ->hello ; movz x1, string.len() as u32 ; ldr x9, ->print ; str x30, [sp, #-16]! ; blr x9 ; ldr x30, [sp], #16 ; ret );
} pub extern "C" fn print(buffer: *const u8, length: u64) -> bool { io::stdout() .write_all(unsafe { slice::from_raw_parts(buffer, length as usize) }) .is_ok() }
let buf = ops.finalize().unwrap(); let hello_fn: extern "C" fn() -> bool = unsafe { mem::transmute(buf.ptr(hello)) }; assert!(hello_fn());
random_line_split
test_phone2numeric.py
from django.template.defaultfilters import phone2numeric_filter from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import render, setup class Phone2numericTests(SimpleTestCase): @setup({'phone2numeric01': '{{ a|phone2numeric }} {{ b|phone2numeric }}'}) def test_phone2numeric01(self): output = render( 'phone2numeric01', {'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, ) self.assertEqual(output, '&lt;1-800-2255-63&gt; <1-800-2255-63>') @setup({'phone2numeric02': '{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}'}) def test_phone2numeric02(self): output = render( 'phone2numeric02', {'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, ) self.assertEqual(output, '<1-800-2255-63> <1-800-2255-63>') @setup({'phone2numeric03': '{{ a|phone2numeric }}'}) def test_phone2numeric03(self): output = render( 'phone2numeric03', {'a': 'How razorback-jumping frogs can level six piqued gymnasts!'}, ) self.assertEqual( output, '469 729672225-5867464 37647 226 53835 749 747833 49662787!' ) class FunctionTests(SimpleTestCase): def test_phone2numeric(self):
self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377')
identifier_body
test_phone2numeric.py
from django.template.defaultfilters import phone2numeric_filter from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import render, setup class
(SimpleTestCase): @setup({'phone2numeric01': '{{ a|phone2numeric }} {{ b|phone2numeric }}'}) def test_phone2numeric01(self): output = render( 'phone2numeric01', {'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, ) self.assertEqual(output, '&lt;1-800-2255-63&gt; <1-800-2255-63>') @setup({'phone2numeric02': '{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}'}) def test_phone2numeric02(self): output = render( 'phone2numeric02', {'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, ) self.assertEqual(output, '<1-800-2255-63> <1-800-2255-63>') @setup({'phone2numeric03': '{{ a|phone2numeric }}'}) def test_phone2numeric03(self): output = render( 'phone2numeric03', {'a': 'How razorback-jumping frogs can level six piqued gymnasts!'}, ) self.assertEqual( output, '469 729672225-5867464 37647 226 53835 749 747833 49662787!' ) class FunctionTests(SimpleTestCase): def test_phone2numeric(self): self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377')
Phone2numericTests
identifier_name
test_phone2numeric.py
from django.template.defaultfilters import phone2numeric_filter from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import render, setup class Phone2numericTests(SimpleTestCase): @setup({'phone2numeric01': '{{ a|phone2numeric }} {{ b|phone2numeric }}'}) def test_phone2numeric01(self): output = render( 'phone2numeric01', {'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, ) self.assertEqual(output, '&lt;1-800-2255-63&gt; <1-800-2255-63>') @setup({'phone2numeric02': '{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}'}) def test_phone2numeric02(self): output = render( 'phone2numeric02',
{'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, ) self.assertEqual(output, '<1-800-2255-63> <1-800-2255-63>') @setup({'phone2numeric03': '{{ a|phone2numeric }}'}) def test_phone2numeric03(self): output = render( 'phone2numeric03', {'a': 'How razorback-jumping frogs can level six piqued gymnasts!'}, ) self.assertEqual( output, '469 729672225-5867464 37647 226 53835 749 747833 49662787!' ) class FunctionTests(SimpleTestCase): def test_phone2numeric(self): self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377')
random_line_split
ironrouter.d.ts
declare module Iron { function controller(): any; interface RouterStatic { bodyParser: any; hooks: any; } var Router: RouterStatic; type HookCallback = (this: RouteController) => void; export type RouteHook = HookCallback | string; export type RouteHooks = RouteHook | RouteHook[]; type RouteCallback = (this: RouteController) => void; interface RouterOptions { layoutTemplate?: string; notFoundTemplate?: string; loadingTemplate?: string; waitOn?: () => DDP.SubscriptionHandle[]; } interface Route { getName(): string; path(params?: any, options?: any): string;
put(func: RouteCallback): Route; delete(func: RouteCallback): Route; } interface RouterGoOptions { replaceState?: boolean; query?: string | { [key: string]: string | number | boolean }; } interface RouteController { stop(): void; next(): void; wait(handle: DDP.SubscriptionHandle); ready(): boolean; render(template: string, options?: { data?: any; to?: string }); redirect(nameOrPath: string, params?: any, options?: RouterGoOptions); route: Route; params: { query: any; hash: string; [param: string]: string; }; data: any; request: any; response: any; layout: any; _rendered: boolean; _layout: { _regions: { [name: string]: { _template: string; }; }; }; } interface RouteOptions { name?: string; path?: string | RegExp; where?: string; action?: RouteCallback; onRun?: RouteHooks; onRerun?: RouteHooks; onBeforeAction?: RouteHooks; onAfterAction?: RouteHooks; onStop?: RouteHooks; template?: string; } interface RouteHookOptions { only?: string[]; except?: string[]; } interface RouteHookEntry { hook: RouteHook; options: RouteHookOptions; } interface Router { configure(options: RouterOptions): void; route(path: string, func: RouteCallback, options?: RouteOptions): Route; route(path: string, options?: RouteOptions): Route; go(nameOrPath: string, params?: any, options?: RouterGoOptions): void; current(): RouteController; onRun(hook: RouteHook, options?: RouteHookOptions): void; onRerun(hook: RouteHook, options?: RouteHookOptions): void; onBeforeAction(hook: RouteHook, options?: RouteHookOptions): void; onAfterAction(hook: RouteHook, options?: RouteHookOptions): void; onStop(hook: RouteHook, options?: RouteHookOptions): void; plugin(plugin: string, options?: any): void; configureBodyParsers(): void; url(routeName: string, params?: any, options?: RouterGoOptions): string; routes: { [name: string]: Route; }; _globalHooks: { onRun: RouteHookEntry[]; }; } } declare var Router: Iron.Router; declare module Iron.Url { interface UrlQueryObject { [s: string]: string; } interface UrlObject { rootUrl: string; originalUrl: string; href: string; protocol: string; auth: string; host: string; hostname: string; port: string; origin: string; path: string; pathname: string; search: string; query: string; queryObject: UrlQueryObject; hash: string; slashes: boolean; } function parse(url: string): UrlObject; }
get(func: RouteCallback): Route; post(func: RouteCallback): Route;
random_line_split
store.rs
pub struct StoreStats { pub num_keys: u64, pub total_memory_in_bytes: u64, } impl StoreStats { pub fn new() -> StoreStats { StoreStats { num_keys: 0, total_memory_in_bytes: 0, } } } pub trait ValueStore<K, V> { fn get(&self, key: &K) -> Option<&V>; fn set(&mut self, key: K, value: V); fn delete(&mut self, key: &K) -> bool; fn delete_many(&mut self, keys: &Vec<K>); fn clear(&mut self); fn stats(&self) -> &StoreStats; } pub trait EvictionPolicy<K, V> { // Metadata management fn update_metadata_on_get(&mut self, key: K); fn update_metadata_on_set(&mut self, key: K, value: V); fn delete_metadata(&mut self, keys: &Vec<K>); fn clear_metadata(&mut self); // Eviction polict logic fn should_evict_keys(&self, store_stats: &StoreStats) -> bool; fn choose_keys_to_evict(&self) -> Vec<K>; } pub struct Store<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> { value_store: KVStore, eviction_policy: EvPolicy, // Hack to allow this struct to take the ValueStore and EvictionPolicy // traits and constrain them to having the same types for the keys (K) and // the values (V). // TODO: find a better way to achieve this __hack1: Option<K>, __hack2: Option<V>, } impl<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> Store<K, V, KVStore, EvPolicy> { pub fn new(value_store: KVStore, eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy> { Store { value_store: value_store, eviction_policy: eviction_policy, __hack1: None, __hack2: None, } } pub fn get(&mut self, key: &K) -> Option<&V>
pub fn set(&mut self, key: K, value: V) { self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_set(key.clone(), value.clone()); self.value_store.set(key, value); } fn evict_keys_if_necessary(&mut self) { let should_evict = self.eviction_policy.should_evict_keys( self.value_store.stats()); if should_evict { let keys_to_evict = self.eviction_policy.choose_keys_to_evict(); self.value_store.delete_many(&keys_to_evict); self.eviction_policy.delete_metadata(&keys_to_evict); } } }
{ self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_get(key.clone()); self.value_store.get(key) }
identifier_body
store.rs
pub struct StoreStats { pub num_keys: u64, pub total_memory_in_bytes: u64, } impl StoreStats { pub fn new() -> StoreStats { StoreStats { num_keys: 0, total_memory_in_bytes: 0, } } } pub trait ValueStore<K, V> { fn get(&self, key: &K) -> Option<&V>; fn set(&mut self, key: K, value: V); fn delete(&mut self, key: &K) -> bool; fn delete_many(&mut self, keys: &Vec<K>); fn clear(&mut self); fn stats(&self) -> &StoreStats; } pub trait EvictionPolicy<K, V> { // Metadata management fn update_metadata_on_get(&mut self, key: K); fn update_metadata_on_set(&mut self, key: K, value: V); fn delete_metadata(&mut self, keys: &Vec<K>); fn clear_metadata(&mut self); // Eviction polict logic fn should_evict_keys(&self, store_stats: &StoreStats) -> bool; fn choose_keys_to_evict(&self) -> Vec<K>; } pub struct Store<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> { value_store: KVStore, eviction_policy: EvPolicy, // Hack to allow this struct to take the ValueStore and EvictionPolicy // traits and constrain them to having the same types for the keys (K) and // the values (V). // TODO: find a better way to achieve this __hack1: Option<K>, __hack2: Option<V>, } impl<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> Store<K, V, KVStore, EvPolicy> { pub fn new(value_store: KVStore, eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy> { Store { value_store: value_store, eviction_policy: eviction_policy, __hack1: None, __hack2: None, } } pub fn get(&mut self, key: &K) -> Option<&V> { self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_get(key.clone()); self.value_store.get(key) } pub fn set(&mut self, key: K, value: V) { self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_set(key.clone(), value.clone()); self.value_store.set(key, value); } fn evict_keys_if_necessary(&mut self) { let should_evict = self.eviction_policy.should_evict_keys( self.value_store.stats()); if should_evict
} }
{ let keys_to_evict = self.eviction_policy.choose_keys_to_evict(); self.value_store.delete_many(&keys_to_evict); self.eviction_policy.delete_metadata(&keys_to_evict); }
conditional_block
store.rs
pub struct StoreStats { pub num_keys: u64, pub total_memory_in_bytes: u64, } impl StoreStats { pub fn new() -> StoreStats { StoreStats { num_keys: 0, total_memory_in_bytes: 0, } }
fn set(&mut self, key: K, value: V); fn delete(&mut self, key: &K) -> bool; fn delete_many(&mut self, keys: &Vec<K>); fn clear(&mut self); fn stats(&self) -> &StoreStats; } pub trait EvictionPolicy<K, V> { // Metadata management fn update_metadata_on_get(&mut self, key: K); fn update_metadata_on_set(&mut self, key: K, value: V); fn delete_metadata(&mut self, keys: &Vec<K>); fn clear_metadata(&mut self); // Eviction polict logic fn should_evict_keys(&self, store_stats: &StoreStats) -> bool; fn choose_keys_to_evict(&self) -> Vec<K>; } pub struct Store<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> { value_store: KVStore, eviction_policy: EvPolicy, // Hack to allow this struct to take the ValueStore and EvictionPolicy // traits and constrain them to having the same types for the keys (K) and // the values (V). // TODO: find a better way to achieve this __hack1: Option<K>, __hack2: Option<V>, } impl<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> Store<K, V, KVStore, EvPolicy> { pub fn new(value_store: KVStore, eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy> { Store { value_store: value_store, eviction_policy: eviction_policy, __hack1: None, __hack2: None, } } pub fn get(&mut self, key: &K) -> Option<&V> { self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_get(key.clone()); self.value_store.get(key) } pub fn set(&mut self, key: K, value: V) { self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_set(key.clone(), value.clone()); self.value_store.set(key, value); } fn evict_keys_if_necessary(&mut self) { let should_evict = self.eviction_policy.should_evict_keys( self.value_store.stats()); if should_evict { let keys_to_evict = self.eviction_policy.choose_keys_to_evict(); self.value_store.delete_many(&keys_to_evict); self.eviction_policy.delete_metadata(&keys_to_evict); } } }
} pub trait ValueStore<K, V> { fn get(&self, key: &K) -> Option<&V>;
random_line_split
store.rs
pub struct StoreStats { pub num_keys: u64, pub total_memory_in_bytes: u64, } impl StoreStats { pub fn new() -> StoreStats { StoreStats { num_keys: 0, total_memory_in_bytes: 0, } } } pub trait ValueStore<K, V> { fn get(&self, key: &K) -> Option<&V>; fn set(&mut self, key: K, value: V); fn delete(&mut self, key: &K) -> bool; fn delete_many(&mut self, keys: &Vec<K>); fn clear(&mut self); fn stats(&self) -> &StoreStats; } pub trait EvictionPolicy<K, V> { // Metadata management fn update_metadata_on_get(&mut self, key: K); fn update_metadata_on_set(&mut self, key: K, value: V); fn delete_metadata(&mut self, keys: &Vec<K>); fn clear_metadata(&mut self); // Eviction polict logic fn should_evict_keys(&self, store_stats: &StoreStats) -> bool; fn choose_keys_to_evict(&self) -> Vec<K>; } pub struct Store<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> { value_store: KVStore, eviction_policy: EvPolicy, // Hack to allow this struct to take the ValueStore and EvictionPolicy // traits and constrain them to having the same types for the keys (K) and // the values (V). // TODO: find a better way to achieve this __hack1: Option<K>, __hack2: Option<V>, } impl<K: Clone, V: Clone, KVStore: ValueStore<K, V>, EvPolicy: EvictionPolicy<K, V>> Store<K, V, KVStore, EvPolicy> { pub fn new(value_store: KVStore, eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy> { Store { value_store: value_store, eviction_policy: eviction_policy, __hack1: None, __hack2: None, } } pub fn
(&mut self, key: &K) -> Option<&V> { self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_get(key.clone()); self.value_store.get(key) } pub fn set(&mut self, key: K, value: V) { self.evict_keys_if_necessary(); self.eviction_policy.update_metadata_on_set(key.clone(), value.clone()); self.value_store.set(key, value); } fn evict_keys_if_necessary(&mut self) { let should_evict = self.eviction_policy.should_evict_keys( self.value_store.stats()); if should_evict { let keys_to_evict = self.eviction_policy.choose_keys_to_evict(); self.value_store.delete_many(&keys_to_evict); self.eviction_policy.delete_metadata(&keys_to_evict); } } }
get
identifier_name
transition.js
/** * @fileoverview transition parser/implementation - still WIP * * @author Tony Parisi */ goog.provide('glam.TransitionElement'); goog.require('glam.AnimationElement'); glam.TransitionElement.DEFAULT_DURATION = glam.AnimationElement.DEFAULT_DURATION; glam.TransitionElement.DEFAULT_TIMING_FUNCTION = glam.AnimationElement.DEFAULT_TIMING_FUNCTION; // transition:transform 2s, background-color 5s linear 2s; glam.TransitionElement.parse = function(docelt, style, obj) { var transition = style.transition || ""; var transitions = { };
var i, len = comps.length; for (i = 0; i < len; i++) { var comp = comps[i]; if (comp) { var params = comp.split(" "); if (params[0] == "") params.shift(); var propname = params[0]; var duration = params[1]; var timingFunction = params[2] || glam.TransitionElement.DEFAULT_TIMING_FUNCTION; var delay = params[3] || ""; duration = glam.AnimationElement.parseTime(duration); timingFunction = glam.AnimationElement.parseTimingFunction(timingFunction); delay = glam.AnimationElement.parseTime(delay); transitions[propname] = { duration : duration, timingFunction : timingFunction, delay : delay }; } } }
var comps = transition.split(",");
random_line_split
transition.js
/** * @fileoverview transition parser/implementation - still WIP * * @author Tony Parisi */ goog.provide('glam.TransitionElement'); goog.require('glam.AnimationElement'); glam.TransitionElement.DEFAULT_DURATION = glam.AnimationElement.DEFAULT_DURATION; glam.TransitionElement.DEFAULT_TIMING_FUNCTION = glam.AnimationElement.DEFAULT_TIMING_FUNCTION; // transition:transform 2s, background-color 5s linear 2s; glam.TransitionElement.parse = function(docelt, style, obj) { var transition = style.transition || ""; var transitions = { }; var comps = transition.split(","); var i, len = comps.length; for (i = 0; i < len; i++)
}
{ var comp = comps[i]; if (comp) { var params = comp.split(" "); if (params[0] == "") params.shift(); var propname = params[0]; var duration = params[1]; var timingFunction = params[2] || glam.TransitionElement.DEFAULT_TIMING_FUNCTION; var delay = params[3] || ""; duration = glam.AnimationElement.parseTime(duration); timingFunction = glam.AnimationElement.parseTimingFunction(timingFunction); delay = glam.AnimationElement.parseTime(delay); transitions[propname] = { duration : duration, timingFunction : timingFunction, delay : delay }; } }
conditional_block
iComponent.ts
export interface IAfterGuiAttachedParams { eComponent: HTMLElement; }
export interface ICellRendererAfterGuiAttachedParams extends IAfterGuiAttachedParams { eParentOfValue: HTMLElement; eGridCell: HTMLElement; } export interface IComponent<T, Z extends IAfterGuiAttachedParams> { /** Return the DOM element of your editor, this is what the grid puts into the DOM */ getGui(): HTMLElement|string; /** Gets called once by grid after editing is finished - if your editor needs to do any cleanup, do it here */ destroy?(): void; /** A hook to perform any necessary operation just after the gui for this component has been renderer in the screen. If the filter popup is closed and reopened, this method is called each time the filter is shown. This is useful for any logic that requires attachment before executing, such as putting focus on a particular DOM element. The params has one callback method 'hidePopup', which you can call at any later point to hide the popup - good if you have an 'Apply' button and you want to hide the popup after it is pressed. */ afterGuiAttached?(params?: Z): void; /** The init(params) method is called on the filter once. See below for details on the parameters. */ init?(params: T): void; }
export interface IFilterAfterGuiAttachedParams extends IAfterGuiAttachedParams { hidePopup: () => void; }
random_line_split
widgets_helpers.js
if (Meteor.isClient) { Template.widgetDistanceInput.helpers({ currentDistance: function(){ var pj = Session.get('active-pj'); return pj.info.distance_target; }, currentDistanceMts: function(){ var pj = Session.get('active-pj'); return Math.floor(pj.info.distance_target * 0.3048); } }); Template.widgetRoundTypeInput.helpers({ roundTypeStyle: function(val){ var pj = Session.get('active-pj'); return pj.info.round_type != val?'':'btn-primary'; } }); Template.widgetCombatManeuver.helpers({ cmb: function(){ var pj = Session.get('active-pj'); var cmb = 0; if(pj){ cmb += parseInt(Tablas.core.classes[pj.info.class].getBaseAttackBonus(pj.info.experience.level)[0]); cmb += parseInt(pj.modificadores.str); cmb += parseInt(pj.info.combat_maneuvers.bonus); cmb += parseInt(Tablas.core.charSize[pj.info.size].special_modifier); } return cmb; }, cmd: function(){ var pj = Session.get('active-pj'); var cmd = 10; if(pj)
return cmd; }, }); }
{ cmd += parseInt(Tablas.core.classes[pj.info.class].getBaseAttackBonus(pj.info.experience.level)[0]); cmd += parseInt(pj.modificadores.str); cmd += parseInt(pj.modificadores.dex); cmd += parseInt(pj.info.combat_maneuvers.defense); cmd += parseInt(Tablas.core.charSize[pj.info.size].special_modifier); }
conditional_block
widgets_helpers.js
if (Meteor.isClient) { Template.widgetDistanceInput.helpers({ currentDistance: function(){ var pj = Session.get('active-pj'); return pj.info.distance_target; }, currentDistanceMts: function(){ var pj = Session.get('active-pj'); return Math.floor(pj.info.distance_target * 0.3048); } }); Template.widgetRoundTypeInput.helpers({ roundTypeStyle: function(val){ var pj = Session.get('active-pj'); return pj.info.round_type != val?'':'btn-primary'; } }); Template.widgetCombatManeuver.helpers({ cmb: function(){ var pj = Session.get('active-pj'); var cmb = 0; if(pj){
return cmb; }, cmd: function(){ var pj = Session.get('active-pj'); var cmd = 10; if(pj){ cmd += parseInt(Tablas.core.classes[pj.info.class].getBaseAttackBonus(pj.info.experience.level)[0]); cmd += parseInt(pj.modificadores.str); cmd += parseInt(pj.modificadores.dex); cmd += parseInt(pj.info.combat_maneuvers.defense); cmd += parseInt(Tablas.core.charSize[pj.info.size].special_modifier); } return cmd; }, }); }
cmb += parseInt(Tablas.core.classes[pj.info.class].getBaseAttackBonus(pj.info.experience.level)[0]); cmb += parseInt(pj.modificadores.str); cmb += parseInt(pj.info.combat_maneuvers.bonus); cmb += parseInt(Tablas.core.charSize[pj.info.size].special_modifier); }
random_line_split
contact-form.js
$(document).ready(function() { $('#feedbackForm input') .not('.optional,.no-asterisk') .after('<span class="glyphicon glyphicon-asterisk form-control-feedback"></span>'); $("#feedbackSubmit").click(function() { var $btn = $(this); $btn.button('loading'); contactForm.clearErrors(); //do a little client-side validation -- check that each field has a value and e-mail field is in proper format var hasErrors = false; $('#feedbackForm input,textarea').not('.optional').each(function() { var $this = $(this); if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) { hasErrors = true; contactForm.addError($(this)); } }); var $email = $('#email'); if (!contactForm.isValidEmail($email.val())) { hasErrors = true; contactForm.addError($email); } //if there are any errors return without sending e-mail if (hasErrors) { $btn.button('reset'); return false; } //send the feedback e-mail $.ajax({ type: "POST", url: "library/sendmail.php", data: $("#feedbackForm").serialize(), success: function(data) { contactForm.addAjaxMessage(data.message, false); contactForm.clearForm(); //get new Captcha on success $('#captcha').attr('src', 'library/vender/securimage/securimage_show.php?' + Math.random()); }, error: function(response) { contactForm.addAjaxMessage(response.responseJSON.message, true); }, complete: function() { $btn.button('reset'); } }); return false; }); $('#feedbackForm input').change(function () { var asteriskSpan = $(this).siblings('.glyphicon-asterisk'); if ($(this).val()) { asteriskSpan.css('color', '#00FF00'); } else
}); }); //namespace as not to pollute global namespace var contactForm = { isValidEmail: function (email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); }, clearErrors: function () { $('#emailAlert').remove(); $('#feedbackForm .help-block').hide(); $('#feedbackForm .form-group').removeClass('has-error'); }, clearForm: function () { $('.glyphicon-asterisk').css('color', 'black'); $('#feedbackForm input,textarea').val(""); }, addError: function ($input) { $input.siblings('.help-block').show(); $input.parent('.form-group').addClass('has-error'); }, addAjaxMessage: function(msg, isError) { $("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>'); } };
{ asteriskSpan.css('color', 'black'); }
conditional_block
contact-form.js
$(document).ready(function() { $('#feedbackForm input') .not('.optional,.no-asterisk') .after('<span class="glyphicon glyphicon-asterisk form-control-feedback"></span>'); $("#feedbackSubmit").click(function() { var $btn = $(this); $btn.button('loading'); contactForm.clearErrors(); //do a little client-side validation -- check that each field has a value and e-mail field is in proper format var hasErrors = false; $('#feedbackForm input,textarea').not('.optional').each(function() { var $this = $(this); if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) { hasErrors = true; contactForm.addError($(this)); } }); var $email = $('#email'); if (!contactForm.isValidEmail($email.val())) { hasErrors = true; contactForm.addError($email); } //if there are any errors return without sending e-mail if (hasErrors) { $btn.button('reset'); return false; } //send the feedback e-mail $.ajax({ type: "POST", url: "library/sendmail.php", data: $("#feedbackForm").serialize(), success: function(data) { contactForm.addAjaxMessage(data.message, false); contactForm.clearForm(); //get new Captcha on success $('#captcha').attr('src', 'library/vender/securimage/securimage_show.php?' + Math.random()); }, error: function(response) { contactForm.addAjaxMessage(response.responseJSON.message, true); }, complete: function() { $btn.button('reset'); } }); return false; }); $('#feedbackForm input').change(function () { var asteriskSpan = $(this).siblings('.glyphicon-asterisk'); if ($(this).val()) { asteriskSpan.css('color', '#00FF00'); } else { asteriskSpan.css('color', 'black'); } }); }); //namespace as not to pollute global namespace var contactForm = { isValidEmail: function (email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); }, clearErrors: function () { $('#emailAlert').remove(); $('#feedbackForm .help-block').hide(); $('#feedbackForm .form-group').removeClass('has-error'); }, clearForm: function () { $('.glyphicon-asterisk').css('color', 'black'); $('#feedbackForm input,textarea').val(""); },
addAjaxMessage: function(msg, isError) { $("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>'); } };
addError: function ($input) { $input.siblings('.help-block').show(); $input.parent('.form-group').addClass('has-error'); },
random_line_split
boxCap.py
""" Capturing and analyzing the box information Author: Lyu Yaopengfei Date: 23-May-2016 """ import cv2 import threading import time from PIL import Image import Lego.dsOperation as dso import Lego.imgPreprocessing as imgprep from Lego.ocr import tesserOcr capImg = None resImg = None stopFlat = 0 lock = threading.Lock() def capFrame(cap): global capImg global stopFlat while(1): lock.acquire() try: _,capImg = cap.read() finally: lock.release() if (stopFlat > 0): break clickCnt = 0 clickFlag = 0 def detect_circle(event,x,y,flags,param): global clickFlag if event==cv2.EVENT_LBUTTONUP: clickFlag = clickFlag+1 elif event==cv2.EVENT_RBUTTONUP: clickFlag = -1 # lock.acquire() # try: # cv2.imwrite('cap.png',capImg) # finally: # clickCnt = clickCnt+1 # lock.release() # detect the useful information from the selected image def detectImg(logoAffinePos,img,idx): _, _, _, _, affinedCropedImg, rtnFlag = logoAffinePos.rcvAffinedAll(img) if (rtnFlag is False): return None,None,None,False filtedCroped = imgprep.imgFilter(affinedCropedImg) filtedCroped = cv2.cvtColor(filtedCroped,cv2.COLOR_GRAY2RGB) filtedCropedPIL = Image.fromarray(filtedCroped) numStr = tesserOcr(filtedCropedPIL) return affinedCropedImg,filtedCroped,numStr,True def analyseBoxInfo(bds,imgfolder): maxCnt = 0 tempCnt = 0 tempNumSet = set(bds.tempNumList) bds.setImgFolder(imgfolder) for item in tempNumSet: tempCnt = bds.tempNumList.count(item) if(tempCnt > maxCnt): maxCnt = tempCnt bds.number = item def exportLog(lf, expStr): print(expStr) expStr = expStr+'\n' lf.writelines(expStr) if __name__ == '__main__': bxnm = input('Input the box name: ') # time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) bx1 = dso.boxds(bxnm) settingInfo = open('../data/setting','r') settingInfo.readline() PATH = settingInfo.readline().strip().lstrip().rstrip(',') DATAPATH = settingInfo.readline().strip().lstrip().rstrip(',') FEATURE_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') MATERIAL_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') BOX_DATA_PATH = settingInfo.readline().strip().lstrip().rstrip(',') LOG_PATH = settingInfo.readline().strip().lstrip().rstrip(',') curTime = time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) LOG_PATH = LOG_PATH+curTime+bx1.boxname+'.log' logFile = open(LOG_PATH,'w+') boxData = open(BOX_DATA_PATH,'r') logoTp = cv2.imread(MATERIAL_IMG_FOLDER + 'purelogo256.png') logoAffinePos = imgprep.LogoAffinePos(logoTp) cv2.namedWindow('capFrame') cv2.setMouseCallback('capFrame',detect_circle) VWIDTH = 1280 VHIGH = 720 cap = cv2.VideoCapture(0) cap.set(3,VWIDTH) cap.set(4,VHIGH) cap.read();cap.read();cap.read() tCapFrame = threading.Thread(target=capFrame, args=(cap,)) tCapFrame.start() while(capImg is None): pass dtrtnFlag = False showFlag = 0 while(1): if ((cv2.waitKey(1) & 0xFF == 27) | (clickCnt>=6) ): stopFlat = 1 break resImg = capImg.copy() showImg = resImg.copy() logoContourPts,logoContour,rtnFlag = logoAffinePos.extLegoLogo(resImg, minArea=5000) if (rtnFlag is True): # draw contour we finding cv2.drawContours(showImg, [logoContourPts], -1, (0,255,0), 2) cPts,rtnFlag = logoAffinePos.extQuadrangleCpts(logoContourPts, logoContour) if (rtnFlag is True): # draw corner points we finding for idx, cPt in enumerate(cPts): cPt = cPt.flatten() ptsize = int(logoAffinePos.estLength/20) showImg[cPt[1]-ptsize:cPt[1]+ptsize,cPt[0]-ptsize:cPt[0]+ptsize,:] = [255,255,0] showImg = cv2.resize(showImg,(0,0),fx=0.4,fy=0.4) # right click, discard the data and re-capturing if(clickFlag < 0): clickFlag = 0 exportLog(logFile, 'Data was discarded') cv2.destroyWindow('filted') # capturing image if(clickFlag is 0): dtrtnFlag = False showFlag = 0 cv2.putText(showImg,'Capturing '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' picture',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) # fisrt time left click, detect the image and output the result elif(clickFlag is 1): if(dtrtnFlag is False): affinedCropedImg,filtedCroped,numStr,dtrtnFlag = detectImg(logoAffinePos,resImg,clickCnt) if(dtrtnFlag is False): # if detect result is False, set clickFlag 0, re-capturing clickFlag = 0 exportLog(logFile, 'Detecting fault, re-capturing') elif(dtrtnFlag is True): cv2.imshow('filted',filtedCroped) cv2.moveWindow('filted',50+int(0.4*VWIDTH),50) exportLog(logFile, bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' OCR: '+str(numStr)) dtrtnFlag = None else: cv2.putText(showImg,'Do you save this result? Lclick Save, Rclick Discard',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) elif(clickFlag is 2):
else: clickFlag = 0 cv2.destroyWindow('filted') cv2.imshow('capFrame',showImg) analyseBoxInfo(bx1,FEATURE_IMG_FOLDER) dso.dsWrite(BOX_DATA_PATH,bx1) print('\n') logFile.close() boxData.close() cap.release() cv2.destroyAllWindows()
exportLog(logFile, 'Saving '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' data') imgName = bx1.boxname+'_'+str(clickCnt)+'.tiff' savingPath = FEATURE_IMG_FOLDER + imgName savingPath2 = FEATURE_IMG_FOLDER + 'color/c' + imgName cv2.imwrite(savingPath, filtedCroped) cv2.imwrite(savingPath2, affinedCropedImg) bx1.setSingleFeatureImgsName(dso.SUF_DEF[clickCnt], imgName) exportLog(logFile, '--------Finish capturing--------\n') if(numStr is not None): bx1.appendTempNumList(numStr) clickCnt = clickCnt + 1 clickFlag = 0 cv2.destroyWindow('filted')
conditional_block
boxCap.py
""" Capturing and analyzing the box information Author: Lyu Yaopengfei Date: 23-May-2016 """ import cv2 import threading import time from PIL import Image import Lego.dsOperation as dso import Lego.imgPreprocessing as imgprep from Lego.ocr import tesserOcr capImg = None resImg = None stopFlat = 0 lock = threading.Lock() def capFrame(cap):
clickCnt = 0 clickFlag = 0 def detect_circle(event,x,y,flags,param): global clickFlag if event==cv2.EVENT_LBUTTONUP: clickFlag = clickFlag+1 elif event==cv2.EVENT_RBUTTONUP: clickFlag = -1 # lock.acquire() # try: # cv2.imwrite('cap.png',capImg) # finally: # clickCnt = clickCnt+1 # lock.release() # detect the useful information from the selected image def detectImg(logoAffinePos,img,idx): _, _, _, _, affinedCropedImg, rtnFlag = logoAffinePos.rcvAffinedAll(img) if (rtnFlag is False): return None,None,None,False filtedCroped = imgprep.imgFilter(affinedCropedImg) filtedCroped = cv2.cvtColor(filtedCroped,cv2.COLOR_GRAY2RGB) filtedCropedPIL = Image.fromarray(filtedCroped) numStr = tesserOcr(filtedCropedPIL) return affinedCropedImg,filtedCroped,numStr,True def analyseBoxInfo(bds,imgfolder): maxCnt = 0 tempCnt = 0 tempNumSet = set(bds.tempNumList) bds.setImgFolder(imgfolder) for item in tempNumSet: tempCnt = bds.tempNumList.count(item) if(tempCnt > maxCnt): maxCnt = tempCnt bds.number = item def exportLog(lf, expStr): print(expStr) expStr = expStr+'\n' lf.writelines(expStr) if __name__ == '__main__': bxnm = input('Input the box name: ') # time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) bx1 = dso.boxds(bxnm) settingInfo = open('../data/setting','r') settingInfo.readline() PATH = settingInfo.readline().strip().lstrip().rstrip(',') DATAPATH = settingInfo.readline().strip().lstrip().rstrip(',') FEATURE_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') MATERIAL_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') BOX_DATA_PATH = settingInfo.readline().strip().lstrip().rstrip(',') LOG_PATH = settingInfo.readline().strip().lstrip().rstrip(',') curTime = time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) LOG_PATH = LOG_PATH+curTime+bx1.boxname+'.log' logFile = open(LOG_PATH,'w+') boxData = open(BOX_DATA_PATH,'r') logoTp = cv2.imread(MATERIAL_IMG_FOLDER + 'purelogo256.png') logoAffinePos = imgprep.LogoAffinePos(logoTp) cv2.namedWindow('capFrame') cv2.setMouseCallback('capFrame',detect_circle) VWIDTH = 1280 VHIGH = 720 cap = cv2.VideoCapture(0) cap.set(3,VWIDTH) cap.set(4,VHIGH) cap.read();cap.read();cap.read() tCapFrame = threading.Thread(target=capFrame, args=(cap,)) tCapFrame.start() while(capImg is None): pass dtrtnFlag = False showFlag = 0 while(1): if ((cv2.waitKey(1) & 0xFF == 27) | (clickCnt>=6) ): stopFlat = 1 break resImg = capImg.copy() showImg = resImg.copy() logoContourPts,logoContour,rtnFlag = logoAffinePos.extLegoLogo(resImg, minArea=5000) if (rtnFlag is True): # draw contour we finding cv2.drawContours(showImg, [logoContourPts], -1, (0,255,0), 2) cPts,rtnFlag = logoAffinePos.extQuadrangleCpts(logoContourPts, logoContour) if (rtnFlag is True): # draw corner points we finding for idx, cPt in enumerate(cPts): cPt = cPt.flatten() ptsize = int(logoAffinePos.estLength/20) showImg[cPt[1]-ptsize:cPt[1]+ptsize,cPt[0]-ptsize:cPt[0]+ptsize,:] = [255,255,0] showImg = cv2.resize(showImg,(0,0),fx=0.4,fy=0.4) # right click, discard the data and re-capturing if(clickFlag < 0): clickFlag = 0 exportLog(logFile, 'Data was discarded') cv2.destroyWindow('filted') # capturing image if(clickFlag is 0): dtrtnFlag = False showFlag = 0 cv2.putText(showImg,'Capturing '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' picture',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) # fisrt time left click, detect the image and output the result elif(clickFlag is 1): if(dtrtnFlag is False): affinedCropedImg,filtedCroped,numStr,dtrtnFlag = detectImg(logoAffinePos,resImg,clickCnt) if(dtrtnFlag is False): # if detect result is False, set clickFlag 0, re-capturing clickFlag = 0 exportLog(logFile, 'Detecting fault, re-capturing') elif(dtrtnFlag is True): cv2.imshow('filted',filtedCroped) cv2.moveWindow('filted',50+int(0.4*VWIDTH),50) exportLog(logFile, bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' OCR: '+str(numStr)) dtrtnFlag = None else: cv2.putText(showImg,'Do you save this result? Lclick Save, Rclick Discard',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) elif(clickFlag is 2): exportLog(logFile, 'Saving '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' data') imgName = bx1.boxname+'_'+str(clickCnt)+'.tiff' savingPath = FEATURE_IMG_FOLDER + imgName savingPath2 = FEATURE_IMG_FOLDER + 'color/c' + imgName cv2.imwrite(savingPath, filtedCroped) cv2.imwrite(savingPath2, affinedCropedImg) bx1.setSingleFeatureImgsName(dso.SUF_DEF[clickCnt], imgName) exportLog(logFile, '--------Finish capturing--------\n') if(numStr is not None): bx1.appendTempNumList(numStr) clickCnt = clickCnt + 1 clickFlag = 0 cv2.destroyWindow('filted') else: clickFlag = 0 cv2.destroyWindow('filted') cv2.imshow('capFrame',showImg) analyseBoxInfo(bx1,FEATURE_IMG_FOLDER) dso.dsWrite(BOX_DATA_PATH,bx1) print('\n') logFile.close() boxData.close() cap.release() cv2.destroyAllWindows()
global capImg global stopFlat while(1): lock.acquire() try: _,capImg = cap.read() finally: lock.release() if (stopFlat > 0): break
identifier_body
boxCap.py
""" Capturing and analyzing the box information Author: Lyu Yaopengfei Date: 23-May-2016 """ import cv2 import threading import time from PIL import Image import Lego.dsOperation as dso import Lego.imgPreprocessing as imgprep from Lego.ocr import tesserOcr capImg = None resImg = None stopFlat = 0 lock = threading.Lock() def capFrame(cap): global capImg global stopFlat while(1): lock.acquire() try: _,capImg = cap.read() finally: lock.release() if (stopFlat > 0): break clickCnt = 0 clickFlag = 0 def detect_circle(event,x,y,flags,param): global clickFlag if event==cv2.EVENT_LBUTTONUP: clickFlag = clickFlag+1 elif event==cv2.EVENT_RBUTTONUP: clickFlag = -1 # lock.acquire() # try: # cv2.imwrite('cap.png',capImg) # finally: # clickCnt = clickCnt+1 # lock.release() # detect the useful information from the selected image def
(logoAffinePos,img,idx): _, _, _, _, affinedCropedImg, rtnFlag = logoAffinePos.rcvAffinedAll(img) if (rtnFlag is False): return None,None,None,False filtedCroped = imgprep.imgFilter(affinedCropedImg) filtedCroped = cv2.cvtColor(filtedCroped,cv2.COLOR_GRAY2RGB) filtedCropedPIL = Image.fromarray(filtedCroped) numStr = tesserOcr(filtedCropedPIL) return affinedCropedImg,filtedCroped,numStr,True def analyseBoxInfo(bds,imgfolder): maxCnt = 0 tempCnt = 0 tempNumSet = set(bds.tempNumList) bds.setImgFolder(imgfolder) for item in tempNumSet: tempCnt = bds.tempNumList.count(item) if(tempCnt > maxCnt): maxCnt = tempCnt bds.number = item def exportLog(lf, expStr): print(expStr) expStr = expStr+'\n' lf.writelines(expStr) if __name__ == '__main__': bxnm = input('Input the box name: ') # time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) bx1 = dso.boxds(bxnm) settingInfo = open('../data/setting','r') settingInfo.readline() PATH = settingInfo.readline().strip().lstrip().rstrip(',') DATAPATH = settingInfo.readline().strip().lstrip().rstrip(',') FEATURE_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') MATERIAL_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') BOX_DATA_PATH = settingInfo.readline().strip().lstrip().rstrip(',') LOG_PATH = settingInfo.readline().strip().lstrip().rstrip(',') curTime = time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) LOG_PATH = LOG_PATH+curTime+bx1.boxname+'.log' logFile = open(LOG_PATH,'w+') boxData = open(BOX_DATA_PATH,'r') logoTp = cv2.imread(MATERIAL_IMG_FOLDER + 'purelogo256.png') logoAffinePos = imgprep.LogoAffinePos(logoTp) cv2.namedWindow('capFrame') cv2.setMouseCallback('capFrame',detect_circle) VWIDTH = 1280 VHIGH = 720 cap = cv2.VideoCapture(0) cap.set(3,VWIDTH) cap.set(4,VHIGH) cap.read();cap.read();cap.read() tCapFrame = threading.Thread(target=capFrame, args=(cap,)) tCapFrame.start() while(capImg is None): pass dtrtnFlag = False showFlag = 0 while(1): if ((cv2.waitKey(1) & 0xFF == 27) | (clickCnt>=6) ): stopFlat = 1 break resImg = capImg.copy() showImg = resImg.copy() logoContourPts,logoContour,rtnFlag = logoAffinePos.extLegoLogo(resImg, minArea=5000) if (rtnFlag is True): # draw contour we finding cv2.drawContours(showImg, [logoContourPts], -1, (0,255,0), 2) cPts,rtnFlag = logoAffinePos.extQuadrangleCpts(logoContourPts, logoContour) if (rtnFlag is True): # draw corner points we finding for idx, cPt in enumerate(cPts): cPt = cPt.flatten() ptsize = int(logoAffinePos.estLength/20) showImg[cPt[1]-ptsize:cPt[1]+ptsize,cPt[0]-ptsize:cPt[0]+ptsize,:] = [255,255,0] showImg = cv2.resize(showImg,(0,0),fx=0.4,fy=0.4) # right click, discard the data and re-capturing if(clickFlag < 0): clickFlag = 0 exportLog(logFile, 'Data was discarded') cv2.destroyWindow('filted') # capturing image if(clickFlag is 0): dtrtnFlag = False showFlag = 0 cv2.putText(showImg,'Capturing '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' picture',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) # fisrt time left click, detect the image and output the result elif(clickFlag is 1): if(dtrtnFlag is False): affinedCropedImg,filtedCroped,numStr,dtrtnFlag = detectImg(logoAffinePos,resImg,clickCnt) if(dtrtnFlag is False): # if detect result is False, set clickFlag 0, re-capturing clickFlag = 0 exportLog(logFile, 'Detecting fault, re-capturing') elif(dtrtnFlag is True): cv2.imshow('filted',filtedCroped) cv2.moveWindow('filted',50+int(0.4*VWIDTH),50) exportLog(logFile, bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' OCR: '+str(numStr)) dtrtnFlag = None else: cv2.putText(showImg,'Do you save this result? Lclick Save, Rclick Discard',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) elif(clickFlag is 2): exportLog(logFile, 'Saving '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' data') imgName = bx1.boxname+'_'+str(clickCnt)+'.tiff' savingPath = FEATURE_IMG_FOLDER + imgName savingPath2 = FEATURE_IMG_FOLDER + 'color/c' + imgName cv2.imwrite(savingPath, filtedCroped) cv2.imwrite(savingPath2, affinedCropedImg) bx1.setSingleFeatureImgsName(dso.SUF_DEF[clickCnt], imgName) exportLog(logFile, '--------Finish capturing--------\n') if(numStr is not None): bx1.appendTempNumList(numStr) clickCnt = clickCnt + 1 clickFlag = 0 cv2.destroyWindow('filted') else: clickFlag = 0 cv2.destroyWindow('filted') cv2.imshow('capFrame',showImg) analyseBoxInfo(bx1,FEATURE_IMG_FOLDER) dso.dsWrite(BOX_DATA_PATH,bx1) print('\n') logFile.close() boxData.close() cap.release() cv2.destroyAllWindows()
detectImg
identifier_name
boxCap.py
""" Capturing and analyzing the box information Author: Lyu Yaopengfei Date: 23-May-2016 """ import cv2 import threading import time from PIL import Image import Lego.dsOperation as dso import Lego.imgPreprocessing as imgprep from Lego.ocr import tesserOcr capImg = None resImg = None stopFlat = 0 lock = threading.Lock() def capFrame(cap): global capImg global stopFlat while(1): lock.acquire() try: _,capImg = cap.read() finally: lock.release() if (stopFlat > 0): break clickCnt = 0 clickFlag = 0 def detect_circle(event,x,y,flags,param): global clickFlag if event==cv2.EVENT_LBUTTONUP: clickFlag = clickFlag+1 elif event==cv2.EVENT_RBUTTONUP: clickFlag = -1 # lock.acquire() # try: # cv2.imwrite('cap.png',capImg) # finally: # clickCnt = clickCnt+1 # lock.release() # detect the useful information from the selected image def detectImg(logoAffinePos,img,idx): _, _, _, _, affinedCropedImg, rtnFlag = logoAffinePos.rcvAffinedAll(img) if (rtnFlag is False): return None,None,None,False filtedCroped = imgprep.imgFilter(affinedCropedImg) filtedCroped = cv2.cvtColor(filtedCroped,cv2.COLOR_GRAY2RGB) filtedCropedPIL = Image.fromarray(filtedCroped) numStr = tesserOcr(filtedCropedPIL) return affinedCropedImg,filtedCroped,numStr,True def analyseBoxInfo(bds,imgfolder): maxCnt = 0 tempCnt = 0 tempNumSet = set(bds.tempNumList) bds.setImgFolder(imgfolder) for item in tempNumSet: tempCnt = bds.tempNumList.count(item) if(tempCnt > maxCnt): maxCnt = tempCnt bds.number = item def exportLog(lf, expStr): print(expStr) expStr = expStr+'\n' lf.writelines(expStr) if __name__ == '__main__': bxnm = input('Input the box name: ') # time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) bx1 = dso.boxds(bxnm) settingInfo = open('../data/setting','r') settingInfo.readline() PATH = settingInfo.readline().strip().lstrip().rstrip(',') DATAPATH = settingInfo.readline().strip().lstrip().rstrip(',') FEATURE_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') MATERIAL_IMG_FOLDER = settingInfo.readline().strip().lstrip().rstrip(',') BOX_DATA_PATH = settingInfo.readline().strip().lstrip().rstrip(',') LOG_PATH = settingInfo.readline().strip().lstrip().rstrip(',') curTime = time.strftime('%Y-%m-%d-%H%M%S',time.localtime(time.time())) LOG_PATH = LOG_PATH+curTime+bx1.boxname+'.log' logFile = open(LOG_PATH,'w+') boxData = open(BOX_DATA_PATH,'r') logoTp = cv2.imread(MATERIAL_IMG_FOLDER + 'purelogo256.png') logoAffinePos = imgprep.LogoAffinePos(logoTp) cv2.namedWindow('capFrame') cv2.setMouseCallback('capFrame',detect_circle) VWIDTH = 1280 VHIGH = 720 cap = cv2.VideoCapture(0) cap.set(3,VWIDTH) cap.set(4,VHIGH) cap.read();cap.read();cap.read() tCapFrame = threading.Thread(target=capFrame, args=(cap,)) tCapFrame.start() while(capImg is None): pass dtrtnFlag = False showFlag = 0 while(1): if ((cv2.waitKey(1) & 0xFF == 27) | (clickCnt>=6) ): stopFlat = 1 break resImg = capImg.copy() showImg = resImg.copy() logoContourPts,logoContour,rtnFlag = logoAffinePos.extLegoLogo(resImg, minArea=5000) if (rtnFlag is True): # draw contour we finding cv2.drawContours(showImg, [logoContourPts], -1, (0,255,0), 2) cPts,rtnFlag = logoAffinePos.extQuadrangleCpts(logoContourPts, logoContour) if (rtnFlag is True): # draw corner points we finding for idx, cPt in enumerate(cPts): cPt = cPt.flatten() ptsize = int(logoAffinePos.estLength/20) showImg[cPt[1]-ptsize:cPt[1]+ptsize,cPt[0]-ptsize:cPt[0]+ptsize,:] = [255,255,0] showImg = cv2.resize(showImg,(0,0),fx=0.4,fy=0.4) # right click, discard the data and re-capturing if(clickFlag < 0): clickFlag = 0 exportLog(logFile, 'Data was discarded') cv2.destroyWindow('filted') # capturing image if(clickFlag is 0):
showFlag = 0 cv2.putText(showImg,'Capturing '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' picture',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) # fisrt time left click, detect the image and output the result elif(clickFlag is 1): if(dtrtnFlag is False): affinedCropedImg,filtedCroped,numStr,dtrtnFlag = detectImg(logoAffinePos,resImg,clickCnt) if(dtrtnFlag is False): # if detect result is False, set clickFlag 0, re-capturing clickFlag = 0 exportLog(logFile, 'Detecting fault, re-capturing') elif(dtrtnFlag is True): cv2.imshow('filted',filtedCroped) cv2.moveWindow('filted',50+int(0.4*VWIDTH),50) exportLog(logFile, bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' OCR: '+str(numStr)) dtrtnFlag = None else: cv2.putText(showImg,'Do you save this result? Lclick Save, Rclick Discard',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1) elif(clickFlag is 2): exportLog(logFile, 'Saving '+bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' data') imgName = bx1.boxname+'_'+str(clickCnt)+'.tiff' savingPath = FEATURE_IMG_FOLDER + imgName savingPath2 = FEATURE_IMG_FOLDER + 'color/c' + imgName cv2.imwrite(savingPath, filtedCroped) cv2.imwrite(savingPath2, affinedCropedImg) bx1.setSingleFeatureImgsName(dso.SUF_DEF[clickCnt], imgName) exportLog(logFile, '--------Finish capturing--------\n') if(numStr is not None): bx1.appendTempNumList(numStr) clickCnt = clickCnt + 1 clickFlag = 0 cv2.destroyWindow('filted') else: clickFlag = 0 cv2.destroyWindow('filted') cv2.imshow('capFrame',showImg) analyseBoxInfo(bx1,FEATURE_IMG_FOLDER) dso.dsWrite(BOX_DATA_PATH,bx1) print('\n') logFile.close() boxData.close() cap.release() cv2.destroyAllWindows()
dtrtnFlag = False
random_line_split
ddraw.rs
// 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. DEFINE_GUID!{CLSID_DirectDraw, 0xd7b70ee0, 0x4340, 0x11cf, 0xb0, 0x63, 0x00, 0x20, 0xaf, 0xc2, 0xcd, 0x35} DEFINE_GUID!{CLSID_DirectDraw7, 0x3c305196, 0x50db, 0x11d3, 0x9c, 0xfe, 0x00, 0xc0, 0x4f, 0xd9, 0x30, 0xc5} DEFINE_GUID!{CLSID_DirectDrawClipper, 0x593817a0, 0x7db3, 0x11cf, 0xa2, 0xde, 0x00, 0xaa, 0x00, 0xb9, 0x33, 0x56} DEFINE_GUID!{IID_IDirectDraw, 0x6c14db80, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60} DEFINE_GUID!{IID_IDirectDraw2, 0xb3a6f3e0, 0x2b43, 0x11cf, 0xa2, 0xde, 0x00, 0xaa, 0x00, 0xb9, 0x33, 0x56} DEFINE_GUID!{IID_IDirectDraw4, 0x9c59509a, 0x39bd, 0x11d1, 0x8c, 0x4a, 0x00, 0xc0, 0x4f, 0xd9, 0x30, 0xc5} DEFINE_GUID!{IID_IDirectDraw7, 0x15e65ec0, 0x3b9c, 0x11d2, 0xb9, 0x2f, 0x00, 0x60, 0x97, 0x97, 0xea, 0x5b} DEFINE_GUID!{IID_IDirectDrawSurface, 0x6c14db81, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60}
0xda044e00, 0x69b2, 0x11d0, 0xa1, 0xd5, 0x00, 0xaa, 0x00, 0xb8, 0xdf, 0xbb} DEFINE_GUID!{IID_IDirectDrawSurface4, 0x0b2b8630, 0xad35, 0x11d0, 0x8e, 0xa6, 0x00, 0x60, 0x97, 0x97, 0xea, 0x5b} DEFINE_GUID!{IID_IDirectDrawSurface7, 0x06675a80, 0x3b9b, 0x11d2, 0xb9, 0x2f, 0x00, 0x60, 0x97, 0x97, 0xea, 0x5b} DEFINE_GUID!{IID_IDirectDrawPalette, 0x6c14db84, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60} DEFINE_GUID!{IID_IDirectDrawClipper, 0x6c14db85, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60} DEFINE_GUID!{IID_IDirectDrawColorControl, 0x4b9f0ee0, 0x0d7e, 0x11d0, 0x9b, 0x06, 0x00, 0xa0, 0xc9, 0x03, 0xa3, 0xb8} DEFINE_GUID!{IID_IDirectDrawGammaControl, 0x69c11c3e, 0xb46b, 0x11d1, 0xad, 0x7a, 0x00, 0xc0, 0x4f, 0xc2, 0x9b, 0x4e}
DEFINE_GUID!{IID_IDirectDrawSurface2, 0x57805885, 0x6eec, 0x11cf, 0x94, 0x41, 0xa8, 0x23, 0x03, 0xc1, 0x0e, 0x27} DEFINE_GUID!{IID_IDirectDrawSurface3,
random_line_split
people.init.js
$(function(){ // set-up the favs_people table if it doesn't exist $(document).ready(function(){ db.transaction( function(transaction) { transaction.executeSql( 'CREATE TABLE IF NOT EXISTS favs_people '+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, givenname TEXT NOT NULL, surname TEXT NOT NULL);' ); } ); }); // after loading the main people view load the number of favs out of the local database $('#people').live('pageAnimationEnd', function(event, info){ if (info.direction == 'out') { $(this).removeClass('active'); } else { // get number of favorites db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { $(".pfavscount").html('<small id="pfavscount" class="counter">'+results.rows.length+'</small>'); }, sqlError ); } ); $('#people-favorites').remove(); } }); // when animating into the people detail see if this item is a favorite or not $('#people-detail').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { checkPeopleFav(); } }); // draw the list of people favorites, use a hidden li item w/ id of #fav-ppl-clone to clone items $('#people-favorites').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { var string_sep = 'A'; var string_sep_check = false; (results.rows.length > 0) ? $('#fav-ppl-info').hide() : $('#fav-ppl-info').show(); for (var i=0; i < results.rows.length; i++) { var row = results.rows.item(i); if ((string_sep_check == false) && (row.surname.substr(0,1) == 'A')) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep_check = true; } else if (string_sep != row.surname.substr(0,1)) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep = row.surname.substr(0,1); } // duplicate an entry for a person var newFavRow = $('#fav-ppl-clone').clone(); newFavRow.removeAttr('id'); newFavRow.removeAttr('style'); newFavRow.data('entryId',row.id); newFavRow.addClass('fav-ppl-entry'); newFavRow.appendTo('#fav-ppl-list'); newFavRow.html("<a href=\"/people/?username="+row.username+"\"><span class='thin'>"+row.givenname+"</span> "+row.surname+"</a>"); } }, sqlError ); } ); } }); // when unloading the people details delete the div holding the old detail so divs with that ID load properly in future // also delete the sessionStorage data so the options can be re-populated cleanly in the future $('.people-list').live('pageAnimationEnd', function(event, info){ if (info.direction == 'in') { $('#people-detail').remove(); peopleFavSelected = false; delete sessionStorage.givenName; delete sessionStorage.surname; delete sessionStorage.username; } else { $('.fav-ppl-entry').remove(); $('.fav-ppl-sep').remove(); } }); // toggle fav graphic on and off when tapped as well as add and remove data from db $('#people-favorite-detail').live('tap',function(){ peopleFav(); }); });
var peopleFavSelected = false; // mark or unmark the item as a favorite function peopleFav() { if (peopleFavSelected == true) { db.transaction( function(transaction) { transaction.executeSql( 'DELETE FROM favs_people WHERE username = ?;', [sessionStorage.username], function() { peopleFavSelected = false; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); }, sqlError ); } ); } else if (peopleFavSelected == false) { db.transaction( function(transaction) { transaction.executeSql( 'INSERT INTO favs_people (username, givenname, surname) VALUES (?,?,?);', [sessionStorage.username, sessionStorage.givenName, sessionStorage.surname], function() { peopleFavSelected = true; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); }, sqlError ); } ); } } // the actual function that checks if there is a favorite for the directory entry function checkPeopleFav() { db.transaction( function(transaction) { transaction.executeSql( 'SELECT id FROM favs_people WHERE username = ?;', [sessionStorage.username], function(transaction,results) { if (results.rows.length > 0) { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); peopleFavSelected = true; } else { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); peopleFavSelected = false; } }, sqlError ); } ); }
random_line_split
people.init.js
$(function(){ // set-up the favs_people table if it doesn't exist $(document).ready(function(){ db.transaction( function(transaction) { transaction.executeSql( 'CREATE TABLE IF NOT EXISTS favs_people '+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, givenname TEXT NOT NULL, surname TEXT NOT NULL);' ); } ); }); // after loading the main people view load the number of favs out of the local database $('#people').live('pageAnimationEnd', function(event, info){ if (info.direction == 'out')
else { // get number of favorites db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { $(".pfavscount").html('<small id="pfavscount" class="counter">'+results.rows.length+'</small>'); }, sqlError ); } ); $('#people-favorites').remove(); } }); // when animating into the people detail see if this item is a favorite or not $('#people-detail').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { checkPeopleFav(); } }); // draw the list of people favorites, use a hidden li item w/ id of #fav-ppl-clone to clone items $('#people-favorites').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { var string_sep = 'A'; var string_sep_check = false; (results.rows.length > 0) ? $('#fav-ppl-info').hide() : $('#fav-ppl-info').show(); for (var i=0; i < results.rows.length; i++) { var row = results.rows.item(i); if ((string_sep_check == false) && (row.surname.substr(0,1) == 'A')) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep_check = true; } else if (string_sep != row.surname.substr(0,1)) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep = row.surname.substr(0,1); } // duplicate an entry for a person var newFavRow = $('#fav-ppl-clone').clone(); newFavRow.removeAttr('id'); newFavRow.removeAttr('style'); newFavRow.data('entryId',row.id); newFavRow.addClass('fav-ppl-entry'); newFavRow.appendTo('#fav-ppl-list'); newFavRow.html("<a href=\"/people/?username="+row.username+"\"><span class='thin'>"+row.givenname+"</span> "+row.surname+"</a>"); } }, sqlError ); } ); } }); // when unloading the people details delete the div holding the old detail so divs with that ID load properly in future // also delete the sessionStorage data so the options can be re-populated cleanly in the future $('.people-list').live('pageAnimationEnd', function(event, info){ if (info.direction == 'in') { $('#people-detail').remove(); peopleFavSelected = false; delete sessionStorage.givenName; delete sessionStorage.surname; delete sessionStorage.username; } else { $('.fav-ppl-entry').remove(); $('.fav-ppl-sep').remove(); } }); // toggle fav graphic on and off when tapped as well as add and remove data from db $('#people-favorite-detail').live('tap',function(){ peopleFav(); }); }); var peopleFavSelected = false; // mark or unmark the item as a favorite function peopleFav() { if (peopleFavSelected == true) { db.transaction( function(transaction) { transaction.executeSql( 'DELETE FROM favs_people WHERE username = ?;', [sessionStorage.username], function() { peopleFavSelected = false; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); }, sqlError ); } ); } else if (peopleFavSelected == false) { db.transaction( function(transaction) { transaction.executeSql( 'INSERT INTO favs_people (username, givenname, surname) VALUES (?,?,?);', [sessionStorage.username, sessionStorage.givenName, sessionStorage.surname], function() { peopleFavSelected = true; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); }, sqlError ); } ); } } // the actual function that checks if there is a favorite for the directory entry function checkPeopleFav() { db.transaction( function(transaction) { transaction.executeSql( 'SELECT id FROM favs_people WHERE username = ?;', [sessionStorage.username], function(transaction,results) { if (results.rows.length > 0) { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); peopleFavSelected = true; } else { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); peopleFavSelected = false; } }, sqlError ); } ); }
{ $(this).removeClass('active'); }
conditional_block
people.init.js
$(function(){ // set-up the favs_people table if it doesn't exist $(document).ready(function(){ db.transaction( function(transaction) { transaction.executeSql( 'CREATE TABLE IF NOT EXISTS favs_people '+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, givenname TEXT NOT NULL, surname TEXT NOT NULL);' ); } ); }); // after loading the main people view load the number of favs out of the local database $('#people').live('pageAnimationEnd', function(event, info){ if (info.direction == 'out') { $(this).removeClass('active'); } else { // get number of favorites db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { $(".pfavscount").html('<small id="pfavscount" class="counter">'+results.rows.length+'</small>'); }, sqlError ); } ); $('#people-favorites').remove(); } }); // when animating into the people detail see if this item is a favorite or not $('#people-detail').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { checkPeopleFav(); } }); // draw the list of people favorites, use a hidden li item w/ id of #fav-ppl-clone to clone items $('#people-favorites').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { var string_sep = 'A'; var string_sep_check = false; (results.rows.length > 0) ? $('#fav-ppl-info').hide() : $('#fav-ppl-info').show(); for (var i=0; i < results.rows.length; i++) { var row = results.rows.item(i); if ((string_sep_check == false) && (row.surname.substr(0,1) == 'A')) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep_check = true; } else if (string_sep != row.surname.substr(0,1)) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep = row.surname.substr(0,1); } // duplicate an entry for a person var newFavRow = $('#fav-ppl-clone').clone(); newFavRow.removeAttr('id'); newFavRow.removeAttr('style'); newFavRow.data('entryId',row.id); newFavRow.addClass('fav-ppl-entry'); newFavRow.appendTo('#fav-ppl-list'); newFavRow.html("<a href=\"/people/?username="+row.username+"\"><span class='thin'>"+row.givenname+"</span> "+row.surname+"</a>"); } }, sqlError ); } ); } }); // when unloading the people details delete the div holding the old detail so divs with that ID load properly in future // also delete the sessionStorage data so the options can be re-populated cleanly in the future $('.people-list').live('pageAnimationEnd', function(event, info){ if (info.direction == 'in') { $('#people-detail').remove(); peopleFavSelected = false; delete sessionStorage.givenName; delete sessionStorage.surname; delete sessionStorage.username; } else { $('.fav-ppl-entry').remove(); $('.fav-ppl-sep').remove(); } }); // toggle fav graphic on and off when tapped as well as add and remove data from db $('#people-favorite-detail').live('tap',function(){ peopleFav(); }); }); var peopleFavSelected = false; // mark or unmark the item as a favorite function peopleFav() { if (peopleFavSelected == true) { db.transaction( function(transaction) { transaction.executeSql( 'DELETE FROM favs_people WHERE username = ?;', [sessionStorage.username], function() { peopleFavSelected = false; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); }, sqlError ); } ); } else if (peopleFavSelected == false) { db.transaction( function(transaction) { transaction.executeSql( 'INSERT INTO favs_people (username, givenname, surname) VALUES (?,?,?);', [sessionStorage.username, sessionStorage.givenName, sessionStorage.surname], function() { peopleFavSelected = true; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); }, sqlError ); } ); } } // the actual function that checks if there is a favorite for the directory entry function
() { db.transaction( function(transaction) { transaction.executeSql( 'SELECT id FROM favs_people WHERE username = ?;', [sessionStorage.username], function(transaction,results) { if (results.rows.length > 0) { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); peopleFavSelected = true; } else { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); peopleFavSelected = false; } }, sqlError ); } ); }
checkPeopleFav
identifier_name
people.init.js
$(function(){ // set-up the favs_people table if it doesn't exist $(document).ready(function(){ db.transaction( function(transaction) { transaction.executeSql( 'CREATE TABLE IF NOT EXISTS favs_people '+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, givenname TEXT NOT NULL, surname TEXT NOT NULL);' ); } ); }); // after loading the main people view load the number of favs out of the local database $('#people').live('pageAnimationEnd', function(event, info){ if (info.direction == 'out') { $(this).removeClass('active'); } else { // get number of favorites db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { $(".pfavscount").html('<small id="pfavscount" class="counter">'+results.rows.length+'</small>'); }, sqlError ); } ); $('#people-favorites').remove(); } }); // when animating into the people detail see if this item is a favorite or not $('#people-detail').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { checkPeopleFav(); } }); // draw the list of people favorites, use a hidden li item w/ id of #fav-ppl-clone to clone items $('#people-favorites').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { var string_sep = 'A'; var string_sep_check = false; (results.rows.length > 0) ? $('#fav-ppl-info').hide() : $('#fav-ppl-info').show(); for (var i=0; i < results.rows.length; i++) { var row = results.rows.item(i); if ((string_sep_check == false) && (row.surname.substr(0,1) == 'A')) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep_check = true; } else if (string_sep != row.surname.substr(0,1)) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep = row.surname.substr(0,1); } // duplicate an entry for a person var newFavRow = $('#fav-ppl-clone').clone(); newFavRow.removeAttr('id'); newFavRow.removeAttr('style'); newFavRow.data('entryId',row.id); newFavRow.addClass('fav-ppl-entry'); newFavRow.appendTo('#fav-ppl-list'); newFavRow.html("<a href=\"/people/?username="+row.username+"\"><span class='thin'>"+row.givenname+"</span> "+row.surname+"</a>"); } }, sqlError ); } ); } }); // when unloading the people details delete the div holding the old detail so divs with that ID load properly in future // also delete the sessionStorage data so the options can be re-populated cleanly in the future $('.people-list').live('pageAnimationEnd', function(event, info){ if (info.direction == 'in') { $('#people-detail').remove(); peopleFavSelected = false; delete sessionStorage.givenName; delete sessionStorage.surname; delete sessionStorage.username; } else { $('.fav-ppl-entry').remove(); $('.fav-ppl-sep').remove(); } }); // toggle fav graphic on and off when tapped as well as add and remove data from db $('#people-favorite-detail').live('tap',function(){ peopleFav(); }); }); var peopleFavSelected = false; // mark or unmark the item as a favorite function peopleFav() { if (peopleFavSelected == true) { db.transaction( function(transaction) { transaction.executeSql( 'DELETE FROM favs_people WHERE username = ?;', [sessionStorage.username], function() { peopleFavSelected = false; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); }, sqlError ); } ); } else if (peopleFavSelected == false) { db.transaction( function(transaction) { transaction.executeSql( 'INSERT INTO favs_people (username, givenname, surname) VALUES (?,?,?);', [sessionStorage.username, sessionStorage.givenName, sessionStorage.surname], function() { peopleFavSelected = true; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); }, sqlError ); } ); } } // the actual function that checks if there is a favorite for the directory entry function checkPeopleFav()
{ db.transaction( function(transaction) { transaction.executeSql( 'SELECT id FROM favs_people WHERE username = ?;', [sessionStorage.username], function(transaction,results) { if (results.rows.length > 0) { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); peopleFavSelected = true; } else { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); peopleFavSelected = false; } }, sqlError ); } ); }
identifier_body
FunctionEntityDetails.tsx
import React, { useContext } from 'react'; import { DetailsListLayoutMode, SelectionMode, ICommandBarItemProps, IColumn } from 'office-ui-fabric-react'; import { useTranslation } from 'react-i18next'; import { AppInsightsOrchestrationTrace, AppInsightsEntityTraceDetail } from '../../../../../../../models/app-insights'; import { PortalContext } from '../../../../../../../PortalContext'; import { openAppInsightsQueryEditor } from '../FunctionMonitorTab.data'; import DisplayTableWithCommandBar from '../../../../../../../components/DisplayTableWithCommandBar/DisplayTableWithCommandBar'; import { tabStyle } from '../FunctionMonitorTab.styles'; import { FunctionEntitiesContext } from './FunctionEntitiesDataLoader'; export interface FunctionEntityDetailsProps { appInsightsResourceId: string;
const { entityDetails, appInsightsResourceId, currentTrace } = props; const portalContext = useContext(PortalContext); const entityContext = useContext(FunctionEntitiesContext); const instanceId = currentTrace ? currentTrace.DurableFunctionsInstanceId : ''; const { t } = useTranslation(); const getCommandBarItems = (): ICommandBarItemProps[] => { return [ { key: 'entity-run-query', onClick: () => openAppInsightsQueryEditor(portalContext, appInsightsResourceId, entityContext.formEntityTraceDetailsQuery(instanceId)), iconProps: { iconName: 'LineChart' }, name: t('runQueryInApplicationInsights'), }, ]; }; const getColumns = (): IColumn[] => { return [ { key: 'timestamp', name: t('timestamp'), fieldName: 'timestampFriendly', minWidth: 100, maxWidth: 170, isResizable: true, }, { key: 'message', name: t('message'), fieldName: 'message', minWidth: 100, maxWidth: 260, isResizable: true, isMultiline: true, }, { key: 'state', name: t('state'), fieldName: 'state', minWidth: 100, maxWidth: 100, isResizable: true, }, ]; }; const getItems = (): AppInsightsEntityTraceDetail[] => { return entityDetails || []; }; return ( <div id="entity-details" className={tabStyle}> <DisplayTableWithCommandBar commandBarItems={getCommandBarItems()} columns={getColumns()} items={getItems()} isHeaderVisible={true} layoutMode={DetailsListLayoutMode.justified} selectionMode={SelectionMode.none} selectionPreservedOnEmptyClick={true} emptyMessage={t('noResults')} shimmer={{ lines: 2, show: !entityDetails }} /> </div> ); }; export default FunctionEntityDetails;
currentTrace?: AppInsightsOrchestrationTrace; entityDetails?: AppInsightsEntityTraceDetail[]; } const FunctionEntityDetails: React.FC<FunctionEntityDetailsProps> = props => {
random_line_split
Menu.js
import React from 'react'; import { StyleSheet, Text, View, Button, Image, Dimensions, } from 'react-native'; import { StackNavigator, } from 'react-navigation'; class
extends React.Component { static navigationOptions = { title: 'Menu' } render() { const imageURI = Expo.Asset.fromModule(require('../assets/screens/menu.png')).uri; return ( <View style={{position: 'relative', alignItems: 'flex-end', justifyContent: 'center', flex: 1}}> <Text onPress={this._handlePress}>Go to Settings</Text> <Image source={{ uri: imageURI }} style={{ height: '100%', width: '100%', opacity: 0.1, position: 'absolute'}} /> <Button title="aaaaaaaaaaaa" style={{ height: 100, width: '100%', position: 'absolute', float: 'down', bottom: 0 }} onPress={this._handleButtonPress} /> </View> ) } _handlePress = () => { this.props.navigation.navigate('Menu'); } _handleButtonPress = () => { this.props.navigation.navigate('Menu'); } }
MenuScreen
identifier_name
Menu.js
import React from 'react'; import { StyleSheet, Text, View, Button, Image, Dimensions, } from 'react-native'; import { StackNavigator, } from 'react-navigation'; class MenuScreen extends React.Component { static navigationOptions = { title: 'Menu' } render() { const imageURI = Expo.Asset.fromModule(require('../assets/screens/menu.png')).uri;
<Image source={{ uri: imageURI }} style={{ height: '100%', width: '100%', opacity: 0.1, position: 'absolute'}} /> <Button title="aaaaaaaaaaaa" style={{ height: 100, width: '100%', position: 'absolute', float: 'down', bottom: 0 }} onPress={this._handleButtonPress} /> </View> ) } _handlePress = () => { this.props.navigation.navigate('Menu'); } _handleButtonPress = () => { this.props.navigation.navigate('Menu'); } }
return ( <View style={{position: 'relative', alignItems: 'flex-end', justifyContent: 'center', flex: 1}}> <Text onPress={this._handlePress}>Go to Settings</Text>
random_line_split
mod.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Collection types. //! //! Rust's standard collection library provides efficient implementations of the most common //! general purpose programming data structures. By using the standard implementations, //! it should be possible for two libraries to communicate without significant data conversion. //! //! To get this out of the way: you should probably just use `Vec` or `HashMap`. These two //! collections cover most use cases for generic data storage and processing. They are //! exceptionally good at doing what they do. All the other collections in the standard //! library have specific use cases where they are the optimal choice, but these cases are //! borderline *niche* in comparison. Even when `Vec` and `HashMap` are technically suboptimal, //! they're probably a good enough choice to get started. //! //! Rust's collections can be grouped into four major categories: //! //! * Sequences: `Vec`, `VecDeque`, `LinkedList`, `BitVec` //! * Maps: `HashMap`, `BTreeMap`, `VecMap` //! * Sets: `HashSet`, `BTreeSet`, `BitSet` //! * Misc: `BinaryHeap` //! //! # When Should You Use Which Collection? //! //! These are fairly high-level and quick break-downs of when each collection should be //! considered. Detailed discussions of strengths and weaknesses of individual collections //! can be found on their own documentation pages. //! //! ### Use a `Vec` when: //! * You want to collect items up to be processed or sent elsewhere later, and don't care about //! any properties of the actual values being stored. //! * You want a sequence of elements in a particular order, and will only be appending to //! (or near) the end. //! * You want a stack. //! * You want a resizable array. //! * You want a heap-allocated array. //! //! ### Use a `VecDeque` when: //! * You want a `Vec` that supports efficient insertion at both ends of the sequence. //! * You want a queue. //! * You want a double-ended queue (deque). //! //! ### Use a `LinkedList` when: //! * You want a `Vec` or `VecDeque` of unknown size, and can't tolerate amortization. //! * You want to efficiently split and append lists. //! * You are *absolutely* certain you *really*, *truly*, want a doubly linked list. //! //! ### Use a `HashMap` when: //! * You want to associate arbitrary keys with an arbitrary value. //! * You want a cache. //! * You want a map, with no extra functionality. //! //! ### Use a `BTreeMap` when: //! * You're interested in what the smallest or largest key-value pair is. //! * You want to find the largest or smallest key that is smaller or larger than something //! * You want to be able to get all of the entries in order on-demand. //! * You want a sorted map. //! //! ### Use a `VecMap` when: //! * You want a `HashMap` but with known to be small `usize` keys. //! * You want a `BTreeMap`, but with known to be small `usize` keys. //! //! ### Use the `Set` variant of any of these `Map`s when: //! * You just want to remember which keys you've seen. //! * There is no meaningful value to associate with your keys. //! * You just want a set. //! //! ### Use a `BitVec` when: //! * You want to store an unbounded number of booleans in a small space. //! * You want a bit vector. //! //! ### Use a `BitSet` when: //! * You want a `BitVec`, but want `Set` properties //! //! ### Use a `BinaryHeap` when: //! * You want to store a bunch of elements, but only ever want to process the "biggest" //! or "most important" one at any given time. //! * You want a priority queue. //! //! # Performance //! //! Choosing the right collection for the job requires an understanding of what each collection //! is good at. Here we briefly summarize the performance of different collections for certain //! important operations. For further details, see each type's documentation, and note that the //! names of actual methods may differ from the tables below on certain collections. //! //! Throughout the documentation, we will follow a few conventions. For all operations, //! the collection's size is denoted by n. If another collection is involved in the operation, it //! contains m elements. Operations which have an *amortized* cost are suffixed with a `*`. //! Operations with an *expected* cost are suffixed with a `~`. //! //! All amortized costs are for the potential need to resize when capacity is exhausted. //! If a resize occurs it will take O(n) time. Our collections never automatically shrink, //! so removal operations aren't amortized. Over a sufficiently large series of //! operations, the average cost per operation will deterministically equal the given cost. //! //! Only HashMap has expected costs, due to the probabilistic nature of hashing. It is //! theoretically possible, though very unlikely, for HashMap to experience worse performance. //! //! ## Sequences //! //! | | get(i) | insert(i) | remove(i) | append | split_off(i) | //! |--------------|----------------|-----------------|----------------|--------|----------------| //! | Vec | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) | //! | VecDeque | O(1) | O(min(i, n-i))* | O(min(i, n-i)) | O(m)* | O(min(i, n-i)) | //! | LinkedList | O(min(i, n-i)) | O(min(i, n-i)) | O(min(i, n-i)) | O(1) | O(min(i, n-i)) | //! | BitVec | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) | //! //! Note that where ties occur, Vec is generally going to be faster than VecDeque, and VecDeque //! is generally going to be faster than LinkedList. BitVec is not a general purpose collection, and //! therefore cannot reasonably be compared. //! //! ## Maps //! //! For Sets, all operations have the cost of the equivalent Map operation. For BitSet, //! refer to VecMap. //! //! | | get | insert | remove | predecessor | //! |----------|-----------|----------|----------|-------------| //! | HashMap | O(1)~ | O(1)~* | O(1)~ | N/A | //! | BTreeMap | O(log n) | O(log n) | O(log n) | O(log n) | //! | VecMap | O(1) | O(1)? | O(1) | O(n) | //! //! Note that VecMap is *incredibly* inefficient in terms of space. The O(1) insertion time //! assumes space for the element is already allocated. Otherwise, a large key may require a //! massive reallocation, with no direct relation to the number of elements in the collection. //! VecMap should only be seriously considered for small keys. //! //! Note also that BTreeMap's precise preformance depends on the value of B. //! //! # Correct and Efficient Usage of Collections //! //! Of course, knowing which collection is the right one for the job doesn't instantly //! permit you to use it correctly. Here are some quick tips for efficient and correct //! usage of the standard collections in general. If you're interested in how to use a
//! Many collections provide several constructors and methods that refer to "capacity". //! These collections are generally built on top of an array. Optimally, this array would be //! exactly the right size to fit only the elements stored in the collection, but for the //! collection to do this would be very inefficient. If the backing array was exactly the //! right size at all times, then every time an element is inserted, the collection would //! have to grow the array to fit it. Due to the way memory is allocated and managed on most //! computers, this would almost surely require allocating an entirely new array and //! copying every single element from the old one into the new one. Hopefully you can //! see that this wouldn't be very efficient to do on every operation. //! //! Most collections therefore use an *amortized* allocation strategy. They generally let //! themselves have a fair amount of unoccupied space so that they only have to grow //! on occasion. When they do grow, they allocate a substantially larger array to move //! the elements into so that it will take a while for another grow to be required. While //! this strategy is great in general, it would be even better if the collection *never* //! had to resize its backing array. Unfortunately, the collection itself doesn't have //! enough information to do this itself. Therefore, it is up to us programmers to give it //! hints. //! //! Any `with_capacity` constructor will instruct the collection to allocate enough space //! for the specified number of elements. Ideally this will be for exactly that many //! elements, but some implementation details may prevent this. `Vec` and `VecDeque` can //! be relied on to allocate exactly the requested amount, though. Use `with_capacity` //! when you know exactly how many elements will be inserted, or at least have a //! reasonable upper-bound on that number. //! //! When anticipating a large influx of elements, the `reserve` family of methods can //! be used to hint to the collection how much room it should make for the coming items. //! As with `with_capacity`, the precise behavior of these methods will be specific to //! the collection of interest. //! //! For optimal performance, collections will generally avoid shrinking themselves. //! If you believe that a collection will not soon contain any more elements, or //! just really need the memory, the `shrink_to_fit` method prompts the collection //! to shrink the backing array to the minimum size capable of holding its elements. //! //! Finally, if ever you're interested in what the actual capacity of the collection is, //! most collections provide a `capacity` method to query this information on demand. //! This can be useful for debugging purposes, or for use with the `reserve` methods. //! //! ## Iterators //! //! Iterators are a powerful and robust mechanism used throughout Rust's standard //! libraries. Iterators provide a sequence of values in a generic, safe, efficient //! and convenient way. The contents of an iterator are usually *lazily* evaluated, //! so that only the values that are actually needed are ever actually produced, and //! no allocation need be done to temporarily store them. Iterators are primarily //! consumed using a `for` loop, although many functions also take iterators where //! a collection or sequence of values is desired. //! //! All of the standard collections provide several iterators for performing bulk //! manipulation of their contents. The three primary iterators almost every collection //! should provide are `iter`, `iter_mut`, and `into_iter`. Some of these are not //! provided on collections where it would be unsound or unreasonable to provide them. //! //! `iter` provides an iterator of immutable references to all the contents of a //! collection in the most "natural" order. For sequence collections like `Vec`, this //! means the items will be yielded in increasing order of index starting at 0. For ordered //! collections like `BTreeMap`, this means that the items will be yielded in sorted order. //! For unordered collections like `HashMap`, the items will be yielded in whatever order //! the internal representation made most convenient. This is great for reading through //! all the contents of the collection. //! //! ``` //! let vec = vec![1, 2, 3, 4]; //! for x in vec.iter() { //! println!("vec contained {}", x); //! } //! ``` //! //! `iter_mut` provides an iterator of *mutable* references in the same order as `iter`. //! This is great for mutating all the contents of the collection. //! //! ``` //! let mut vec = vec![1, 2, 3, 4]; //! for x in vec.iter_mut() { //! *x += 1; //! } //! ``` //! //! `into_iter` transforms the actual collection into an iterator over its contents //! by-value. This is great when the collection itself is no longer needed, and the //! values are needed elsewhere. Using `extend` with `into_iter` is the main way that //! contents of one collection are moved into another. Calling `collect` on an iterator //! itself is also a great way to convert one collection into another. Both of these //! methods should internally use the capacity management tools discussed in the //! previous section to do this as efficiently as possible. //! //! ``` //! let mut vec1 = vec![1, 2, 3, 4]; //! let vec2 = vec![10, 20, 30, 40]; //! vec1.extend(vec2.into_iter()); //! ``` //! //! ``` //! use std::collections::VecDeque; //! //! let vec = vec![1, 2, 3, 4]; //! let buf: VecDeque<_> = vec.into_iter().collect(); //! ``` //! //! Iterators also provide a series of *adapter* methods for performing common tasks to //! sequences. Among the adapters are functional favorites like `map`, `fold`, `skip`, //! and `take`. Of particular interest to collections is the `rev` adapter, that //! reverses any iterator that supports this operation. Most collections provide reversible //! iterators as the way to iterate over them in reverse order. //! //! ``` //! let vec = vec![1, 2, 3, 4]; //! for x in vec.iter().rev() { //! println!("vec contained {}", x); //! } //! ``` //! //! Several other collection methods also return iterators to yield a sequence of results //! but avoid allocating an entire collection to store the result in. This provides maximum //! flexibility as `collect` or `extend` can be called to "pipe" the sequence into any //! collection if desired. Otherwise, the sequence can be looped over with a `for` loop. The //! iterator can also be discarded after partial use, preventing the computation of the unused //! items. //! //! ## Entries //! //! The `entry` API is intended to provide an efficient mechanism for manipulating //! the contents of a map conditionally on the presence of a key or not. The primary //! motivating use case for this is to provide efficient accumulator maps. For instance, //! if one wishes to maintain a count of the number of times each key has been seen, //! they will have to perform some conditional logic on whether this is the first time //! the key has been seen or not. Normally, this would require a `find` followed by an //! `insert`, effectively duplicating the search effort on each insertion. //! //! When a user calls `map.entry(&key)`, the map will search for the key and then yield //! a variant of the `Entry` enum. //! //! If a `Vacant(entry)` is yielded, then the key *was not* found. In this case the //! only valid operation is to `insert` a value into the entry. When this is done, //! the vacant entry is consumed and converted into a mutable reference to the //! the value that was inserted. This allows for further manipulation of the value //! beyond the lifetime of the search itself. This is useful if complex logic needs to //! be performed on the value regardless of whether the value was just inserted. //! //! If an `Occupied(entry)` is yielded, then the key *was* found. In this case, the user //! has several options: they can `get`, `insert`, or `remove` the value of the occupied //! entry. Additionally, they can convert the occupied entry into a mutable reference //! to its value, providing symmetry to the vacant `insert` case. //! //! ### Examples //! //! Here are the two primary ways in which `entry` is used. First, a simple example //! where the logic performed on the values is trivial. //! //! #### Counting the number of times each character in a string occurs //! //! ``` //! use std::collections::btree_map::{BTreeMap, Entry}; //! //! let mut count = BTreeMap::new(); //! let message = "she sells sea shells by the sea shore"; //! //! for c in message.chars() { //! match count.entry(c) { //! Entry::Vacant(entry) => { entry.insert(1); }, //! Entry::Occupied(mut entry) => *entry.get_mut() += 1, //! } //! } //! //! assert_eq!(count.get(&'s'), Some(&8)); //! //! println!("Number of occurrences of each character"); //! for (char, count) in count.iter() { //! println!("{}: {}", char, count); //! } //! ``` //! //! When the logic to be performed on the value is more complex, we may simply use //! the `entry` API to ensure that the value is initialized, and perform the logic //! afterwards. //! //! #### Tracking the inebriation of customers at a bar //! //! ``` //! use std::collections::btree_map::{BTreeMap, Entry}; //! //! // A client of the bar. They have an id and a blood alcohol level. //! struct Person { id: u32, blood_alcohol: f32 } //! //! // All the orders made to the bar, by client id. //! let orders = vec![1,2,1,2,3,4,1,2,2,3,4,1,1,1]; //! //! // Our clients. //! let mut blood_alcohol = BTreeMap::new(); //! //! for id in orders.into_iter() { //! // If this is the first time we've seen this customer, initialize them //! // with no blood alcohol. Otherwise, just retrieve them. //! let person = match blood_alcohol.entry(id) { //! Entry::Vacant(entry) => entry.insert(Person{id: id, blood_alcohol: 0.0}), //! Entry::Occupied(entry) => entry.into_mut(), //! }; //! //! // Reduce their blood alcohol level. It takes time to order and drink a beer! //! person.blood_alcohol *= 0.9; //! //! // Check if they're sober enough to have another beer. //! if person.blood_alcohol > 0.3 { //! // Too drunk... for now. //! println!("Sorry {}, I have to cut you off", person.id); //! } else { //! // Have another! //! person.blood_alcohol += 0.1; //! } //! } //! ``` #![stable(feature = "rust1", since = "1.0.0")] pub use core_collections::Bound; pub use core_collections::{BinaryHeap, BitVec, BitSet, BTreeMap, BTreeSet}; pub use core_collections::{LinkedList, VecDeque, VecMap}; pub use core_collections::{binary_heap, bit_vec, bit_set, btree_map, btree_set}; pub use core_collections::{linked_list, vec_deque, vec_map}; pub use self::hash_map::HashMap; pub use self::hash_set::HashSet; mod hash; #[stable(feature = "rust1", since = "1.0.0")] pub mod hash_map { //! A hashmap pub use super::hash::map::*; } #[stable(feature = "rust1", since = "1.0.0")] pub mod hash_set { //! A hashset pub use super::hash::set::*; } /// Experimental support for providing custom hash algorithms to a HashMap and /// HashSet. #[unstable(feature = "std_misc", reason = "module was recently added")] pub mod hash_state { pub use super::hash::state::*; }
//! specific collection in particular, consult its documentation for detailed discussion //! and code examples. //! //! ## Capacity Management //!
random_line_split
scheme.rs
use alloc::boxed::Box; use collections::vec::Vec; use collections::vec_deque::VecDeque; use core::ops::DerefMut; use fs::Resource; use system::error::Result; use sync::{Intex, WaitQueue}; pub trait NetworkScheme { fn add(&mut self, resource: *mut NetworkResource); fn remove(&mut self, resource: *mut NetworkResource); fn sync(&mut self); } pub struct NetworkResource { pub nic: *mut NetworkScheme, pub ptr: *mut NetworkResource, pub inbound: WaitQueue<Vec<u8>>, pub outbound: Intex<VecDeque<Vec<u8>>>, } impl NetworkResource { pub fn new(nic: *mut NetworkScheme) -> Box<Self> { let mut ret = box NetworkResource { nic: nic, ptr: 0 as *mut NetworkResource, inbound: WaitQueue::new(), outbound: Intex::new(VecDeque::new()), }; unsafe { ret.ptr = ret.deref_mut(); (*ret.nic).add(ret.ptr); } ret } } impl Resource for NetworkResource { fn dup(&self) -> Result<Box<Resource>> { let mut ret = box NetworkResource { nic: self.nic, ptr: 0 as *mut NetworkResource, inbound: self.inbound.clone(), outbound: Intex::new(self.outbound.lock().clone()), }; unsafe { ret.ptr = ret.deref_mut(); (*ret.nic).add(ret.ptr); } Ok(ret) } fn path(&self, buf: &mut [u8]) -> Result<usize> { let path = b"network:"; let mut i = 0; while i < buf.len() && i < path.len() { buf[i] = path[i]; i += 1; } Ok(i) } fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize> { unsafe { (*self.ptr).outbound.lock().push_back(Vec::from(buf)); (*self.nic).sync(); } Ok(buf.len()) } fn sync(&mut self) -> Result<()> { unsafe { (*self.nic).sync(); } Ok(()) } } impl Drop for NetworkResource { fn drop(&mut self) { unsafe { (*self.nic).remove(self.ptr); } } }
{ let bytes = unsafe { (*self.nic).sync(); (*self.ptr).inbound.receive() }; let mut i = 0; while i < bytes.len() && i < buf.len() { buf[i] = bytes[i]; i += 1; } return Ok(bytes.len()); }
identifier_body
scheme.rs
use alloc::boxed::Box; use collections::vec::Vec; use collections::vec_deque::VecDeque; use core::ops::DerefMut; use fs::Resource; use system::error::Result; use sync::{Intex, WaitQueue}; pub trait NetworkScheme { fn add(&mut self, resource: *mut NetworkResource); fn remove(&mut self, resource: *mut NetworkResource); fn sync(&mut self); } pub struct NetworkResource { pub nic: *mut NetworkScheme, pub ptr: *mut NetworkResource, pub inbound: WaitQueue<Vec<u8>>, pub outbound: Intex<VecDeque<Vec<u8>>>, } impl NetworkResource { pub fn new(nic: *mut NetworkScheme) -> Box<Self> { let mut ret = box NetworkResource { nic: nic, ptr: 0 as *mut NetworkResource, inbound: WaitQueue::new(), outbound: Intex::new(VecDeque::new()), }; unsafe { ret.ptr = ret.deref_mut(); (*ret.nic).add(ret.ptr); } ret } } impl Resource for NetworkResource { fn dup(&self) -> Result<Box<Resource>> { let mut ret = box NetworkResource { nic: self.nic, ptr: 0 as *mut NetworkResource, inbound: self.inbound.clone(), outbound: Intex::new(self.outbound.lock().clone()), }; unsafe { ret.ptr = ret.deref_mut(); (*ret.nic).add(ret.ptr); } Ok(ret) } fn path(&self, buf: &mut [u8]) -> Result<usize> { let path = b"network:"; let mut i = 0; while i < buf.len() && i < path.len() { buf[i] = path[i]; i += 1; } Ok(i) } fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let bytes = unsafe { (*self.nic).sync(); (*self.ptr).inbound.receive() }; let mut i = 0; while i < bytes.len() && i < buf.len() { buf[i] = bytes[i]; i += 1; } return Ok(bytes.len()); } fn
(&mut self, buf: &[u8]) -> Result<usize> { unsafe { (*self.ptr).outbound.lock().push_back(Vec::from(buf)); (*self.nic).sync(); } Ok(buf.len()) } fn sync(&mut self) -> Result<()> { unsafe { (*self.nic).sync(); } Ok(()) } } impl Drop for NetworkResource { fn drop(&mut self) { unsafe { (*self.nic).remove(self.ptr); } } }
write
identifier_name
scheme.rs
use alloc::boxed::Box; use collections::vec::Vec; use collections::vec_deque::VecDeque; use core::ops::DerefMut; use fs::Resource; use system::error::Result; use sync::{Intex, WaitQueue}; pub trait NetworkScheme { fn add(&mut self, resource: *mut NetworkResource); fn remove(&mut self, resource: *mut NetworkResource); fn sync(&mut self); } pub struct NetworkResource { pub nic: *mut NetworkScheme, pub ptr: *mut NetworkResource, pub inbound: WaitQueue<Vec<u8>>, pub outbound: Intex<VecDeque<Vec<u8>>>, } impl NetworkResource { pub fn new(nic: *mut NetworkScheme) -> Box<Self> { let mut ret = box NetworkResource { nic: nic, ptr: 0 as *mut NetworkResource, inbound: WaitQueue::new(), outbound: Intex::new(VecDeque::new()), }; unsafe { ret.ptr = ret.deref_mut(); (*ret.nic).add(ret.ptr); } ret } } impl Resource for NetworkResource { fn dup(&self) -> Result<Box<Resource>> { let mut ret = box NetworkResource { nic: self.nic, ptr: 0 as *mut NetworkResource, inbound: self.inbound.clone(), outbound: Intex::new(self.outbound.lock().clone()), }; unsafe { ret.ptr = ret.deref_mut(); (*ret.nic).add(ret.ptr); } Ok(ret) } fn path(&self, buf: &mut [u8]) -> Result<usize> { let path = b"network:"; let mut i = 0; while i < buf.len() && i < path.len() { buf[i] = path[i]; i += 1; } Ok(i) } fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let bytes = unsafe { (*self.nic).sync(); (*self.ptr).inbound.receive() }; let mut i = 0; while i < bytes.len() && i < buf.len() { buf[i] = bytes[i]; i += 1; } return Ok(bytes.len()); } fn write(&mut self, buf: &[u8]) -> Result<usize> { unsafe {
Ok(buf.len()) } fn sync(&mut self) -> Result<()> { unsafe { (*self.nic).sync(); } Ok(()) } } impl Drop for NetworkResource { fn drop(&mut self) { unsafe { (*self.nic).remove(self.ptr); } } }
(*self.ptr).outbound.lock().push_back(Vec::from(buf)); (*self.nic).sync(); }
random_line_split
Column.ts
/* Tournament grid Copyright (C) 2017 Egor Nepomnyaschih 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; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Class from "jwidget/Class"; import Dictionary from "jwidget/Dictionary"; import Functor from "jwidget/Functor"; import JWArray from "jwidget/JWArray"; import Property from "jwidget/Property"; import Cup from "./Cup"; import Match from "./Match"; import Participant from "./Participant"; import {GRID_TYPE_DOUBLE, MATCH_GAP, MATCH_HEIGHT} from "../../constants"; import locale from "../../locale"; export default class Column extends Class { index: number; cup: Cup; matches: JWArray<Match>; bo: number; superfinal: boolean = false; visible: Property<boolean>; visibleIndex: Property<number>; gap: Property<number>; offset: Property<number>; constructor(config: ColumnConfig) { super(); this.index = config.index; this.cup = config.cup; this.matches = new JWArray(config.matches); this.bo = config.bo; this.superfinal = config.superfinal; this.visible = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => this.index >= hiddenColumns)); this.visibleIndex = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => { if (this.cup.gridIndex === 1) { return Math.floor(this.index / 2) - Math.floor(hiddenColumns / 2); } return this.index - hiddenColumns - (this.superfinal ? 1 : 0); })); this.gap = this.own(this.visibleIndex.mapValue((visibleIndex) => { return Math.pow(2, visibleIndex) * (MATCH_HEIGHT + MATCH_GAP) - MATCH_HEIGHT; })); // rely on the fact that visibleIndex and gap are already computed this.offset = this.own(new Functor([this.cup.alignBy], (alignBy) => { if (!alignBy) { return this.gap.get() / 2; } const firstMatchIndex = this.cup.getParticipantVerticalIndex(alignBy); if (firstMatchIndex === undefined) { return this.gap.get() / 2; } const currentMatchIndex = Math.floor(firstMatchIndex / Math.pow(2, this.visibleIndex.get())); return MATCH_GAP / 2 + firstMatchIndex * (MATCH_HEIGHT + MATCH_GAP) - (this.gap.get() + MATCH_HEIGHT) * currentMatchIndex; })).watch(this.cup.hiddenColumns).target; } get title() { if (this.cup.gridIndex === 1) { return "";
(this.cup.gridType === GRID_TYPE_DOUBLE && this.cup.gridIndex === 0 ? 1 : 0) switch (columnsRemaining) { case 0: return locale("GRAND_FINAL"); case 1: return locale("FINAL"); case 2: return locale("SEMIFINAL"); default: return "1/" + this.matches.getLength(); } } get fullTitle() { return (this.cup.gridIndex === 1) ? ("Bo" + this.bo) : (this.title + ", Bo" + this.bo); } get next() { return this.cup.grid.get(this.index + 1); } get prev() { return this.cup.grid.get(this.index - 1); } get maxScore() { return (this.bo + 1) / 2; } update(column: Column) { this.matches.each((match, index) => { match.update(column.matches.get(index)); }) } static createByJson(json: any, index: number, cup: Cup, participants: Dictionary<Participant>, superfinal: boolean) { const column = new Column({ index: index, cup: cup, bo: +json["bo"], superfinal: superfinal }); column.matches.addAll((<any[]>json["matches"]).map((json, index) => Match.createByJson(json, column, index, participants))); return column; } } export interface ColumnConfig { index: number; cup: Cup; matches?: Match[]; bo: number; superfinal: boolean; }
} const columnsRemaining = this.cup.grid.getLength() - this.index -
random_line_split
Column.ts
/* Tournament grid Copyright (C) 2017 Egor Nepomnyaschih 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; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Class from "jwidget/Class"; import Dictionary from "jwidget/Dictionary"; import Functor from "jwidget/Functor"; import JWArray from "jwidget/JWArray"; import Property from "jwidget/Property"; import Cup from "./Cup"; import Match from "./Match"; import Participant from "./Participant"; import {GRID_TYPE_DOUBLE, MATCH_GAP, MATCH_HEIGHT} from "../../constants"; import locale from "../../locale"; export default class Column extends Class { index: number; cup: Cup; matches: JWArray<Match>; bo: number; superfinal: boolean = false; visible: Property<boolean>; visibleIndex: Property<number>; gap: Property<number>; offset: Property<number>; constructor(config: ColumnConfig) { super(); this.index = config.index; this.cup = config.cup; this.matches = new JWArray(config.matches); this.bo = config.bo; this.superfinal = config.superfinal; this.visible = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => this.index >= hiddenColumns)); this.visibleIndex = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => { if (this.cup.gridIndex === 1) { return Math.floor(this.index / 2) - Math.floor(hiddenColumns / 2); } return this.index - hiddenColumns - (this.superfinal ? 1 : 0); })); this.gap = this.own(this.visibleIndex.mapValue((visibleIndex) => { return Math.pow(2, visibleIndex) * (MATCH_HEIGHT + MATCH_GAP) - MATCH_HEIGHT; })); // rely on the fact that visibleIndex and gap are already computed this.offset = this.own(new Functor([this.cup.alignBy], (alignBy) => { if (!alignBy) { return this.gap.get() / 2; } const firstMatchIndex = this.cup.getParticipantVerticalIndex(alignBy); if (firstMatchIndex === undefined) { return this.gap.get() / 2; } const currentMatchIndex = Math.floor(firstMatchIndex / Math.pow(2, this.visibleIndex.get())); return MATCH_GAP / 2 + firstMatchIndex * (MATCH_HEIGHT + MATCH_GAP) - (this.gap.get() + MATCH_HEIGHT) * currentMatchIndex; })).watch(this.cup.hiddenColumns).target; } get title() { if (this.cup.gridIndex === 1) { return ""; } const columnsRemaining = this.cup.grid.getLength() - this.index - (this.cup.gridType === GRID_TYPE_DOUBLE && this.cup.gridIndex === 0 ? 1 : 0) switch (columnsRemaining) { case 0: return locale("GRAND_FINAL"); case 1: return locale("FINAL"); case 2: return locale("SEMIFINAL"); default: return "1/" + this.matches.getLength(); } } get fullTitle() { return (this.cup.gridIndex === 1) ? ("Bo" + this.bo) : (this.title + ", Bo" + this.bo); } get next() { return this.cup.grid.get(this.index + 1); } get prev() { return this.cup.grid.get(this.index - 1); } get maxScore()
update(column: Column) { this.matches.each((match, index) => { match.update(column.matches.get(index)); }) } static createByJson(json: any, index: number, cup: Cup, participants: Dictionary<Participant>, superfinal: boolean) { const column = new Column({ index: index, cup: cup, bo: +json["bo"], superfinal: superfinal }); column.matches.addAll((<any[]>json["matches"]).map((json, index) => Match.createByJson(json, column, index, participants))); return column; } } export interface ColumnConfig { index: number; cup: Cup; matches?: Match[]; bo: number; superfinal: boolean; }
{ return (this.bo + 1) / 2; }
identifier_body
Column.ts
/* Tournament grid Copyright (C) 2017 Egor Nepomnyaschih 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; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Class from "jwidget/Class"; import Dictionary from "jwidget/Dictionary"; import Functor from "jwidget/Functor"; import JWArray from "jwidget/JWArray"; import Property from "jwidget/Property"; import Cup from "./Cup"; import Match from "./Match"; import Participant from "./Participant"; import {GRID_TYPE_DOUBLE, MATCH_GAP, MATCH_HEIGHT} from "../../constants"; import locale from "../../locale"; export default class Column extends Class { index: number; cup: Cup; matches: JWArray<Match>; bo: number; superfinal: boolean = false; visible: Property<boolean>; visibleIndex: Property<number>; gap: Property<number>; offset: Property<number>; constructor(config: ColumnConfig) { super(); this.index = config.index; this.cup = config.cup; this.matches = new JWArray(config.matches); this.bo = config.bo; this.superfinal = config.superfinal; this.visible = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => this.index >= hiddenColumns)); this.visibleIndex = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => { if (this.cup.gridIndex === 1) { return Math.floor(this.index / 2) - Math.floor(hiddenColumns / 2); } return this.index - hiddenColumns - (this.superfinal ? 1 : 0); })); this.gap = this.own(this.visibleIndex.mapValue((visibleIndex) => { return Math.pow(2, visibleIndex) * (MATCH_HEIGHT + MATCH_GAP) - MATCH_HEIGHT; })); // rely on the fact that visibleIndex and gap are already computed this.offset = this.own(new Functor([this.cup.alignBy], (alignBy) => { if (!alignBy) { return this.gap.get() / 2; } const firstMatchIndex = this.cup.getParticipantVerticalIndex(alignBy); if (firstMatchIndex === undefined) { return this.gap.get() / 2; } const currentMatchIndex = Math.floor(firstMatchIndex / Math.pow(2, this.visibleIndex.get())); return MATCH_GAP / 2 + firstMatchIndex * (MATCH_HEIGHT + MATCH_GAP) - (this.gap.get() + MATCH_HEIGHT) * currentMatchIndex; })).watch(this.cup.hiddenColumns).target; } get
() { if (this.cup.gridIndex === 1) { return ""; } const columnsRemaining = this.cup.grid.getLength() - this.index - (this.cup.gridType === GRID_TYPE_DOUBLE && this.cup.gridIndex === 0 ? 1 : 0) switch (columnsRemaining) { case 0: return locale("GRAND_FINAL"); case 1: return locale("FINAL"); case 2: return locale("SEMIFINAL"); default: return "1/" + this.matches.getLength(); } } get fullTitle() { return (this.cup.gridIndex === 1) ? ("Bo" + this.bo) : (this.title + ", Bo" + this.bo); } get next() { return this.cup.grid.get(this.index + 1); } get prev() { return this.cup.grid.get(this.index - 1); } get maxScore() { return (this.bo + 1) / 2; } update(column: Column) { this.matches.each((match, index) => { match.update(column.matches.get(index)); }) } static createByJson(json: any, index: number, cup: Cup, participants: Dictionary<Participant>, superfinal: boolean) { const column = new Column({ index: index, cup: cup, bo: +json["bo"], superfinal: superfinal }); column.matches.addAll((<any[]>json["matches"]).map((json, index) => Match.createByJson(json, column, index, participants))); return column; } } export interface ColumnConfig { index: number; cup: Cup; matches?: Match[]; bo: number; superfinal: boolean; }
title
identifier_name
Column.ts
/* Tournament grid Copyright (C) 2017 Egor Nepomnyaschih 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; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Class from "jwidget/Class"; import Dictionary from "jwidget/Dictionary"; import Functor from "jwidget/Functor"; import JWArray from "jwidget/JWArray"; import Property from "jwidget/Property"; import Cup from "./Cup"; import Match from "./Match"; import Participant from "./Participant"; import {GRID_TYPE_DOUBLE, MATCH_GAP, MATCH_HEIGHT} from "../../constants"; import locale from "../../locale"; export default class Column extends Class { index: number; cup: Cup; matches: JWArray<Match>; bo: number; superfinal: boolean = false; visible: Property<boolean>; visibleIndex: Property<number>; gap: Property<number>; offset: Property<number>; constructor(config: ColumnConfig) { super(); this.index = config.index; this.cup = config.cup; this.matches = new JWArray(config.matches); this.bo = config.bo; this.superfinal = config.superfinal; this.visible = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => this.index >= hiddenColumns)); this.visibleIndex = this.own(this.cup.hiddenColumns.mapValue((hiddenColumns) => { if (this.cup.gridIndex === 1)
return this.index - hiddenColumns - (this.superfinal ? 1 : 0); })); this.gap = this.own(this.visibleIndex.mapValue((visibleIndex) => { return Math.pow(2, visibleIndex) * (MATCH_HEIGHT + MATCH_GAP) - MATCH_HEIGHT; })); // rely on the fact that visibleIndex and gap are already computed this.offset = this.own(new Functor([this.cup.alignBy], (alignBy) => { if (!alignBy) { return this.gap.get() / 2; } const firstMatchIndex = this.cup.getParticipantVerticalIndex(alignBy); if (firstMatchIndex === undefined) { return this.gap.get() / 2; } const currentMatchIndex = Math.floor(firstMatchIndex / Math.pow(2, this.visibleIndex.get())); return MATCH_GAP / 2 + firstMatchIndex * (MATCH_HEIGHT + MATCH_GAP) - (this.gap.get() + MATCH_HEIGHT) * currentMatchIndex; })).watch(this.cup.hiddenColumns).target; } get title() { if (this.cup.gridIndex === 1) { return ""; } const columnsRemaining = this.cup.grid.getLength() - this.index - (this.cup.gridType === GRID_TYPE_DOUBLE && this.cup.gridIndex === 0 ? 1 : 0) switch (columnsRemaining) { case 0: return locale("GRAND_FINAL"); case 1: return locale("FINAL"); case 2: return locale("SEMIFINAL"); default: return "1/" + this.matches.getLength(); } } get fullTitle() { return (this.cup.gridIndex === 1) ? ("Bo" + this.bo) : (this.title + ", Bo" + this.bo); } get next() { return this.cup.grid.get(this.index + 1); } get prev() { return this.cup.grid.get(this.index - 1); } get maxScore() { return (this.bo + 1) / 2; } update(column: Column) { this.matches.each((match, index) => { match.update(column.matches.get(index)); }) } static createByJson(json: any, index: number, cup: Cup, participants: Dictionary<Participant>, superfinal: boolean) { const column = new Column({ index: index, cup: cup, bo: +json["bo"], superfinal: superfinal }); column.matches.addAll((<any[]>json["matches"]).map((json, index) => Match.createByJson(json, column, index, participants))); return column; } } export interface ColumnConfig { index: number; cup: Cup; matches?: Match[]; bo: number; superfinal: boolean; }
{ return Math.floor(this.index / 2) - Math.floor(hiddenColumns / 2); }
conditional_block
tags.ts
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. export const tags = [ ".htaccess", ".net", ".net-core", "abap", "access-vba", "actions-on-google", "actionscript", "actionscript-3", "active-directory", "activemq", "acumatica", "ada", "admin-on-rest", "admob", "adobe-analytics", "aem", "aerospike", "aframe", "ag-grid", "air", "airflow", "ajax", "akka", "alfresco", "algolia", "algorithm", "alloy", "amazon-dynamodb", "amazon-ec2", "amazon-redshift", "amazon-s3", "amazon-web-services", "amcharts", "amp-html", "android", "android-emulator", "android-fragments", "android-layout", "android-ndk", "android-studio", "angular", "angular-cli", "angular-material", "angular-ui-grid", "angular2-routing", "angular5", "angularjs", "ansible", "ant", "antlr", "antlr4", "apache", "apache-camel", "apache-flink", "apache-kafka", "apache-nifi", "apache-pig", "apache-poi", "apache-spark", "apache-storm", "apache-zeppelin", "apache-zookeeper", "apache2", "api", "apigee", "apostrophe-cms", "appium", "applescript", "aptana", "arangodb", "architecture", "arduino", "arm", "arrays", "artifactory", "artificial-intelligence", "asana", "asp-classic", "asp.net", "asp.net-ajax", "asp.net-core", "asp.net-core-mvc", "asp.net-mvc", "asp.net-mvc-2", "asp.net-mvc-3", "asp.net-mvc-4", "asp.net-mvc-5", "asp.net-web-api", "aspnetboilerplate", "assembly", "asterisk", "atk4", "atom-editor", "audio", "aurelia", "autofac", "autohotkey", "autoit", "automapper", "awk", "azure", "azure-active-directory", "azure-ad-b2c", "azure-cosmosdb", "azure-search", "azure-service-fabric", "azure-sql-database", "backbone.js", "bash", "batch-file", "bazel", "big-o", "bigcommerce", "binary", "bing-maps", "birt", "biztalk", "blackberry", "bokeh", "boost", "bootstrap-4", "botframework", "bower", "box-api", "breeze", "browser", "c", "c#", "c#-2.0", "c#-3.0", "c#-4.0", "c++", "c++-cli", "c++11", "caching", "caffe", "cakephp", "cakephp-2.0", "cakephp-3.0", "casperjs", "cassandra", "castle-windsor", "chart.js", "chef", "chromecast", "ckan", "ckeditor", "clearcase", "clickonce", "clips", "clojure", "clojurescript", "cloudfoundry", "cmake", "cmd", "cntk", "cobol", "cocoa", "cocoa-touch", "cocoapods", "cocos2d-iphone", "cocos2d-x", "coded-ui-tests", "codeigniter", "codeigniter-3", "codenameone", "coding-style", "coffeescript", "cognos", "coldfusion", "common-lisp", "compiler-construction", "composer-php", "computer-science", "content-management-system", "cookies", "coq", "corda", "cordova", "core-data", "corona", "couchbase", "couchdb", "cq5", "cron", "cruisecontrol.net", "crystal-lang", "crystal-reports", "css", "css3", "csv", "cucumber", "cuda", "curl", "cvs", "cygwin", "cytoscape.js", "d", "d3.js", "dapper", "dart", "data-structures", "database", "database-design", "datatables", "db2", "dc.js", "debugging", "delphi", "design", "design-patterns", "desire2learn", "devexpress", "django", "django-models", "django-rest-framework", "dns", "docker", "doctrine2", "docusignapi", "dojo", "domain-driven-design", "dotnetnuke", "doxygen", "drools", "drupal", "drupal-6", "drupal-7", "drupal-8", "dygraphs", "dynamics-crm", "dynamics-crm-2011", "dynamics-crm-2013", "eclipse", "eclipse-plugin", "eclipse-rcp", "ecmascript-6", "elasticsearch", "electron", "elisp", "elixir", "elm", "emacs", "email", "ember.js", "encryption", "enterprise-architect", "entity-framework", "entity-framework-4", "entity-framework-4.1", "entity-framework-5", "entity-framework-6", "entity-framework-core", "erlang", "excel", "excel-2007", "excel-2010", "excel-formula", "excel-vba", "exchangewebservices", "expect", "express", "expressionengine", "extjs", "extjs4", "extjs4.1", "f#", "fabricjs", "facebook", "facebook-c#-sdk", "facebook-graph-api", "facebook-like", "famo.us", "ffmpeg", "fiddler", "file", "filemaker", "filepicker.io", "fine-uploader", "firebase", "firefox", "firefox-addon", "fish", "fiware-orion", "flash", "flask", "flex", "flot", "flowtype", "fluent-nhibernate", "flutter", "flyway", "fonts", "forms", "fortran", "foursquare", "freemarker", "ftp", "fullcalendar", "functional-programming", "gcc", "gdb", "gerrit", "getstream-io", "git", "github", "gitlab", "glassfish", "gmail-api", "gnu-make", "gnuplot", "go", "google-admin-sdk", "google-adwords", "google-analytics", "google-analytics-api", "google-api", "google-app-engine", "google-apps-marketplace", "google-apps-script", "google-bigquery", "google-calendar", "google-chrome", "google-chrome-app", "google-chrome-devtools", "google-chrome-extension", "google-cloud-dataflow", "google-cloud-messaging", "google-cloud-platform", "google-cloud-sql", "google-cloud-storage", "google-compute-engine", "google-drive-sdk", "google-fusion-tables", "google-maps", "google-maps-api-3", "google-oauth", "google-places-api", "google-play", "google-plus", "google-project-tango", "google-search", "google-spreadsheet", "google-tag-manager", "google-visualization", "gradle", "grails", "graph", "graphql", "graphviz", "grep", "groovy", "gruntjs", "gstreamer", "gtk", "gulp", "gwt", "h2", "hadoop", "handlebars.js", "handsontable", "haproxy", "hash", "haskell", "haxe", "hazelcast", "hbase", "here-api", "heroku", "hibernate", "highcharts", "hive", "hl7-fhir", "homebrew", "hsqldb", "html", "html5", "html5-canvas", "http", "hudson", "hybris", "hyperledger-composer", "hyperledger-fabric", "ibm-cloud", "ibm-cloud-infrastructure", "ibm-mobilefirst", "ibm-mq", "identityserver3", "identityserver4", "idris", "if-statement", "iframe", "ignite", "iis", "iis-7", "imacros", "image", "image-processing", "imagemagick", "imageresizer", "indexeddb", "influxdb", "informatica", "informix", "inno-setup", "instagram", "instagram-api", "install4j", "installshield", "intellij-idea", "internet-explorer", "intuit-partner-platform", "ionic-framework", "ionic2", "ionic3", "ios", "ios4", "ios5", "ios7", "ipad", "iphone", "ipython", "isabelle", "itext", "itextsharp", "itunesconnect", "j", "jasper-reports", "java", "java-8", "java-ee", "java-me", "javafx", "javafx-2", "javafx-8", "javamail", "javascript", "javascript-events", "jaxb", "jboss", "jbpm", "jdbc", "jekyll", "jenkins", "jetty", "jfreechart", "jhipster", "jira", "jmeter", "joomla", "joomla2.5", "joomla3.0", "jpa", "jqgrid", "jqplot", "jquery", "jquery-mobile", "jquery-plugins", "jquery-select2", "jquery-selectors", "jquery-ui", "jsf", "jsf-2", "json", "json.net", "jsoup", "jsp", "jssor", "jstl", "jstree", "julia-lang", "junit", "jupyter-notebook", "jwplayer", "kaa", "karate", "kdb", "kendo-grid", "kendo-ui", "kentico", "keras", "kineticjs", "kivy", "knockout.js", "kotlin", "kubernetes", "labview", "language-agnostic", "laravel", "laravel-4", "laravel-5", "laravel-5.1", "laravel-5.2", "laravel-5.3", "laravel-5.4", "latex", "ldap", "leaflet", "less", "libgdx", "licensing", "liferay", "liferay-6", "linkedin", "linq", "linq-to-entities", "linq-to-sql", "linq-to-xml", "linux", "linux-kernel", "liquibase", "lisp", "livecode", "llvm", "loadrunner", "log4j", "log4j2", "log4net", "logstash", "loopbackjs", "lotus-notes", "lua", "lucene", "lucene.net", "machine-learning", "macos", "magento", "magento-1.7", "magento-1.9", "magento2", "mailchimp", "makefile", "maple", "marionette", "markdown", "marklogic", "material-ui", "math", "matlab", "matplotlib", "maven", "maven-2", "maven-3", "maxima", "mdx", "mediaelement.js", "mediawiki", "memcached", "mercurial", "meteor", "mfc", "microsoft-cognitive", "microsoft-graph", "mips", "mobile", "mod-rewrite", "model-view-controller", "momentjs", "mongodb", "mongoose", "mono", "moodle", "mootools", "mpi", "ms-access", "ms-access-2007", "ms-access-2010", "ms-word", "msbuild", "msmq", "mule", "multithreading", "mvvm-light", "mvvmcross", "mybatis", "mysql", "mysql-workbench", "mysqli", "nagios", "nativescript", "neo4j", "nest-api", "netbeans", "netlogo", "netsuite", "netty", "networking", "neural-network", "nginx", "nhibernate", "nightwatch.js", "nlog", "nlp", "node-red", "node.js", "notepad++", "npm", "nservicebus", "nsis", "nuget", "numpy", "nunit", "nutch", "oauth", "oauth-2.0", "objective-c", "ocaml", "octave", "odata", "office-js", "office365", "omnet++", "onedrive", "onsen-ui", "oop", "open-source", "opencart", "opencl", "opencv", "openerp", "opengl", "opengl-es", "openlayers", "openlayers-3", "openmp", "openshift", "openssl", "openstack", "operating-system", "optaplanner", "oracle", "oracle-adf", "oracle-apex", "oracle-sqldeveloper", "oracle10g", "oracle11g", "orbeon", "orchardcms", "orientdb", "outlook", "pandas", "parse.com", "pascal", "paw-app", "paypal", "pdf", "pdfbox", "pentaho", "perforce", "performance", "perl", "perl6", "phalcon", "phantomjs", "phaser-framework", "php", "phpexcel", "phpmailer", "phpmyadmin", "phpstorm", "phpunit", "playframework", "playframework-2.0", "plone", "plsql", "polymer", "polymer-1.0", "postgresql", "postman", "powerbi", "powerbuilder", "powershell", "powershell-v2.0", "powershell-v3.0", "prestashop", "primefaces", "processing", "programming-languages", "project-management", "prolog", "prometheus", "protobuf-net", "protocol-buffers", "protractor", "pug", "puppet", "purescript", "pycharm", "pygame", "pyspark", "python", "python-2.7", "python-3.6", "python-3.x", "python-sphinx", "qlikview", "qml", "qooxdoo", "qt", "qt4", "qtp", "quartz-scheduler", "quickblox", "quickbooks", "r", "rabbitmq", "racket", "ractivejs", "rally", "random", "raphael", "rascal", "raspberry-pi", "ravendb", "razor", "rdlc", "react-native", "react-router", "reactjs", "realm", "rebol", "recaptcha", "recursion", "redhawksdr", "redirect", "redis", "redux", "regex", "reporting-services", "requirejs", "resharper", "rest", "rethinkdb", "robotframework", "robots.txt", "rspec", "rstudio", "rsync", "ruby", "ruby-on-rails", "ruby-on-rails-3", "ruby-on-rails-3.1", "ruby-on-rails-3.2", "ruby-on-rails-4", "rust", "rx-java", "rxjs", "sabre", "sails.js", "salesforce", "salt-stack", "sap", "sapui5", "sas", "sass", "sbt", "scala", "scala.js", "scheme", "scikit-learn", "scons", "scrapy", "search", "security", "sed", "selenium", "selenium-ide", "selenium-webdriver", "semantic-ui", "sencha-touch", "sencha-touch-2", "seo", "sequelize.js", "servicestack", "servlets", "sharepoint", "sharepoint-2007", "sharepoint-2010", "sharepoint-2013", "shell", "shiny", "shopify", "signalr", "silverlight", "silverlight-4.0", "silverstripe", "sitecore", "slickgrid", "smartface.io", "smartgwt", "smarty", "sml", "soapui", "socket.io", "sockets", "solr", "sonarqube", "sorting", "soundcloud", "sparql", "specflow", "sphinx", "splunk", "spotfire", "spotify", "spring", "spring-batch", "spring-boot", "spring-data-jpa", "spring-integration", "spring-mvc", "spring-roo", "spring-security", "spring-xd", "sprite-kit", "spss", "sql", "sql-server", "sql-server-2005", "sql-server-2008", "sql-server-2008-r2", "sql-server-2012", "sqlalchemy", "sqlite", "sqlite3", "sqoop", "square-connect", "ssas", "ssh", "ssis", "ssl", "ssrs-2008", "stanford-nlp", "stata", "string", "stripe-payments", "struts", "struts2", "sublimetext2", "sublimetext3", "subsonic", "sugarcrm", "surveymonkey", "svg", "svn", "swagger", "swift", "swift2", "swift3", "sybase", "symfony", "symfony1", "system-verilog", "system.reactive", "tableau", "tag", "talend", "tapestry", "tcl", "tcp", "teamcity", "tensorflow", "teradata", "terminology", "terraform", "testing", "testng", "tfs", "tfs2010", "three.js", "thymeleaf", "time-complexity", "tinymce", "titanium", "tkinter", "tmux", "tomcat", "tortoisesvn", "travis-ci", "tridion", "trigger.io", "tsql", "tumblr", "twig", "twilio", "twitter", "twitter-bootstrap", "twitter-bootstrap-3", "typescript", "typo3",
"ubuntu", "uitableview", "umbraco", "uml", "unicode", "unit-testing", "unity3d", "unix", "url", "user-interface", "uwp", "vaadin", "vagrant", "vb.net", "vb.net-2010", "vb6", "vba", "vbscript", "verilog", "version-control", "vhdl", "video.js", "vim", "virtualbox", "visual-c++", "visual-studio", "visual-studio-2008", "visual-studio-2010", "visual-studio-2012", "visual-studio-2013", "visual-studio-2015", "visual-studio-2017", "visual-studio-code", "visual-studio-lightswitch", "vsts", "vue.js", "vuejs2", "vulkan", "wagtail", "wcf", "web", "web-applications", "web-crawler", "web-services", "web2py", "webgl", "weblogic", "webpack", "webrtc", "websocket", "websphere", "webstorm", "weka", "wget", "wicket", "winapi", "windbg", "windows", "windows-7", "windows-8", "windows-installer", "windows-mobile", "windows-phone", "windows-phone-7", "windows-phone-8", "windows-phone-8.1", "windows-services", "winforms", "wix", "wolfram-mathematica", "woocommerce", "wordpress", "workflow-foundation-4", "wpf", "wso2", "wso2esb", "wso2is", "wxpython", "wxwidgets", "xamarin", "xamarin.android", "xamarin.forms", "xamarin.ios", "xaml", "xampp", "xcode", "xcode4", "xml", "xna", "xpages", "xpath", "xquery", "xsd", "xslt", "xslt-1.0", "xslt-2.0", "xtext", "yammer", "yii", "yii2", "yodlee", "youtube", "youtube-api", "z3", "zabbix", "zend-framework", "zend-framework2", "zeromq", "zsh", "zurb-foundation", ];
"uber-api",
random_line_split
index.ts
import { Injectable } from '@angular/core'; import { CordovaProperty, IonicNativePlugin, Plugin } from '@ionic-native/core'; /** * @name Uid * @description * Get unique identifiers: UUID, IMEI, IMSI, ICCID and MAC. * * @usage * ```typescript * import { Uid } from '@ionic-native/uid/ngx'; * import { AndroidPermissions } from '@ionic-native/android-permissions/ngx'; * * constructor(private uid: Uid, private androidPermissions: AndroidPermissions) { } *
* const { hasPermission } = await this.androidPermissions.checkPermission( * this.androidPermissions.PERMISSION.READ_PHONE_STATE * ); * * if (!hasPermission) { * const result = await this.androidPermissions.requestPermission( * this.androidPermissions.PERMISSION.READ_PHONE_STATE * ); * * if (!result.hasPermission) { * throw new Error('Permissions required'); * } * * // ok, a user gave us permission, we can get him identifiers after restart app * return; * } * * return this.uid.IMEI * } * ``` */ @Plugin({ pluginName: 'Uid', plugin: 'cordova-plugin-uid', pluginRef: 'cordova.plugins.uid', repo: 'https://github.com/lionelhe/cordova-plugin-uid', platforms: ['Android'] }) @Injectable({ providedIn: 'root' }) export class Uid extends IonicNativePlugin { /** Get the device Universally Unique Identifier (UUID). */ @CordovaProperty() UUID: string; /** Get the device International Mobile Station Equipment Identity (IMEI). */ @CordovaProperty() IMEI: string; /** Get the device International mobile Subscriber Identity (IMSI). */ @CordovaProperty() IMSI: string; /** Get the sim Integrated Circuit Card Identifier (ICCID). */ @CordovaProperty() ICCID: string; /** Get the Media Access Control address (MAC). */ @CordovaProperty() MAC: string; }
* * async getImei() {
random_line_split
index.ts
import { Injectable } from '@angular/core'; import { CordovaProperty, IonicNativePlugin, Plugin } from '@ionic-native/core'; /** * @name Uid * @description * Get unique identifiers: UUID, IMEI, IMSI, ICCID and MAC. * * @usage * ```typescript * import { Uid } from '@ionic-native/uid/ngx'; * import { AndroidPermissions } from '@ionic-native/android-permissions/ngx'; * * constructor(private uid: Uid, private androidPermissions: AndroidPermissions) { } * * * async getImei() { * const { hasPermission } = await this.androidPermissions.checkPermission( * this.androidPermissions.PERMISSION.READ_PHONE_STATE * ); * * if (!hasPermission) { * const result = await this.androidPermissions.requestPermission( * this.androidPermissions.PERMISSION.READ_PHONE_STATE * ); * * if (!result.hasPermission) { * throw new Error('Permissions required'); * } * * // ok, a user gave us permission, we can get him identifiers after restart app * return; * } * * return this.uid.IMEI * } * ``` */ @Plugin({ pluginName: 'Uid', plugin: 'cordova-plugin-uid', pluginRef: 'cordova.plugins.uid', repo: 'https://github.com/lionelhe/cordova-plugin-uid', platforms: ['Android'] }) @Injectable({ providedIn: 'root' }) export class
extends IonicNativePlugin { /** Get the device Universally Unique Identifier (UUID). */ @CordovaProperty() UUID: string; /** Get the device International Mobile Station Equipment Identity (IMEI). */ @CordovaProperty() IMEI: string; /** Get the device International mobile Subscriber Identity (IMSI). */ @CordovaProperty() IMSI: string; /** Get the sim Integrated Circuit Card Identifier (ICCID). */ @CordovaProperty() ICCID: string; /** Get the Media Access Control address (MAC). */ @CordovaProperty() MAC: string; }
Uid
identifier_name
state.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright 2018 Google, Inc # Written by Simon Glass <[email protected]> # # Holds and modifies the state information held by binman # import hashlib import re from dtoc import fdt import os from patman import tools from patman import tout # Records the device-tree files known to binman, keyed by entry type (e.g. # 'u-boot-spl-dtb'). These are the output FDT files, which can be updated by # binman. They have been copied to <xxx>.out files. # # key: entry type # value: tuple: # Fdt object # Filename # Entry object, or None if not known output_fdt_info = {} # Prefix to add to an fdtmap path to turn it into a path to the /binman node fdt_path_prefix = '' # Arguments passed to binman to provide arguments to entries entry_args = {} # True to use fake device-tree files for testing (see U_BOOT_DTB_DATA in # ftest.py) use_fake_dtb = False # The DTB which contains the full image information main_dtb = None # Allow entries to expand after they have been packed. This is detected and # forces a re-pack. If not allowed, any attempted expansion causes an error in # Entry.ProcessContentsUpdate() allow_entry_expansion = True # Don't allow entries to contract after they have been packed. Instead just # leave some wasted space. If allowed, this is detected and forces a re-pack, # but may result in entries that oscillate in size, thus causing a pack error. # An example is a compressed device tree where the original offset values # result in a larger compressed size than the new ones, but then after updating # to the new ones, the compressed size increases, etc. allow_entry_contraction = False def GetFdtForEtype(etype): """Get the Fdt object for a particular device-tree entry Binman keeps track of at least one device-tree file called u-boot.dtb but can also have others (e.g. for SPL). This function looks up the given entry and returns the associated Fdt object. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Fdt object associated with the entry type """ value = output_fdt_info.get(etype); if not value: return None return value[0] def GetFdtPath(etype): """Get the full pathname of a particular Fdt object Similar to GetFdtForEtype() but returns the pathname associated with the Fdt. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Full path name to the associated Fdt """ return output_fdt_info[etype][0]._fname def GetFdtContents(etype='u-boot-dtb'): """Looks up the FDT pathname and contents This is used to obtain the Fdt pathname and contents when needed by an entry. It supports a 'fake' dtb, allowing tests to substitute test data for the real dtb. Args: etype: Entry type to look up (e.g. 'u-boot.dtb'). Returns: tuple: pathname to Fdt Fdt data (as bytes) """ if etype not in output_fdt_info: return None, None if not use_fake_dtb: pathname = GetFdtPath(etype) data = GetFdtForEtype(etype).GetContents() else: fname = output_fdt_info[etype][1] pathname = tools.GetInputFilename(fname) data = tools.ReadFile(pathname) return pathname, data def UpdateFdtContents(etype, data): """Update the contents of a particular device tree The device tree is updated and written back to its file. This affects what is returned from future called to GetFdtContents(), etc. Args: etype: Entry type (e.g. 'u-boot-dtb') data: Data to replace the DTB with """ dtb, fname, entry = output_fdt_info[etype] dtb_fname = dtb.GetFilename() tools.WriteFile(dtb_fname, data) dtb = fdt.FdtScan(dtb_fname) output_fdt_info[etype] = [dtb, fname, entry] def SetEntryArgs(args): """Set the value of the entry args This sets up the entry_args dict which is used to supply entry arguments to entries. Args: args: List of entry arguments, each in the format "name=value" """ global entry_args entry_args = {} if args: for arg in args: m = re.match('([^=]*)=(.*)', arg) if not m: raise ValueError("Invalid entry arguemnt '%s'" % arg) entry_args[m.group(1)] = m.group(2) def GetEntryArg(name): """Get the value of an entry argument Args: name: Name of argument to retrieve Returns: String value of argument """ return entry_args.get(name) def Prepare(images, dtb): """Get device tree files ready for use This sets up a set of device tree files that can be retrieved by GetAllFdts(). This includes U-Boot proper and any SPL device trees. Args: images: List of images being used dtb: Main dtb """ global output_fdt_info, main_dtb, fdt_path_prefix # Import these here in case libfdt.py is not available, in which case # the above help option still works. from dtoc import fdt from dtoc import fdt_util # If we are updating the DTBs we need to put these updated versions # where Entry_blob_dtb can find them. We can ignore 'u-boot.dtb' # since it is assumed to be the one passed in with options.dt, and # was handled just above. main_dtb = dtb output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['u-boot-dtb'] = [dtb, 'u-boot.dtb', None] output_fdt_info['u-boot-spl-dtb'] = [dtb, 'spl/u-boot-spl.dtb', None] output_fdt_info['u-boot-tpl-dtb'] = [dtb, 'tpl/u-boot-tpl.dtb', None] if not use_fake_dtb: fdt_set = {} for image in images.values(): fdt_set.update(image.GetFdts()) for etype, other in fdt_set.items(): entry, other_fname = other infile = tools.GetInputFilename(other_fname) other_fname_dtb = fdt_util.EnsureCompiled(infile) out_fname = tools.GetOutputFilename('%s.out' % os.path.split(other_fname)[1]) tools.WriteFile(out_fname, tools.ReadFile(other_fname_dtb)) other_dtb = fdt.FdtScan(out_fname) output_fdt_info[etype] = [other_dtb, out_fname, entry] def PrepareFromLoadedData(image): """Get device tree files ready for use with a loaded image Loaded images are different from images that are being created by binman, since there is generally already an fdtmap and we read the description from that. This provides the position and size of every entry in the image with no calculation required. This function uses the same output_fdt_info[] as Prepare(). It finds the device tree files, adds a reference to the fdtmap and sets the FDT path prefix to translate from the fdtmap (where the root node is the image node) to the normal device tree (where the image node is under a /binman node). Args: images: List of images being used """ global output_fdt_info, main_dtb, fdt_path_prefix tout.Info('Preparing device trees') output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['fdtmap'] = [image.fdtmap_dtb, 'u-boot.dtb', None] main_dtb = None tout.Info(" Found device tree type 'fdtmap' '%s'" % image.fdtmap_dtb.name) for etype, value in image.GetFdts().items(): entry, fname = value out_fname = tools.GetOutputFilename('%s.dtb' % entry.etype) tout.Info(" Found device tree type '%s' at '%s' path '%s'" % (etype, out_fname, entry.GetPath())) entry._filename = entry.GetDefaultFilename() data = entry.ReadData() tools.WriteFile(out_fname, data) dtb = fdt.Fdt(out_fname) dtb.Scan() image_node = dtb.GetNode('/binman') if 'multiple-images' in image_node.props: image_node = dtb.GetNode('/binman/%s' % image.image_node) fdt_path_prefix = image_node.path output_fdt_info[etype] = [dtb, None, entry] tout.Info(" FDT path prefix '%s'" % fdt_path_prefix) def GetAllFdts(): """Yield all device tree files being used by binman Yields: Device trees being used (U-Boot proper, SPL, TPL) """ if main_dtb: yield main_dtb for etype in output_fdt_info: dtb = output_fdt_info[etype][0] if dtb != main_dtb: yield dtb def GetUpdateNodes(node, for_repack=False): """Yield all the nodes that need to be updated in all device trees The property referenced by this node is added to any device trees which have the given node. Due to removable of unwanted notes, SPL and TPL may not have this node. Args: node: Node object in the main device tree to look up for_repack: True if we want only nodes which need 'repack' properties added to them (e.g. 'orig-offset'), False to return all nodes. We don't add repack properties to SPL/TPL device trees. Yields: Node objects in each device tree that is in use (U-Boot proper, which is node, SPL and TPL) """ yield node for dtb, fname, entry in output_fdt_info.values(): if dtb != node.GetFdt(): if for_repack and entry.etype != 'u-boot-dtb': continue other_node = dtb.GetNode(fdt_path_prefix + node.path) #print(' try', fdt_path_prefix + node.path, other_node) if other_node: yield other_node def AddZeroProp(node, prop, for_repack=False): """Add a new property to affected device trees with an integer value of 0. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): n.AddZeroProp(prop) def AddSubnode(node, name): """Add a new subnode to a node in affected device trees Args: node: Node to add to name: name of node to add Returns: New subnode that was created in main tree """ first = None for n in GetUpdateNodes(node): subnode = n.AddSubnode(name) if not first: first = subnode return first def AddString(node, prop, value): """Add a new string property to affected device trees Args: prop_name: Name of property value: String value (which will be \0-terminated in the DT) """ for n in GetUpdateNodes(node): n.AddString(prop, value) def SetInt(node, prop, value, for_repack=False): """Update an integer property in affected device trees with an integer value This is not allowed to change the size of the FDT. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): tout.Detail("File %s: Update node '%s' prop '%s' to %#x" % (n.GetFdt().name, n.path, prop, value)) n.SetInt(prop, value) def CheckAddHashProp(node): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo') if not algo: return "Missing 'algo' property for hash node" if algo.value == 'sha256': size = 32 else: return "Unknown hash algorithm '%s'" % algo for n in GetUpdateNodes(hash_node): n.AddEmptyProp('value', size) def CheckSetHashValue(node, get_data_func): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo').value if algo == 'sha256': m = hashlib.sha256() m.update(get_data_func()) data = m.digest() for n in GetUpdateNodes(hash_node): n.SetData('value', data) def SetAllowEntryExpansion(allow): """Set whether post-pack expansion of entries is allowed Args: allow: True to allow expansion, False to raise an exception """ global allow_entry_expansion allow_entry_expansion = allow def AllowEntryExpansion(): """Check whether post-pack expansion of entries is allowed Returns: True if expansion should be allowed, False if an exception should be raised """ return allow_entry_expansion def SetAllowEntryContraction(allow):
def AllowEntryContraction(): """Check whether post-pack contraction of entries is allowed Returns: True if contraction should be allowed, False if an exception should be raised """ return allow_entry_contraction
"""Set whether post-pack contraction of entries is allowed Args: allow: True to allow contraction, False to raise an exception """ global allow_entry_contraction allow_entry_contraction = allow
identifier_body
state.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright 2018 Google, Inc # Written by Simon Glass <[email protected]> # # Holds and modifies the state information held by binman # import hashlib import re from dtoc import fdt import os from patman import tools from patman import tout # Records the device-tree files known to binman, keyed by entry type (e.g. # 'u-boot-spl-dtb'). These are the output FDT files, which can be updated by # binman. They have been copied to <xxx>.out files. # # key: entry type # value: tuple: # Fdt object # Filename # Entry object, or None if not known output_fdt_info = {} # Prefix to add to an fdtmap path to turn it into a path to the /binman node fdt_path_prefix = '' # Arguments passed to binman to provide arguments to entries entry_args = {} # True to use fake device-tree files for testing (see U_BOOT_DTB_DATA in # ftest.py) use_fake_dtb = False # The DTB which contains the full image information main_dtb = None # Allow entries to expand after they have been packed. This is detected and # forces a re-pack. If not allowed, any attempted expansion causes an error in # Entry.ProcessContentsUpdate() allow_entry_expansion = True # Don't allow entries to contract after they have been packed. Instead just # leave some wasted space. If allowed, this is detected and forces a re-pack, # but may result in entries that oscillate in size, thus causing a pack error. # An example is a compressed device tree where the original offset values # result in a larger compressed size than the new ones, but then after updating # to the new ones, the compressed size increases, etc. allow_entry_contraction = False def GetFdtForEtype(etype): """Get the Fdt object for a particular device-tree entry Binman keeps track of at least one device-tree file called u-boot.dtb but can also have others (e.g. for SPL). This function looks up the given entry and returns the associated Fdt object. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Fdt object associated with the entry type """ value = output_fdt_info.get(etype); if not value: return None return value[0] def GetFdtPath(etype): """Get the full pathname of a particular Fdt object Similar to GetFdtForEtype() but returns the pathname associated with the Fdt. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Full path name to the associated Fdt """ return output_fdt_info[etype][0]._fname def GetFdtContents(etype='u-boot-dtb'): """Looks up the FDT pathname and contents This is used to obtain the Fdt pathname and contents when needed by an entry. It supports a 'fake' dtb, allowing tests to substitute test data for the real dtb. Args: etype: Entry type to look up (e.g. 'u-boot.dtb'). Returns: tuple: pathname to Fdt Fdt data (as bytes) """ if etype not in output_fdt_info: return None, None if not use_fake_dtb: pathname = GetFdtPath(etype) data = GetFdtForEtype(etype).GetContents() else: fname = output_fdt_info[etype][1] pathname = tools.GetInputFilename(fname) data = tools.ReadFile(pathname) return pathname, data def UpdateFdtContents(etype, data): """Update the contents of a particular device tree The device tree is updated and written back to its file. This affects what is returned from future called to GetFdtContents(), etc. Args: etype: Entry type (e.g. 'u-boot-dtb') data: Data to replace the DTB with """ dtb, fname, entry = output_fdt_info[etype] dtb_fname = dtb.GetFilename() tools.WriteFile(dtb_fname, data) dtb = fdt.FdtScan(dtb_fname) output_fdt_info[etype] = [dtb, fname, entry] def SetEntryArgs(args): """Set the value of the entry args This sets up the entry_args dict which is used to supply entry arguments to entries. Args: args: List of entry arguments, each in the format "name=value" """ global entry_args entry_args = {} if args: for arg in args: m = re.match('([^=]*)=(.*)', arg) if not m: raise ValueError("Invalid entry arguemnt '%s'" % arg) entry_args[m.group(1)] = m.group(2) def GetEntryArg(name): """Get the value of an entry argument Args: name: Name of argument to retrieve Returns: String value of argument """ return entry_args.get(name) def Prepare(images, dtb): """Get device tree files ready for use This sets up a set of device tree files that can be retrieved by GetAllFdts(). This includes U-Boot proper and any SPL device trees. Args: images: List of images being used dtb: Main dtb """ global output_fdt_info, main_dtb, fdt_path_prefix # Import these here in case libfdt.py is not available, in which case # the above help option still works. from dtoc import fdt from dtoc import fdt_util # If we are updating the DTBs we need to put these updated versions # where Entry_blob_dtb can find them. We can ignore 'u-boot.dtb' # since it is assumed to be the one passed in with options.dt, and # was handled just above. main_dtb = dtb output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['u-boot-dtb'] = [dtb, 'u-boot.dtb', None] output_fdt_info['u-boot-spl-dtb'] = [dtb, 'spl/u-boot-spl.dtb', None] output_fdt_info['u-boot-tpl-dtb'] = [dtb, 'tpl/u-boot-tpl.dtb', None] if not use_fake_dtb: fdt_set = {} for image in images.values(): fdt_set.update(image.GetFdts()) for etype, other in fdt_set.items(): entry, other_fname = other infile = tools.GetInputFilename(other_fname) other_fname_dtb = fdt_util.EnsureCompiled(infile) out_fname = tools.GetOutputFilename('%s.out' % os.path.split(other_fname)[1]) tools.WriteFile(out_fname, tools.ReadFile(other_fname_dtb)) other_dtb = fdt.FdtScan(out_fname) output_fdt_info[etype] = [other_dtb, out_fname, entry] def PrepareFromLoadedData(image): """Get device tree files ready for use with a loaded image Loaded images are different from images that are being created by binman, since there is generally already an fdtmap and we read the description from that. This provides the position and size of every entry in the image with no calculation required. This function uses the same output_fdt_info[] as Prepare(). It finds the device tree files, adds a reference to the fdtmap and sets the FDT path prefix to translate from the fdtmap (where the root node is the image node) to the normal device tree (where the image node is under a /binman node). Args: images: List of images being used """ global output_fdt_info, main_dtb, fdt_path_prefix tout.Info('Preparing device trees') output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['fdtmap'] = [image.fdtmap_dtb, 'u-boot.dtb', None] main_dtb = None tout.Info(" Found device tree type 'fdtmap' '%s'" % image.fdtmap_dtb.name) for etype, value in image.GetFdts().items(): entry, fname = value out_fname = tools.GetOutputFilename('%s.dtb' % entry.etype) tout.Info(" Found device tree type '%s' at '%s' path '%s'" % (etype, out_fname, entry.GetPath())) entry._filename = entry.GetDefaultFilename() data = entry.ReadData() tools.WriteFile(out_fname, data) dtb = fdt.Fdt(out_fname) dtb.Scan() image_node = dtb.GetNode('/binman') if 'multiple-images' in image_node.props: image_node = dtb.GetNode('/binman/%s' % image.image_node) fdt_path_prefix = image_node.path output_fdt_info[etype] = [dtb, None, entry] tout.Info(" FDT path prefix '%s'" % fdt_path_prefix) def GetAllFdts(): """Yield all device tree files being used by binman Yields: Device trees being used (U-Boot proper, SPL, TPL) """ if main_dtb: yield main_dtb for etype in output_fdt_info: dtb = output_fdt_info[etype][0] if dtb != main_dtb: yield dtb def GetUpdateNodes(node, for_repack=False): """Yield all the nodes that need to be updated in all device trees The property referenced by this node is added to any device trees which have the given node. Due to removable of unwanted notes, SPL and TPL may not have this node. Args: node: Node object in the main device tree to look up for_repack: True if we want only nodes which need 'repack' properties added to them (e.g. 'orig-offset'), False to return all nodes. We don't add repack properties to SPL/TPL device trees. Yields: Node objects in each device tree that is in use (U-Boot proper, which is node, SPL and TPL) """ yield node for dtb, fname, entry in output_fdt_info.values(): if dtb != node.GetFdt(): if for_repack and entry.etype != 'u-boot-dtb': continue other_node = dtb.GetNode(fdt_path_prefix + node.path) #print(' try', fdt_path_prefix + node.path, other_node) if other_node: yield other_node def AddZeroProp(node, prop, for_repack=False): """Add a new property to affected device trees with an integer value of 0. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): n.AddZeroProp(prop) def AddSubnode(node, name): """Add a new subnode to a node in affected device trees Args: node: Node to add to name: name of node to add Returns: New subnode that was created in main tree """ first = None for n in GetUpdateNodes(node): subnode = n.AddSubnode(name) if not first: first = subnode return first def AddString(node, prop, value): """Add a new string property to affected device trees Args: prop_name: Name of property value: String value (which will be \0-terminated in the DT) """ for n in GetUpdateNodes(node): n.AddString(prop, value) def SetInt(node, prop, value, for_repack=False): """Update an integer property in affected device trees with an integer value This is not allowed to change the size of the FDT. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): tout.Detail("File %s: Update node '%s' prop '%s' to %#x" % (n.GetFdt().name, n.path, prop, value)) n.SetInt(prop, value) def CheckAddHashProp(node): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo') if not algo: return "Missing 'algo' property for hash node" if algo.value == 'sha256': size = 32 else:
n.AddEmptyProp('value', size) def CheckSetHashValue(node, get_data_func): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo').value if algo == 'sha256': m = hashlib.sha256() m.update(get_data_func()) data = m.digest() for n in GetUpdateNodes(hash_node): n.SetData('value', data) def SetAllowEntryExpansion(allow): """Set whether post-pack expansion of entries is allowed Args: allow: True to allow expansion, False to raise an exception """ global allow_entry_expansion allow_entry_expansion = allow def AllowEntryExpansion(): """Check whether post-pack expansion of entries is allowed Returns: True if expansion should be allowed, False if an exception should be raised """ return allow_entry_expansion def SetAllowEntryContraction(allow): """Set whether post-pack contraction of entries is allowed Args: allow: True to allow contraction, False to raise an exception """ global allow_entry_contraction allow_entry_contraction = allow def AllowEntryContraction(): """Check whether post-pack contraction of entries is allowed Returns: True if contraction should be allowed, False if an exception should be raised """ return allow_entry_contraction
return "Unknown hash algorithm '%s'" % algo for n in GetUpdateNodes(hash_node):
random_line_split
state.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright 2018 Google, Inc # Written by Simon Glass <[email protected]> # # Holds and modifies the state information held by binman # import hashlib import re from dtoc import fdt import os from patman import tools from patman import tout # Records the device-tree files known to binman, keyed by entry type (e.g. # 'u-boot-spl-dtb'). These are the output FDT files, which can be updated by # binman. They have been copied to <xxx>.out files. # # key: entry type # value: tuple: # Fdt object # Filename # Entry object, or None if not known output_fdt_info = {} # Prefix to add to an fdtmap path to turn it into a path to the /binman node fdt_path_prefix = '' # Arguments passed to binman to provide arguments to entries entry_args = {} # True to use fake device-tree files for testing (see U_BOOT_DTB_DATA in # ftest.py) use_fake_dtb = False # The DTB which contains the full image information main_dtb = None # Allow entries to expand after they have been packed. This is detected and # forces a re-pack. If not allowed, any attempted expansion causes an error in # Entry.ProcessContentsUpdate() allow_entry_expansion = True # Don't allow entries to contract after they have been packed. Instead just # leave some wasted space. If allowed, this is detected and forces a re-pack, # but may result in entries that oscillate in size, thus causing a pack error. # An example is a compressed device tree where the original offset values # result in a larger compressed size than the new ones, but then after updating # to the new ones, the compressed size increases, etc. allow_entry_contraction = False def GetFdtForEtype(etype): """Get the Fdt object for a particular device-tree entry Binman keeps track of at least one device-tree file called u-boot.dtb but can also have others (e.g. for SPL). This function looks up the given entry and returns the associated Fdt object. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Fdt object associated with the entry type """ value = output_fdt_info.get(etype); if not value: return None return value[0] def GetFdtPath(etype): """Get the full pathname of a particular Fdt object Similar to GetFdtForEtype() but returns the pathname associated with the Fdt. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Full path name to the associated Fdt """ return output_fdt_info[etype][0]._fname def GetFdtContents(etype='u-boot-dtb'): """Looks up the FDT pathname and contents This is used to obtain the Fdt pathname and contents when needed by an entry. It supports a 'fake' dtb, allowing tests to substitute test data for the real dtb. Args: etype: Entry type to look up (e.g. 'u-boot.dtb'). Returns: tuple: pathname to Fdt Fdt data (as bytes) """ if etype not in output_fdt_info: return None, None if not use_fake_dtb: pathname = GetFdtPath(etype) data = GetFdtForEtype(etype).GetContents() else: fname = output_fdt_info[etype][1] pathname = tools.GetInputFilename(fname) data = tools.ReadFile(pathname) return pathname, data def UpdateFdtContents(etype, data): """Update the contents of a particular device tree The device tree is updated and written back to its file. This affects what is returned from future called to GetFdtContents(), etc. Args: etype: Entry type (e.g. 'u-boot-dtb') data: Data to replace the DTB with """ dtb, fname, entry = output_fdt_info[etype] dtb_fname = dtb.GetFilename() tools.WriteFile(dtb_fname, data) dtb = fdt.FdtScan(dtb_fname) output_fdt_info[etype] = [dtb, fname, entry] def SetEntryArgs(args): """Set the value of the entry args This sets up the entry_args dict which is used to supply entry arguments to entries. Args: args: List of entry arguments, each in the format "name=value" """ global entry_args entry_args = {} if args: for arg in args: m = re.match('([^=]*)=(.*)', arg) if not m: raise ValueError("Invalid entry arguemnt '%s'" % arg) entry_args[m.group(1)] = m.group(2) def GetEntryArg(name): """Get the value of an entry argument Args: name: Name of argument to retrieve Returns: String value of argument """ return entry_args.get(name) def Prepare(images, dtb): """Get device tree files ready for use This sets up a set of device tree files that can be retrieved by GetAllFdts(). This includes U-Boot proper and any SPL device trees. Args: images: List of images being used dtb: Main dtb """ global output_fdt_info, main_dtb, fdt_path_prefix # Import these here in case libfdt.py is not available, in which case # the above help option still works. from dtoc import fdt from dtoc import fdt_util # If we are updating the DTBs we need to put these updated versions # where Entry_blob_dtb can find them. We can ignore 'u-boot.dtb' # since it is assumed to be the one passed in with options.dt, and # was handled just above. main_dtb = dtb output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['u-boot-dtb'] = [dtb, 'u-boot.dtb', None] output_fdt_info['u-boot-spl-dtb'] = [dtb, 'spl/u-boot-spl.dtb', None] output_fdt_info['u-boot-tpl-dtb'] = [dtb, 'tpl/u-boot-tpl.dtb', None] if not use_fake_dtb: fdt_set = {} for image in images.values(): fdt_set.update(image.GetFdts()) for etype, other in fdt_set.items(): entry, other_fname = other infile = tools.GetInputFilename(other_fname) other_fname_dtb = fdt_util.EnsureCompiled(infile) out_fname = tools.GetOutputFilename('%s.out' % os.path.split(other_fname)[1]) tools.WriteFile(out_fname, tools.ReadFile(other_fname_dtb)) other_dtb = fdt.FdtScan(out_fname) output_fdt_info[etype] = [other_dtb, out_fname, entry] def PrepareFromLoadedData(image): """Get device tree files ready for use with a loaded image Loaded images are different from images that are being created by binman, since there is generally already an fdtmap and we read the description from that. This provides the position and size of every entry in the image with no calculation required. This function uses the same output_fdt_info[] as Prepare(). It finds the device tree files, adds a reference to the fdtmap and sets the FDT path prefix to translate from the fdtmap (where the root node is the image node) to the normal device tree (where the image node is under a /binman node). Args: images: List of images being used """ global output_fdt_info, main_dtb, fdt_path_prefix tout.Info('Preparing device trees') output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['fdtmap'] = [image.fdtmap_dtb, 'u-boot.dtb', None] main_dtb = None tout.Info(" Found device tree type 'fdtmap' '%s'" % image.fdtmap_dtb.name) for etype, value in image.GetFdts().items(): entry, fname = value out_fname = tools.GetOutputFilename('%s.dtb' % entry.etype) tout.Info(" Found device tree type '%s' at '%s' path '%s'" % (etype, out_fname, entry.GetPath())) entry._filename = entry.GetDefaultFilename() data = entry.ReadData() tools.WriteFile(out_fname, data) dtb = fdt.Fdt(out_fname) dtb.Scan() image_node = dtb.GetNode('/binman') if 'multiple-images' in image_node.props: image_node = dtb.GetNode('/binman/%s' % image.image_node) fdt_path_prefix = image_node.path output_fdt_info[etype] = [dtb, None, entry] tout.Info(" FDT path prefix '%s'" % fdt_path_prefix) def GetAllFdts(): """Yield all device tree files being used by binman Yields: Device trees being used (U-Boot proper, SPL, TPL) """ if main_dtb: yield main_dtb for etype in output_fdt_info: dtb = output_fdt_info[etype][0] if dtb != main_dtb: yield dtb def GetUpdateNodes(node, for_repack=False): """Yield all the nodes that need to be updated in all device trees The property referenced by this node is added to any device trees which have the given node. Due to removable of unwanted notes, SPL and TPL may not have this node. Args: node: Node object in the main device tree to look up for_repack: True if we want only nodes which need 'repack' properties added to them (e.g. 'orig-offset'), False to return all nodes. We don't add repack properties to SPL/TPL device trees. Yields: Node objects in each device tree that is in use (U-Boot proper, which is node, SPL and TPL) """ yield node for dtb, fname, entry in output_fdt_info.values(): if dtb != node.GetFdt(): if for_repack and entry.etype != 'u-boot-dtb': continue other_node = dtb.GetNode(fdt_path_prefix + node.path) #print(' try', fdt_path_prefix + node.path, other_node) if other_node: yield other_node def AddZeroProp(node, prop, for_repack=False): """Add a new property to affected device trees with an integer value of 0. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): n.AddZeroProp(prop) def AddSubnode(node, name): """Add a new subnode to a node in affected device trees Args: node: Node to add to name: name of node to add Returns: New subnode that was created in main tree """ first = None for n in GetUpdateNodes(node):
return first def AddString(node, prop, value): """Add a new string property to affected device trees Args: prop_name: Name of property value: String value (which will be \0-terminated in the DT) """ for n in GetUpdateNodes(node): n.AddString(prop, value) def SetInt(node, prop, value, for_repack=False): """Update an integer property in affected device trees with an integer value This is not allowed to change the size of the FDT. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): tout.Detail("File %s: Update node '%s' prop '%s' to %#x" % (n.GetFdt().name, n.path, prop, value)) n.SetInt(prop, value) def CheckAddHashProp(node): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo') if not algo: return "Missing 'algo' property for hash node" if algo.value == 'sha256': size = 32 else: return "Unknown hash algorithm '%s'" % algo for n in GetUpdateNodes(hash_node): n.AddEmptyProp('value', size) def CheckSetHashValue(node, get_data_func): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo').value if algo == 'sha256': m = hashlib.sha256() m.update(get_data_func()) data = m.digest() for n in GetUpdateNodes(hash_node): n.SetData('value', data) def SetAllowEntryExpansion(allow): """Set whether post-pack expansion of entries is allowed Args: allow: True to allow expansion, False to raise an exception """ global allow_entry_expansion allow_entry_expansion = allow def AllowEntryExpansion(): """Check whether post-pack expansion of entries is allowed Returns: True if expansion should be allowed, False if an exception should be raised """ return allow_entry_expansion def SetAllowEntryContraction(allow): """Set whether post-pack contraction of entries is allowed Args: allow: True to allow contraction, False to raise an exception """ global allow_entry_contraction allow_entry_contraction = allow def AllowEntryContraction(): """Check whether post-pack contraction of entries is allowed Returns: True if contraction should be allowed, False if an exception should be raised """ return allow_entry_contraction
subnode = n.AddSubnode(name) if not first: first = subnode
conditional_block
state.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright 2018 Google, Inc # Written by Simon Glass <[email protected]> # # Holds and modifies the state information held by binman # import hashlib import re from dtoc import fdt import os from patman import tools from patman import tout # Records the device-tree files known to binman, keyed by entry type (e.g. # 'u-boot-spl-dtb'). These are the output FDT files, which can be updated by # binman. They have been copied to <xxx>.out files. # # key: entry type # value: tuple: # Fdt object # Filename # Entry object, or None if not known output_fdt_info = {} # Prefix to add to an fdtmap path to turn it into a path to the /binman node fdt_path_prefix = '' # Arguments passed to binman to provide arguments to entries entry_args = {} # True to use fake device-tree files for testing (see U_BOOT_DTB_DATA in # ftest.py) use_fake_dtb = False # The DTB which contains the full image information main_dtb = None # Allow entries to expand after they have been packed. This is detected and # forces a re-pack. If not allowed, any attempted expansion causes an error in # Entry.ProcessContentsUpdate() allow_entry_expansion = True # Don't allow entries to contract after they have been packed. Instead just # leave some wasted space. If allowed, this is detected and forces a re-pack, # but may result in entries that oscillate in size, thus causing a pack error. # An example is a compressed device tree where the original offset values # result in a larger compressed size than the new ones, but then after updating # to the new ones, the compressed size increases, etc. allow_entry_contraction = False def GetFdtForEtype(etype): """Get the Fdt object for a particular device-tree entry Binman keeps track of at least one device-tree file called u-boot.dtb but can also have others (e.g. for SPL). This function looks up the given entry and returns the associated Fdt object. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Fdt object associated with the entry type """ value = output_fdt_info.get(etype); if not value: return None return value[0] def GetFdtPath(etype): """Get the full pathname of a particular Fdt object Similar to GetFdtForEtype() but returns the pathname associated with the Fdt. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Full path name to the associated Fdt """ return output_fdt_info[etype][0]._fname def GetFdtContents(etype='u-boot-dtb'): """Looks up the FDT pathname and contents This is used to obtain the Fdt pathname and contents when needed by an entry. It supports a 'fake' dtb, allowing tests to substitute test data for the real dtb. Args: etype: Entry type to look up (e.g. 'u-boot.dtb'). Returns: tuple: pathname to Fdt Fdt data (as bytes) """ if etype not in output_fdt_info: return None, None if not use_fake_dtb: pathname = GetFdtPath(etype) data = GetFdtForEtype(etype).GetContents() else: fname = output_fdt_info[etype][1] pathname = tools.GetInputFilename(fname) data = tools.ReadFile(pathname) return pathname, data def UpdateFdtContents(etype, data): """Update the contents of a particular device tree The device tree is updated and written back to its file. This affects what is returned from future called to GetFdtContents(), etc. Args: etype: Entry type (e.g. 'u-boot-dtb') data: Data to replace the DTB with """ dtb, fname, entry = output_fdt_info[etype] dtb_fname = dtb.GetFilename() tools.WriteFile(dtb_fname, data) dtb = fdt.FdtScan(dtb_fname) output_fdt_info[etype] = [dtb, fname, entry] def SetEntryArgs(args): """Set the value of the entry args This sets up the entry_args dict which is used to supply entry arguments to entries. Args: args: List of entry arguments, each in the format "name=value" """ global entry_args entry_args = {} if args: for arg in args: m = re.match('([^=]*)=(.*)', arg) if not m: raise ValueError("Invalid entry arguemnt '%s'" % arg) entry_args[m.group(1)] = m.group(2) def GetEntryArg(name): """Get the value of an entry argument Args: name: Name of argument to retrieve Returns: String value of argument """ return entry_args.get(name) def Prepare(images, dtb): """Get device tree files ready for use This sets up a set of device tree files that can be retrieved by GetAllFdts(). This includes U-Boot proper and any SPL device trees. Args: images: List of images being used dtb: Main dtb """ global output_fdt_info, main_dtb, fdt_path_prefix # Import these here in case libfdt.py is not available, in which case # the above help option still works. from dtoc import fdt from dtoc import fdt_util # If we are updating the DTBs we need to put these updated versions # where Entry_blob_dtb can find them. We can ignore 'u-boot.dtb' # since it is assumed to be the one passed in with options.dt, and # was handled just above. main_dtb = dtb output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['u-boot-dtb'] = [dtb, 'u-boot.dtb', None] output_fdt_info['u-boot-spl-dtb'] = [dtb, 'spl/u-boot-spl.dtb', None] output_fdt_info['u-boot-tpl-dtb'] = [dtb, 'tpl/u-boot-tpl.dtb', None] if not use_fake_dtb: fdt_set = {} for image in images.values(): fdt_set.update(image.GetFdts()) for etype, other in fdt_set.items(): entry, other_fname = other infile = tools.GetInputFilename(other_fname) other_fname_dtb = fdt_util.EnsureCompiled(infile) out_fname = tools.GetOutputFilename('%s.out' % os.path.split(other_fname)[1]) tools.WriteFile(out_fname, tools.ReadFile(other_fname_dtb)) other_dtb = fdt.FdtScan(out_fname) output_fdt_info[etype] = [other_dtb, out_fname, entry] def
(image): """Get device tree files ready for use with a loaded image Loaded images are different from images that are being created by binman, since there is generally already an fdtmap and we read the description from that. This provides the position and size of every entry in the image with no calculation required. This function uses the same output_fdt_info[] as Prepare(). It finds the device tree files, adds a reference to the fdtmap and sets the FDT path prefix to translate from the fdtmap (where the root node is the image node) to the normal device tree (where the image node is under a /binman node). Args: images: List of images being used """ global output_fdt_info, main_dtb, fdt_path_prefix tout.Info('Preparing device trees') output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['fdtmap'] = [image.fdtmap_dtb, 'u-boot.dtb', None] main_dtb = None tout.Info(" Found device tree type 'fdtmap' '%s'" % image.fdtmap_dtb.name) for etype, value in image.GetFdts().items(): entry, fname = value out_fname = tools.GetOutputFilename('%s.dtb' % entry.etype) tout.Info(" Found device tree type '%s' at '%s' path '%s'" % (etype, out_fname, entry.GetPath())) entry._filename = entry.GetDefaultFilename() data = entry.ReadData() tools.WriteFile(out_fname, data) dtb = fdt.Fdt(out_fname) dtb.Scan() image_node = dtb.GetNode('/binman') if 'multiple-images' in image_node.props: image_node = dtb.GetNode('/binman/%s' % image.image_node) fdt_path_prefix = image_node.path output_fdt_info[etype] = [dtb, None, entry] tout.Info(" FDT path prefix '%s'" % fdt_path_prefix) def GetAllFdts(): """Yield all device tree files being used by binman Yields: Device trees being used (U-Boot proper, SPL, TPL) """ if main_dtb: yield main_dtb for etype in output_fdt_info: dtb = output_fdt_info[etype][0] if dtb != main_dtb: yield dtb def GetUpdateNodes(node, for_repack=False): """Yield all the nodes that need to be updated in all device trees The property referenced by this node is added to any device trees which have the given node. Due to removable of unwanted notes, SPL and TPL may not have this node. Args: node: Node object in the main device tree to look up for_repack: True if we want only nodes which need 'repack' properties added to them (e.g. 'orig-offset'), False to return all nodes. We don't add repack properties to SPL/TPL device trees. Yields: Node objects in each device tree that is in use (U-Boot proper, which is node, SPL and TPL) """ yield node for dtb, fname, entry in output_fdt_info.values(): if dtb != node.GetFdt(): if for_repack and entry.etype != 'u-boot-dtb': continue other_node = dtb.GetNode(fdt_path_prefix + node.path) #print(' try', fdt_path_prefix + node.path, other_node) if other_node: yield other_node def AddZeroProp(node, prop, for_repack=False): """Add a new property to affected device trees with an integer value of 0. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): n.AddZeroProp(prop) def AddSubnode(node, name): """Add a new subnode to a node in affected device trees Args: node: Node to add to name: name of node to add Returns: New subnode that was created in main tree """ first = None for n in GetUpdateNodes(node): subnode = n.AddSubnode(name) if not first: first = subnode return first def AddString(node, prop, value): """Add a new string property to affected device trees Args: prop_name: Name of property value: String value (which will be \0-terminated in the DT) """ for n in GetUpdateNodes(node): n.AddString(prop, value) def SetInt(node, prop, value, for_repack=False): """Update an integer property in affected device trees with an integer value This is not allowed to change the size of the FDT. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): tout.Detail("File %s: Update node '%s' prop '%s' to %#x" % (n.GetFdt().name, n.path, prop, value)) n.SetInt(prop, value) def CheckAddHashProp(node): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo') if not algo: return "Missing 'algo' property for hash node" if algo.value == 'sha256': size = 32 else: return "Unknown hash algorithm '%s'" % algo for n in GetUpdateNodes(hash_node): n.AddEmptyProp('value', size) def CheckSetHashValue(node, get_data_func): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo').value if algo == 'sha256': m = hashlib.sha256() m.update(get_data_func()) data = m.digest() for n in GetUpdateNodes(hash_node): n.SetData('value', data) def SetAllowEntryExpansion(allow): """Set whether post-pack expansion of entries is allowed Args: allow: True to allow expansion, False to raise an exception """ global allow_entry_expansion allow_entry_expansion = allow def AllowEntryExpansion(): """Check whether post-pack expansion of entries is allowed Returns: True if expansion should be allowed, False if an exception should be raised """ return allow_entry_expansion def SetAllowEntryContraction(allow): """Set whether post-pack contraction of entries is allowed Args: allow: True to allow contraction, False to raise an exception """ global allow_entry_contraction allow_entry_contraction = allow def AllowEntryContraction(): """Check whether post-pack contraction of entries is allowed Returns: True if contraction should be allowed, False if an exception should be raised """ return allow_entry_contraction
PrepareFromLoadedData
identifier_name
delete_course.py
from __future__ import print_function from six import text_type from django.core.management.base import BaseCommand, CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from contentstore.utils import delete_course from xmodule.contentstore.django import contentstore from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from .prompt import query_yes_no class Command(BaseCommand):
""" Delete a MongoDB backed course Example usage: $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --keep-instructors --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --remove-assets --settings=devstack Note: The keep-instructors option is useful for resolving issues that arise when a course run's ID is duplicated in a case-insensitive manner. MongoDB is case-sensitive, but MySQL is case-insensitive. This results in course-v1:edX+DemoX+1t2017 being treated differently in MongoDB from course-v1:edX+DemoX+1T2017 (capital 'T'). If you need to remove a duplicate that has resulted from casing issues, use the --keep-instructors flag to ensure that permissions for the remaining course run are not deleted. Use the remove-assets option to ensure all assets are deleted. This is especially relevant to users of the split Mongo modulestore. """ help = 'Delete a MongoDB backed course' def add_arguments(self, parser): parser.add_argument( 'course_key', help='ID of the course to delete.', ) parser.add_argument( '--keep-instructors', action='store_true', default=False, help='Do not remove permissions of users and groups for course', ) parser.add_argument( '--remove-assets', action='store_true', help='Remove all assets associated with the course. ' 'Be careful! These assets may be associated with another course', ) def handle(self, *args, **options): try: # a course key may have unicode chars in it try: course_key = text_type(options['course_key'], 'utf8') # May already be decoded to unicode if coming in through tests, this is ok. except TypeError: course_key = text_type(options['course_key']) course_key = CourseKey.from_string(course_key) except InvalidKeyError: raise CommandError(u'Invalid course_key: {}'.format(options['course_key'])) if not modulestore().get_course(course_key): raise CommandError(u'Course not found: {}'.format(options['course_key'])) print(u'Preparing to delete course %s from module store....' % options['course_key']) if query_yes_no(u'Are you sure you want to delete course {}?'.format(course_key), default='no'): if query_yes_no(u'Are you sure? This action cannot be undone!', default='no'): delete_course(course_key, ModuleStoreEnum.UserID.mgmt_command, options['keep_instructors']) if options['remove_assets']: contentstore().delete_all_course_assets(course_key) print(u'Deleted assets for course'.format(course_key)) print(u'Deleted course {}'.format(course_key))
identifier_body
delete_course.py
from __future__ import print_function from six import text_type from django.core.management.base import BaseCommand, CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey
from .prompt import query_yes_no class Command(BaseCommand): """ Delete a MongoDB backed course Example usage: $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --keep-instructors --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --remove-assets --settings=devstack Note: The keep-instructors option is useful for resolving issues that arise when a course run's ID is duplicated in a case-insensitive manner. MongoDB is case-sensitive, but MySQL is case-insensitive. This results in course-v1:edX+DemoX+1t2017 being treated differently in MongoDB from course-v1:edX+DemoX+1T2017 (capital 'T'). If you need to remove a duplicate that has resulted from casing issues, use the --keep-instructors flag to ensure that permissions for the remaining course run are not deleted. Use the remove-assets option to ensure all assets are deleted. This is especially relevant to users of the split Mongo modulestore. """ help = 'Delete a MongoDB backed course' def add_arguments(self, parser): parser.add_argument( 'course_key', help='ID of the course to delete.', ) parser.add_argument( '--keep-instructors', action='store_true', default=False, help='Do not remove permissions of users and groups for course', ) parser.add_argument( '--remove-assets', action='store_true', help='Remove all assets associated with the course. ' 'Be careful! These assets may be associated with another course', ) def handle(self, *args, **options): try: # a course key may have unicode chars in it try: course_key = text_type(options['course_key'], 'utf8') # May already be decoded to unicode if coming in through tests, this is ok. except TypeError: course_key = text_type(options['course_key']) course_key = CourseKey.from_string(course_key) except InvalidKeyError: raise CommandError(u'Invalid course_key: {}'.format(options['course_key'])) if not modulestore().get_course(course_key): raise CommandError(u'Course not found: {}'.format(options['course_key'])) print(u'Preparing to delete course %s from module store....' % options['course_key']) if query_yes_no(u'Are you sure you want to delete course {}?'.format(course_key), default='no'): if query_yes_no(u'Are you sure? This action cannot be undone!', default='no'): delete_course(course_key, ModuleStoreEnum.UserID.mgmt_command, options['keep_instructors']) if options['remove_assets']: contentstore().delete_all_course_assets(course_key) print(u'Deleted assets for course'.format(course_key)) print(u'Deleted course {}'.format(course_key))
from contentstore.utils import delete_course from xmodule.contentstore.django import contentstore from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore
random_line_split
delete_course.py
from __future__ import print_function from six import text_type from django.core.management.base import BaseCommand, CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from contentstore.utils import delete_course from xmodule.contentstore.django import contentstore from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from .prompt import query_yes_no class Command(BaseCommand): """ Delete a MongoDB backed course Example usage: $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --keep-instructors --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --remove-assets --settings=devstack Note: The keep-instructors option is useful for resolving issues that arise when a course run's ID is duplicated in a case-insensitive manner. MongoDB is case-sensitive, but MySQL is case-insensitive. This results in course-v1:edX+DemoX+1t2017 being treated differently in MongoDB from course-v1:edX+DemoX+1T2017 (capital 'T'). If you need to remove a duplicate that has resulted from casing issues, use the --keep-instructors flag to ensure that permissions for the remaining course run are not deleted. Use the remove-assets option to ensure all assets are deleted. This is especially relevant to users of the split Mongo modulestore. """ help = 'Delete a MongoDB backed course' def add_arguments(self, parser): parser.add_argument( 'course_key', help='ID of the course to delete.', ) parser.add_argument( '--keep-instructors', action='store_true', default=False, help='Do not remove permissions of users and groups for course', ) parser.add_argument( '--remove-assets', action='store_true', help='Remove all assets associated with the course. ' 'Be careful! These assets may be associated with another course', ) def
(self, *args, **options): try: # a course key may have unicode chars in it try: course_key = text_type(options['course_key'], 'utf8') # May already be decoded to unicode if coming in through tests, this is ok. except TypeError: course_key = text_type(options['course_key']) course_key = CourseKey.from_string(course_key) except InvalidKeyError: raise CommandError(u'Invalid course_key: {}'.format(options['course_key'])) if not modulestore().get_course(course_key): raise CommandError(u'Course not found: {}'.format(options['course_key'])) print(u'Preparing to delete course %s from module store....' % options['course_key']) if query_yes_no(u'Are you sure you want to delete course {}?'.format(course_key), default='no'): if query_yes_no(u'Are you sure? This action cannot be undone!', default='no'): delete_course(course_key, ModuleStoreEnum.UserID.mgmt_command, options['keep_instructors']) if options['remove_assets']: contentstore().delete_all_course_assets(course_key) print(u'Deleted assets for course'.format(course_key)) print(u'Deleted course {}'.format(course_key))
handle
identifier_name
delete_course.py
from __future__ import print_function from six import text_type from django.core.management.base import BaseCommand, CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from contentstore.utils import delete_course from xmodule.contentstore.django import contentstore from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from .prompt import query_yes_no class Command(BaseCommand): """ Delete a MongoDB backed course Example usage: $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --keep-instructors --settings=devstack $ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --remove-assets --settings=devstack Note: The keep-instructors option is useful for resolving issues that arise when a course run's ID is duplicated in a case-insensitive manner. MongoDB is case-sensitive, but MySQL is case-insensitive. This results in course-v1:edX+DemoX+1t2017 being treated differently in MongoDB from course-v1:edX+DemoX+1T2017 (capital 'T'). If you need to remove a duplicate that has resulted from casing issues, use the --keep-instructors flag to ensure that permissions for the remaining course run are not deleted. Use the remove-assets option to ensure all assets are deleted. This is especially relevant to users of the split Mongo modulestore. """ help = 'Delete a MongoDB backed course' def add_arguments(self, parser): parser.add_argument( 'course_key', help='ID of the course to delete.', ) parser.add_argument( '--keep-instructors', action='store_true', default=False, help='Do not remove permissions of users and groups for course', ) parser.add_argument( '--remove-assets', action='store_true', help='Remove all assets associated with the course. ' 'Be careful! These assets may be associated with another course', ) def handle(self, *args, **options): try: # a course key may have unicode chars in it try: course_key = text_type(options['course_key'], 'utf8') # May already be decoded to unicode if coming in through tests, this is ok. except TypeError: course_key = text_type(options['course_key']) course_key = CourseKey.from_string(course_key) except InvalidKeyError: raise CommandError(u'Invalid course_key: {}'.format(options['course_key'])) if not modulestore().get_course(course_key): raise CommandError(u'Course not found: {}'.format(options['course_key'])) print(u'Preparing to delete course %s from module store....' % options['course_key']) if query_yes_no(u'Are you sure you want to delete course {}?'.format(course_key), default='no'): if query_yes_no(u'Are you sure? This action cannot be undone!', default='no'): delete_course(course_key, ModuleStoreEnum.UserID.mgmt_command, options['keep_instructors']) if options['remove_assets']:
print(u'Deleted course {}'.format(course_key))
contentstore().delete_all_course_assets(course_key) print(u'Deleted assets for course'.format(course_key))
conditional_block
unsized5.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test `?Sized` types not allowed in fields (except the last one). struct S1<X: ?Sized> { f1: X, //~ ERROR `core::marker::Sized` is not implemented f2: isize, } struct S2<X: ?Sized> { f: isize, g: X, //~ ERROR `core::marker::Sized` is not implemented h: isize, } struct S3 { f: str, //~ ERROR `core::marker::Sized` is not implemented g: [usize] } struct S4 { f: str, //~ ERROR `core::marker::Sized` is not implemented g: usize } enum E<X: ?Sized> { V1(X, isize), //~ERROR `core::marker::Sized` is not implemented } enum F<X: ?Sized> { V2{f1: X, f: isize}, //~ERROR `core::marker::Sized` is not implemented } pub fn main()
{ }
identifier_body
unsized5.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test `?Sized` types not allowed in fields (except the last one). struct S1<X: ?Sized> { f1: X, //~ ERROR `core::marker::Sized` is not implemented f2: isize, } struct S2<X: ?Sized> { f: isize, g: X, //~ ERROR `core::marker::Sized` is not implemented h: isize, } struct S3 { f: str, //~ ERROR `core::marker::Sized` is not implemented g: [usize]
struct S4 { f: str, //~ ERROR `core::marker::Sized` is not implemented g: usize } enum E<X: ?Sized> { V1(X, isize), //~ERROR `core::marker::Sized` is not implemented } enum F<X: ?Sized> { V2{f1: X, f: isize}, //~ERROR `core::marker::Sized` is not implemented } pub fn main() { }
}
random_line_split
unsized5.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test `?Sized` types not allowed in fields (except the last one). struct S1<X: ?Sized> { f1: X, //~ ERROR `core::marker::Sized` is not implemented f2: isize, } struct
<X: ?Sized> { f: isize, g: X, //~ ERROR `core::marker::Sized` is not implemented h: isize, } struct S3 { f: str, //~ ERROR `core::marker::Sized` is not implemented g: [usize] } struct S4 { f: str, //~ ERROR `core::marker::Sized` is not implemented g: usize } enum E<X: ?Sized> { V1(X, isize), //~ERROR `core::marker::Sized` is not implemented } enum F<X: ?Sized> { V2{f1: X, f: isize}, //~ERROR `core::marker::Sized` is not implemented } pub fn main() { }
S2
identifier_name
mmio.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. use zinc64_core::{AddressableFaded, Chip, Ram, Shared}; pub struct Mmio { cia_1: Shared<dyn Chip>, cia_2: Shared<dyn Chip>,
} impl Mmio { pub fn new( cia_1: Shared<dyn Chip>, cia_2: Shared<dyn Chip>, color_ram: Shared<Ram>, expansion_port: Shared<dyn AddressableFaded>, sid: Shared<dyn Chip>, vic: Shared<dyn Chip>, ) -> Self { Self { cia_1, cia_2, color_ram, expansion_port, sid, vic, } } pub fn read(&self, address: u16) -> u8 { match address { 0xd000..=0xd3ff => self.vic.borrow_mut().read((address & 0x003f) as u8), 0xd400..=0xd7ff => self.sid.borrow_mut().read((address & 0x001f) as u8), 0xd800..=0xdbff => self.color_ram.borrow().read(address - 0xd800), 0xdc00..=0xdcff => self.cia_1.borrow_mut().read((address & 0x000f) as u8), 0xdd00..=0xddff => self.cia_2.borrow_mut().read((address & 0x000f) as u8), 0xde00..=0xdfff => self.expansion_port.borrow_mut().read(address).unwrap_or(0), _ => panic!("invalid address 0x{:x}", address), } } pub fn write(&mut self, address: u16, value: u8) { match address { 0xd000..=0xd3ff => self.vic.borrow_mut().write((address & 0x003f) as u8, value), 0xd400..=0xd7ff => self.sid.borrow_mut().write((address & 0x001f) as u8, value), 0xd800..=0xdbff => self.color_ram.borrow_mut().write(address - 0xd800, value), 0xdc00..=0xdcff => self .cia_1 .borrow_mut() .write((address & 0x000f) as u8, value), 0xdd00..=0xddff => self .cia_2 .borrow_mut() .write((address & 0x000f) as u8, value), 0xde00..=0xdfff => self.expansion_port.borrow_mut().write(address, value), _ => panic!("invalid address 0x{:x}", address), } } }
color_ram: Shared<Ram>, expansion_port: Shared<dyn AddressableFaded>, sid: Shared<dyn Chip>, vic: Shared<dyn Chip>,
random_line_split
mmio.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. use zinc64_core::{AddressableFaded, Chip, Ram, Shared}; pub struct Mmio { cia_1: Shared<dyn Chip>, cia_2: Shared<dyn Chip>, color_ram: Shared<Ram>, expansion_port: Shared<dyn AddressableFaded>, sid: Shared<dyn Chip>, vic: Shared<dyn Chip>, } impl Mmio { pub fn new( cia_1: Shared<dyn Chip>, cia_2: Shared<dyn Chip>, color_ram: Shared<Ram>, expansion_port: Shared<dyn AddressableFaded>, sid: Shared<dyn Chip>, vic: Shared<dyn Chip>, ) -> Self { Self { cia_1, cia_2, color_ram, expansion_port, sid, vic, } } pub fn
(&self, address: u16) -> u8 { match address { 0xd000..=0xd3ff => self.vic.borrow_mut().read((address & 0x003f) as u8), 0xd400..=0xd7ff => self.sid.borrow_mut().read((address & 0x001f) as u8), 0xd800..=0xdbff => self.color_ram.borrow().read(address - 0xd800), 0xdc00..=0xdcff => self.cia_1.borrow_mut().read((address & 0x000f) as u8), 0xdd00..=0xddff => self.cia_2.borrow_mut().read((address & 0x000f) as u8), 0xde00..=0xdfff => self.expansion_port.borrow_mut().read(address).unwrap_or(0), _ => panic!("invalid address 0x{:x}", address), } } pub fn write(&mut self, address: u16, value: u8) { match address { 0xd000..=0xd3ff => self.vic.borrow_mut().write((address & 0x003f) as u8, value), 0xd400..=0xd7ff => self.sid.borrow_mut().write((address & 0x001f) as u8, value), 0xd800..=0xdbff => self.color_ram.borrow_mut().write(address - 0xd800, value), 0xdc00..=0xdcff => self .cia_1 .borrow_mut() .write((address & 0x000f) as u8, value), 0xdd00..=0xddff => self .cia_2 .borrow_mut() .write((address & 0x000f) as u8, value), 0xde00..=0xdfff => self.expansion_port.borrow_mut().write(address, value), _ => panic!("invalid address 0x{:x}", address), } } }
read
identifier_name
custom_utils.py
############################################################################### ## Imports ############################################################################### # Django from django import template from django.forms.forms import BoundField ############################################################################### ## Filters ############################################################################### register = template.Library() class NamelessField(BoundField): def __init__(self, field): self.__dict__ = field.__dict__ def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be used. """ if not widget: widget = self.field.widget attrs = attrs or {} auto_id = self.auto_id if auto_id and 'id' not in attrs and 'id' not in widget.attrs: if not only_initial: attrs['id'] = auto_id else: attrs['id'] = self.html_initial_id
return widget.render(name, self.value(), attrs=attrs) @register.filter(name='namelessfield') def namelessfield(field): return NamelessField(field)
name = ""
random_line_split
custom_utils.py
############################################################################### ## Imports ############################################################################### # Django from django import template from django.forms.forms import BoundField ############################################################################### ## Filters ############################################################################### register = template.Library() class NamelessField(BoundField): def __init__(self, field): self.__dict__ = field.__dict__ def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be used. """ if not widget: widget = self.field.widget attrs = attrs or {} auto_id = self.auto_id if auto_id and 'id' not in attrs and 'id' not in widget.attrs: if not only_initial: attrs['id'] = auto_id else: attrs['id'] = self.html_initial_id name = "" return widget.render(name, self.value(), attrs=attrs) @register.filter(name='namelessfield') def
(field): return NamelessField(field)
namelessfield
identifier_name
custom_utils.py
############################################################################### ## Imports ############################################################################### # Django from django import template from django.forms.forms import BoundField ############################################################################### ## Filters ############################################################################### register = template.Library() class NamelessField(BoundField): def __init__(self, field): self.__dict__ = field.__dict__ def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be used. """ if not widget: widget = self.field.widget attrs = attrs or {} auto_id = self.auto_id if auto_id and 'id' not in attrs and 'id' not in widget.attrs: if not only_initial: attrs['id'] = auto_id else: attrs['id'] = self.html_initial_id name = "" return widget.render(name, self.value(), attrs=attrs) @register.filter(name='namelessfield') def namelessfield(field):
return NamelessField(field)
identifier_body
custom_utils.py
############################################################################### ## Imports ############################################################################### # Django from django import template from django.forms.forms import BoundField ############################################################################### ## Filters ############################################################################### register = template.Library() class NamelessField(BoundField): def __init__(self, field): self.__dict__ = field.__dict__ def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be used. """ if not widget: widget = self.field.widget attrs = attrs or {} auto_id = self.auto_id if auto_id and 'id' not in attrs and 'id' not in widget.attrs: if not only_initial:
else: attrs['id'] = self.html_initial_id name = "" return widget.render(name, self.value(), attrs=attrs) @register.filter(name='namelessfield') def namelessfield(field): return NamelessField(field)
attrs['id'] = auto_id
conditional_block