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
search.py
# Copyright 2013 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 ...
def _post_index_course(handler): """Submits a new indexing operation.""" try: check_job_and_submit(handler.app_context, incremental=False) except db.TransactionFailedError: # Double submission from multiple browsers, just pass pass handler.redirect('/dashboard?action=settings_s...
"""Renders course indexing view.""" template_values = {'page_title': handler.format_title('Search')} mc_template_value = {} mc_template_value['module_enabled'] = custom_module.enabled indexing_job = IndexCourse(handler.app_context).load() if indexing_job: if indexing_job.status_code in [jobs...
identifier_body
plat_win.py
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at
from ctypes.wintypes import HWND, UINT, LPCWSTR, BOOL import os.path as op from .compat import text_type shell32 = windll.shell32 SHFileOperationW = shell32.SHFileOperationW class SHFILEOPSTRUCTW(Structure): _fields_ = [ ("hwnd", HWND), ("wFunc", UINT), ("pFrom", LPCWSTR), ("pTo",...
# http://www.hardcoded.net/licenses/bsd_license from __future__ import unicode_literals from ctypes import windll, Structure, byref, c_uint
random_line_split
plat_win.py
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from __future__ import unicode_literals...
if not isinstance(path, text_type): path = text_type(path, 'mbcs') if not op.isabs(path): path = op.abspath(path) fileop = SHFILEOPSTRUCTW() fileop.hwnd = 0 fileop.wFunc = FO_DELETE fileop.pFrom = LPCWSTR(path + '\0') fileop.pTo = None fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCO...
identifier_body
plat_win.py
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from __future__ import unicode_literals...
if not op.isabs(path): path = op.abspath(path) fileop = SHFILEOPSTRUCTW() fileop.hwnd = 0 fileop.wFunc = FO_DELETE fileop.pFrom = LPCWSTR(path + '\0') fileop.pTo = None fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT fileop.fAnyOperationsAborted =...
path = text_type(path, 'mbcs')
conditional_block
plat_win.py
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from __future__ import unicode_literals...
(Structure): _fields_ = [ ("hwnd", HWND), ("wFunc", UINT), ("pFrom", LPCWSTR), ("pTo", LPCWSTR), ("fFlags", c_uint), ("fAnyOperationsAborted", BOOL), ("hNameMappings", c_uint), ("lpszProgressTitle", LPCWSTR), ] FO_MOVE = 1 FO_COPY = 2 FO_DELET...
SHFILEOPSTRUCTW
identifier_name
revealer.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! Hide and show with animation use ffi; use cast::{GTK_REVEALER}; use glib::{to_bool, ...
pub fn get_transition_duration(&self) -> u32 { unsafe { ffi::gtk_revealer_get_transition_duration(GTK_REVEALER(self.pointer)) } } pub fn set_transition_duration(&self, duration: u32) { unsafe { ffi::gtk_revealer_set_transition_duration(GTK_REVEALER(self.point...
unsafe { to_bool(ffi::gtk_revealer_get_child_revealed(GTK_REVEALER(self.pointer))) } }
identifier_body
revealer.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! Hide and show with animation use ffi; use cast::{GTK_REVEALER}; use glib::{to_bool, ...
impl ::ContainerTrait for Revealer {} impl ::BinTrait for Revealer {}
impl_drop!(Revealer); impl_TraitWidget!(Revealer);
random_line_split
revealer.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! Hide and show with animation use ffi; use cast::{GTK_REVEALER}; use glib::{to_bool, ...
self, duration: u32) { unsafe { ffi::gtk_revealer_set_transition_duration(GTK_REVEALER(self.pointer), duration) } } pub fn set_transition_type(&self, transition: ::RevealerTransitionType) { unsafe { ffi::gtk_revealer_set_transition_type(GTK_REVEALER(self.pointer)...
t_transition_duration(&
identifier_name
recent_commits_test.py
# coding: utf-8 # # Copyright 2018 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
'public', True) commit3 = exp_models.ExplorationCommitLogEntryModel.create( 'entity_2', 0, self.committer_1_id, 'create', 'created second commit', [], 'private', False) commit1.exploration_id = 'exp_1' commit2.exploration_id = 'exp_1' commit3.explorati...
random_line_split
recent_commits_test.py
# coding: utf-8 # # Copyright 2018 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
"""Test the RecentCommitsHandler class.""" def setUp(self): super(RecentCommitsHandlerUnitTests, self).setUp() self.signup(self.MODERATOR_EMAIL, self.MODERATOR_USERNAME) self.set_moderators([self.MODERATOR_USERNAME]) self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) self...
identifier_body
recent_commits_test.py
# coding: utf-8 # # Copyright 2018 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
(test_utils.GenericTestBase): """Test the RecentCommitsHandler class.""" def setUp(self): super(RecentCommitsHandlerUnitTests, self).setUp() self.signup(self.MODERATOR_EMAIL, self.MODERATOR_USERNAME) self.set_moderators([self.MODERATOR_USERNAME]) self.signup(self.VIEWER_EMAIL, ...
RecentCommitsHandlerUnitTests
identifier_name
recent_commits_test.py
# coding: utf-8 # # Copyright 2018 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
response_dict = self.get_json( feconf.RECENT_COMMITS_DATA_URL, params={'query_type': 'all_non_private_commits'}) self.assertEqual( len(response_dict['results']), feconf.COMMIT_LIST_PAGE_SIZE) self.assertTrue(response_dict['more']) cursor = response_...
entity_id = 'my_entity_%s' % i exp_id = 'exp_%s' % i commit_i = exp_models.ExplorationCommitLogEntryModel.create( entity_id, 0, self.committer_2_id, 'create', 'created commit', [], 'public', True) commit_i.exploration_id = exp_id commit_i....
conditional_block
test_uptime.py
import unittest try: from unittest import mock except ImportError: import mock from pi3bar.plugins.uptime import get_uptime_seconds, uptime_format, Uptime class GetUptimeSecondsTestCase(unittest.TestCase): def test(self): m = mock.mock_open(read_data='5') m.return_value.readline.return_val...
def test_format_days_applied_to_hours(self): s = uptime_format(135420, '%H:%M:%S') self.assertEqual('37:37:00', s) def test_format_hours_applied_to_minutes(self): s = uptime_format(49020, '%M:%S') self.assertEqual('817:00', s) class UptimeTestCase(unittest.TestCase): def...
s = uptime_format(135420) self.assertEqual('1:13:37:00', s)
identifier_body
test_uptime.py
import unittest try: from unittest import mock except ImportError: import mock from pi3bar.plugins.uptime import get_uptime_seconds, uptime_format, Uptime class GetUptimeSecondsTestCase(unittest.TestCase): def test(self): m = mock.mock_open(read_data='5') m.return_value.readline.return_val...
(unittest.TestCase): def test_seconds(self): s = uptime_format(5) self.assertEqual('0:00:00:05', s) def test_minutes(self): s = uptime_format(3540) self.assertEqual('0:00:59:00', s) def test_hours(self): s = uptime_format(49020) self.assertEqual('0:13:37:00'...
UptimeFormatTestCase
identifier_name
test_uptime.py
import unittest try: from unittest import mock except ImportError: import mock from pi3bar.plugins.uptime import get_uptime_seconds, uptime_format, Uptime class GetUptimeSecondsTestCase(unittest.TestCase): def test(self): m = mock.mock_open(read_data='5')
class UptimeFormatTestCase(unittest.TestCase): def test_seconds(self): s = uptime_format(5) self.assertEqual('0:00:00:05', s) def test_minutes(self): s = uptime_format(3540) self.assertEqual('0:00:59:00', s) def test_hours(self): s = uptime_format(49020) s...
m.return_value.readline.return_value = '5' # py33 with mock.patch('pi3bar.plugins.uptime.open', m, create=True): seconds = get_uptime_seconds() self.assertEqual(5, seconds)
random_line_split
minesweeperNN.js
// ==UserScript== // @name mineAI // @namespace minesAI // @include http://minesweeperonline.com/#beginner-night // @version 1 // @required http://localhost:8000/convnetjs.js // @grant none // ==/UserScript== // Load the library. var D = document; var appTarg = D.getElementsByTa...
// Call the library's start-up function, if any. Note needed use of unsafeWindow. function initConvNetJs () { // species a 2-layer neural network with one hidden layer of 20 neurons var layer_defs = []; // ConvNetJS works on 3-Dimensional volumes (sx, sy, depth), but if you're not dealing with ima...
{ setTimeout (initConvNetJs, 666); }
identifier_body
minesweeperNN.js
// ==UserScript== // @name mineAI // @namespace minesAI // @include http://minesweeperonline.com/#beginner-night // @version 1 // @required http://localhost:8000/convnetjs.js // @grant none // ==/UserScript== // Load the library. var D = document; var appTarg = D.getElementsByTa...
// learned probability var prob00 = net.forward(t1); var prob01 = net.forward(t2); var prob10 = net.forward(t3); var prob11 = net.forward(t4); // log probability console.log('p(0 | 00): ' + prob00.w[0] + ", p(1 | 00): " + prob00.w[1]); console.log('p(0 | 01): ' + prob01.w[0] + ", p(1 ...
{ trainer.train(t1, 0); trainer.train(t2, 1); trainer.train(t3, 1); trainer.train(t4, 0); }
conditional_block
minesweeperNN.js
// ==UserScript== // @name mineAI // @namespace minesAI // @include http://minesweeperonline.com/#beginner-night // @version 1 // @required http://localhost:8000/convnetjs.js // @grant none // ==/UserScript== // Load the library. var D = document; var appTarg = D.getElementsByTa...
() { // species a 2-layer neural network with one hidden layer of 20 neurons var layer_defs = []; // ConvNetJS works on 3-Dimensional volumes (sx, sy, depth), but if you're not dealing with images // then the first two dimensions (sx, sy) will always be kept at size 1 layer_defs.push({type:...
initConvNetJs
identifier_name
minesweeperNN.js
// ==UserScript== // @name mineAI // @namespace minesAI // @include http://minesweeperonline.com/#beginner-night // @version 1 // @required http://localhost:8000/convnetjs.js // @grant none // ==/UserScript== // Load the library. var D = document; var appTarg = D.getElementsByTa...
// species a 2-layer neural network with one hidden layer of 20 neurons var layer_defs = []; // ConvNetJS works on 3-Dimensional volumes (sx, sy, depth), but if you're not dealing with images // then the first two dimensions (sx, sy) will always be kept at size 1 layer_defs.push({type:'input', ou...
} // Call the library's start-up function, if any. Note needed use of unsafeWindow. function initConvNetJs () {
random_line_split
state.directive.ts
import {Directive, ElementRef, Renderer, Input, OnChanges} from '@angular/core'; @Directive({ selector: '[state]' }) export class StateDirective implements OnChanges {
constructor(renderer: Renderer, el: ElementRef) { this.element = el; this.renderer = renderer; } ngOnChanges() { let cssClass = `state-${this.itemState}`; let text = 'A livrer'; let elementNode = this.element.nativeElement; switch (this.itemState) { ...
@Input('state') itemState: any; private element: ElementRef; private renderer: Renderer;
random_line_split
state.directive.ts
import {Directive, ElementRef, Renderer, Input, OnChanges} from '@angular/core'; @Directive({ selector: '[state]' }) export class StateDirective implements OnChanges { @Input('state') itemState: any; private element: ElementRef; private renderer: Renderer; constructor(renderer: Renderer, el: Ele...
ngOnChanges() { let cssClass = `state-${this.itemState}`; let text = 'A livrer'; let elementNode = this.element.nativeElement; switch (this.itemState) { case 1 : text = "aaaaa"; break; case 2 : text = "xxxxx"; ...
{ this.element = el; this.renderer = renderer; }
identifier_body
state.directive.ts
import {Directive, ElementRef, Renderer, Input, OnChanges} from '@angular/core'; @Directive({ selector: '[state]' }) export class
implements OnChanges { @Input('state') itemState: any; private element: ElementRef; private renderer: Renderer; constructor(renderer: Renderer, el: ElementRef) { this.element = el; this.renderer = renderer; } ngOnChanges() { let cssClass = `state-${this.itemState}`; ...
StateDirective
identifier_name
vsoFormatterTests.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable l...
});
{ return `##vso[task.logissue type=warning;sourcepath=${file};linenumber=${line};columnnumber=${character};code=${code};]${reason}\n`; }
identifier_body
vsoFormatterTests.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable l...
(file: string, line: number, character: number, reason: string, code: string) { return `##vso[task.logissue type=warning;sourcepath=${file};linenumber=${line};columnnumber=${character};code=${code};]${reason}\n`; } });
getFailureString
identifier_name
vsoFormatterTests.ts
/* * Copyright 2013 Palantir Technologies, Inc. *
* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed ...
random_line_split
mainStaticPersonTask.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: # Purpose: This .py file is the main Framework file # It ranks images of a specific person of interest in a static manner # # Required libs: python-dateutil, numpy...
selection = int(input('Select a dataset from the above: '))-1 dataset_path_results = "./data/"+filename[selection][:-4]+"/staticPersonCentered_"+commDetectMethod[0]+"/results/" dataset_path_tmp = "./data/"+filename[selection][:-4]+"/staticPersonCentered_"+commDetectMethod[0]+"/tmp/" datasetFilename = './data/txt/'+fi...
random_line_split
mainStaticPersonTask.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: # Purpose: This .py file is the main Framework file # It ranks images of a specific person of interest in a static manner # # Required libs: python-dateutil, numpy...
if dataextract==1 or dataextract==2:#If the basic data (authors, mentions, time) has been created data = pickle.load(open(dataset_path_tmp + "allPersondata.pck", "rb")) captiondict = data.captiondict print('static Community detection method selected is :'+commDetectMethod[0]) dataStatic=data.extraction...
data = communitystatic.from_txt(datasetFilename,dataset_path_results,dataset_path_tmp,timeLimit=timeLimit) dataPck = open(dataset_path_tmp + "allPersondata.pck", "wb") pickle.dump(data, dataPck , protocol = 2) dataPck.close() del(data) elapsed = time.time() - t print('Stage 1: %.2f seconds' % el...
conditional_block
test_instructor_dashboard.py
""" End to end tests for Instructor Dashboard. """ from bok_choy.web_app_test import WebAppTest from regression.pages.lms.course_page_lms import CourseHomePageExtended from regression.pages.lms.dashboard_lms import DashboardPageExtended from regression.pages.lms.instructor_dashboard import InstructorDashboardPageExte...
""" Regression tests on Analytics on Instructor Dashboard """ def setUp(self): super().setUp() login_api = LmsLoginApi() login_api.authenticate(self.browser) course_info = get_course_info() self.dashboard_page = DashboardPageExtended(self.browser) self....
class AnalyticsTest(WebAppTest):
random_line_split
test_instructor_dashboard.py
""" End to end tests for Instructor Dashboard. """ from bok_choy.web_app_test import WebAppTest from regression.pages.lms.course_page_lms import CourseHomePageExtended from regression.pages.lms.dashboard_lms import DashboardPageExtended from regression.pages.lms.instructor_dashboard import InstructorDashboardPageExte...
""" Regression tests on Analytics on Instructor Dashboard """ def setUp(self): super().setUp() login_api = LmsLoginApi() login_api.authenticate(self.browser) course_info = get_course_info() self.dashboard_page = DashboardPageExtended(self.browser) self.inst...
identifier_body
test_instructor_dashboard.py
""" End to end tests for Instructor Dashboard. """ from bok_choy.web_app_test import WebAppTest from regression.pages.lms.course_page_lms import CourseHomePageExtended from regression.pages.lms.dashboard_lms import DashboardPageExtended from regression.pages.lms.instructor_dashboard import InstructorDashboardPageExte...
(self): super().setUp() login_api = LmsLoginApi() login_api.authenticate(self.browser) course_info = get_course_info() self.dashboard_page = DashboardPageExtended(self.browser) self.instructor_dashboard = InstructorDashboardPageExtended( self.browser, ...
setUp
identifier_name
reportcommon.py
#!/usr/local/munkireport/munkireport-python2 # encoding: utf-8 from . import display from . import prefs from . import constants from . import FoundationPlist from munkilib.purl import Purl from munkilib.phpserialize import * import subprocess import pwd import sys import hashlib import platform from urllib import ur...
def finish_run(): remove_run_file() display_detail("## Finished run") exit(0) def remove_run_file(): touchfile = '/Users/Shared/.com.github.munkireport.run' if os.path.exists(touchfile): os.remove(touchfile) def curl(url, values): options = dict() options["url"] = url o...
"""Call display detail msg handler.""" display.display_detail("%s" % msg, *args)
identifier_body
reportcommon.py
#!/usr/local/munkireport/munkireport-python2 # encoding: utf-8 from . import display from . import prefs from . import constants from . import FoundationPlist from munkilib.purl import Purl from munkilib.phpserialize import * import subprocess import pwd import sys import hashlib import platform from urllib import ur...
if not os.path.exists(script): raise ScriptNotFoundError("script does not exist: %s" % script) if not allow_insecure: try: utils.verifyFileOnlyWritableByMunkiAndRoot(script) except utils.VerifyFilePermissionsError, e: msg = ( "Skipping execution d...
RunExternalScriptError: there was an error running the script. """ from munkilib import utils
random_line_split
reportcommon.py
#!/usr/local/munkireport/munkireport-python2 # encoding: utf-8 from . import display from . import prefs from . import constants from . import FoundationPlist from munkilib.purl import Purl from munkilib.phpserialize import * import subprocess import pwd import sys import hashlib import platform from urllib import ur...
( script, allow_insecure=False, script_args=(), timeout=30 ): """Run a script (e.g. preflight/postflight) and return its exit status. Args: script: string path to the script to execute. allow_insecure: bool skip the permissions check of executable. args: args to pass to the script. Re...
runExternalScriptWithTimeout
identifier_name
reportcommon.py
#!/usr/local/munkireport/munkireport-python2 # encoding: utf-8 from . import display from . import prefs from . import constants from . import FoundationPlist from munkilib.purl import Purl from munkilib.phpserialize import * import subprocess import pwd import sys import hashlib import platform from urllib import ur...
fileref.close() return hash_function.hexdigest() def getmd5hash(filename): """Returns hex of MD5 checksum of a file.""" hash_function = hashlib.md5() return gethash(filename, hash_function) def getOsVersion(only_major_minor=True, as_tuple=False): """Returns an OS version. Args: o...
chunk = fileref.read(2 ** 16) if not chunk: break hash_function.update(chunk)
conditional_block
regroup_gradient_stops.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // 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 ...
fn gen_id(doc: &Document, prefix: &str) -> String { let mut n = 1; let mut s = String::new(); loop { s.clear(); s.push_str(prefix); s.push_str(&n.to_string()); // TODO: very slow if !doc.descendants().any(|n| *n.id() == s) { break; } n...
{ let mut nodes: Vec<Node> = doc.descendants() .filter(|n| n.is_gradient()) .filter(|n| n.has_children()) .filter(|n| !n.has_attribute(AId::XlinkHref)) .collect(); let mut is_changed = false; let mut join_nodes = Vec::new(); // TODO: join with rm_dupl_defs::rm_loop ...
identifier_body
regroup_gradient_stops.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // 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 ...
(doc: &mut Document) { let mut nodes: Vec<Node> = doc.descendants() .filter(|n| n.is_gradient()) .filter(|n| n.has_children()) .filter(|n| !n.has_attribute(AId::XlinkHref)) .collect(); let mut is_changed = false; let mut join_nodes = Vec::new(); // TODO: join with rm_du...
regroup_gradient_stops
identifier_name
regroup_gradient_stops.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // 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 ...
n += 1; } s } #[cfg(test)] mod tests { use super::*; use svgdom::{Document, ToStringWithOptions}; use task; macro_rules! test { ($name:ident, $in_text:expr, $out_text:expr) => ( #[test] fn $name() { let mut doc = Document::from_str($in...
{ break; }
conditional_block
regroup_gradient_stops.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // 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 ...
) } test!(rm_1, "<svg> <linearGradient id='lg1' x1='50'> <stop offset='0'/> <stop offset='1'/> </linearGradient> <linearGradient id='lg2' x1='100'> <stop offset='0'/> <stop offset='1'/> </linearGradient> </svg>", "<svg> <linearGradient id='lg3'> ...
regroup_gradient_stops(&mut doc); assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), $out_text); }
random_line_split
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! https://html.spec.whatwg.org/multipage/#the-end use dom::binding...
/// Add a load to the list of blocking loads. fn add_blocking_load(&mut self, load: LoadType) { debug!("Adding blocking load {:?} ({}).", load, self.blocking_loads.len()); self.blocking_loads.push(load); } /// Initiate a new fetch. pub fn fetch_async(&mut self, ...
{ debug!("Initial blocking load {:?}.", initial_load); let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect(); DocumentLoader { resource_threads: resource_threads, blocking_loads: initial_loads, events_inhibited: false, } ...
identifier_body
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! https://html.spec.whatwg.org/multipage/#the-end use dom::binding...
} } #[derive(JSTraceable, HeapSizeOf)] pub struct DocumentLoader { resource_threads: ResourceThreads, blocking_loads: Vec<LoadType>, events_inhibited: bool, } impl DocumentLoader { pub fn new(existing: &DocumentLoader) -> DocumentLoader { DocumentLoader::new_with_threads(existing.resource...
{ debug_assert!(self.load.is_none()); }
conditional_block
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! https://html.spec.whatwg.org/multipage/#the-end use dom::binding...
doc: JS::from_ref(doc), load: Some(load), } } /// Remove this load from the associated document's list of blocking loads. pub fn terminate(blocker: &mut Option<LoadBlocker>) { if let Some(this) = blocker.as_mut() { this.doc.finish_load(this.load.take().un...
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker { doc.mut_loader().add_blocking_load(load.clone()); LoadBlocker {
random_line_split
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! https://html.spec.whatwg.org/multipage/#the-end use dom::binding...
(existing: &DocumentLoader) -> DocumentLoader { DocumentLoader::new_with_threads(existing.resource_threads.clone(), None) } pub fn new_with_threads(resource_threads: ResourceThreads, initial_load: Option<Url>) -> DocumentLoader { debug!("Initial blocking load {:?}.",...
new
identifier_name
test_rowcount.py
from sqlalchemy import * from sqlalchemy.test import * class FoundRowsTest(TestBase, AssertsExecutionResults): """tests rowcount functionality""" __requires__ = ('sane_rowcount', ) @classmethod def
(cls): global employees_table, metadata metadata = MetaData(testing.db) employees_table = Table('employees', metadata, Column('employee_id', Integer, Sequence('employee_id_seq', optional=True), primary_key=True), Column('...
setup_class
identifier_name
test_rowcount.py
from sqlalchemy import * from sqlalchemy.test import * class FoundRowsTest(TestBase, AssertsExecutionResults): """tests rowcount functionality""" __requires__ = ('sane_rowcount', ) @classmethod def setup_class(cls): global employees_table, metadata metadata = MetaData(testing...
def testbasic(self): s = employees_table.select() r = s.execute().fetchall() assert len(r) == len(data) def test_update_rowcount1(self): # WHERE matches 3, 3 rows changed department = employees_table.c.department r = employees_table.update(department=='C').exec...
@classmethod def teardown_class(cls): metadata.drop_all()
random_line_split
test_rowcount.py
from sqlalchemy import * from sqlalchemy.test import * class FoundRowsTest(TestBase, AssertsExecutionResults): """tests rowcount functionality""" __requires__ = ('sane_rowcount', ) @classmethod def setup_class(cls): global employees_table, metadata metadata = MetaData(testing...
def test_update_rowcount2(self): # WHERE matches 3, 0 rows changed department = employees_table.c.department r = employees_table.update(department=='C').execute(department='C') print "expecting 3, dialect reports %s" % r.rowcount assert r.rowcount == 3 def test_delete_...
department = employees_table.c.department r = employees_table.update(department=='C').execute(department='Z') print "expecting 3, dialect reports %s" % r.rowcount assert r.rowcount == 3
identifier_body
lib.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to g...
#[macro_use] extern crate serde_derive; extern crate serde_json; mod generated; mod custom; pub use generated::*; pub use custom::*;
extern crate futures; extern crate rusoto_core; extern crate serde;
random_line_split
common.js
"use strict"; var core_1 = require('@angular/core'); var NgTranscludeDirective = (function () { function NgTranscludeDirective(_viewRef)
Object.defineProperty(NgTranscludeDirective.prototype, "ngTransclude", { get: function () { return this._ngTransclude; }, set: function (templateRef) { this._ngTransclude = templateRef; if (templateRef) { this.viewRef.createEmbeddedView(te...
{ this._viewRef = _viewRef; this.viewRef = _viewRef; }
identifier_body
common.js
"use strict"; var core_1 = require('@angular/core'); var NgTranscludeDirective = (function () { function NgTranscludeDirective(_viewRef) { this._viewRef = _viewRef; this.viewRef = _viewRef; } Object.defineProperty(NgTranscludeDirective.prototype, "ngTransclude", { get: function () { ...
}, enumerable: true, configurable: true }); NgTranscludeDirective.decorators = [ { type: core_1.Directive, args: [{ selector: '[ngTransclude]' },] }, ]; /** @nocollapse */ NgTranscludeDirective.ctorParameters = [ { type: co...
{ this.viewRef.createEmbeddedView(templateRef); }
conditional_block
common.js
"use strict"; var core_1 = require('@angular/core'); var NgTranscludeDirective = (function () { function
(_viewRef) { this._viewRef = _viewRef; this.viewRef = _viewRef; } Object.defineProperty(NgTranscludeDirective.prototype, "ngTransclude", { get: function () { return this._ngTransclude; }, set: function (templateRef) { this._ngTransclude = templateR...
NgTranscludeDirective
identifier_name
common.js
"use strict"; var core_1 = require('@angular/core'); var NgTranscludeDirective = (function () { function NgTranscludeDirective(_viewRef) { this._viewRef = _viewRef; this.viewRef = _viewRef; } Object.defineProperty(NgTranscludeDirective.prototype, "ngTransclude", { get: function () { ...
enumerable: true, configurable: true }); NgTranscludeDirective.decorators = [ { type: core_1.Directive, args: [{ selector: '[ngTransclude]' },] }, ]; /** @nocollapse */ NgTranscludeDirective.ctorParameters = [ { type: core_1.ViewCon...
random_line_split
mod.rs
// Copyright 2017, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. use super::enums::*; use super::RegKey; use std::error::Error; use std::fmt; use std::io; use winapi::shared::...
enumeration_state: DecoderEnumerationState, } const DECODER_SAM: DWORD = KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS; impl Decoder { pub fn from_key(key: &RegKey) -> DecodeResult<Decoder> { key.open_subkey_with_flags("", DECODER_SAM) .map(Decoder::new) .map_err(DecoderError::IoErr...
f_name: Option<String>, reading_state: DecoderReadingState,
random_line_split
mod.rs
// Copyright 2017, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. use super::enums::*; use super::RegKey; use std::error::Error; use std::fmt; use std::io; use winapi::shared::...
(err: io::Error) -> DecoderError { DecoderError::IoError(err) } } pub type DecodeResult<T> = Result<T, DecoderError>; #[derive(Debug)] enum DecoderReadingState { WaitingForKey, WaitingForValue, } #[derive(Debug)] enum DecoderEnumerationState { EnumeratingKeys(DWORD), EnumeratingValues(DWO...
from
identifier_name
util.js
export const ATTR_ID = 'data-referid' export let info = { component: { amount: 0, mounts: 0, unmounts: 0 } } export let getId = () => Math.random().toString(36).substr(2) export let pipe = (fn1, fn2) => function(...args) { fn1.apply(this, args) return fn2.apply(this, args) } export let createCallbackSto...
, push(item) { store.push(item) }, store } } export let wrapNative = (obj, method, fn) => { let nativeMethod = obj[method] let wrapper = function(...args) { fn.apply(this, args) return nativeMethod.apply(this, args) } obj[method] = wrapper return () => obj[method] = nativeMethod } if (!Object.assig...
{ while (store.length) { store.shift()() } }
identifier_body
util.js
export const ATTR_ID = 'data-referid' export let info = { component: { amount: 0, mounts: 0, unmounts: 0 } } export let getId = () => Math.random().toString(36).substr(2) export let pipe = (fn1, fn2) => function(...args) { fn1.apply(this, args) return fn2.apply(this, args) } export let createCallbackSto...
(item) { store.push(item) }, store } } export let wrapNative = (obj, method, fn) => { let nativeMethod = obj[method] let wrapper = function(...args) { fn.apply(this, args) return nativeMethod.apply(this, args) } obj[method] = wrapper return () => obj[method] = nativeMethod } if (!Object.assign) { Ob...
push
identifier_name
util.js
export const ATTR_ID = 'data-referid' export let info = { component: { amount: 0, mounts: 0, unmounts: 0 } } export let getId = () => Math.random().toString(36).substr(2) export let pipe = (fn1, fn2) => function(...args) { fn1.apply(this, args) return fn2.apply(this, args) } export let createCallbackSto...
target[key] = source[key] } }) return target } }
{ continue }
conditional_block
util.js
export const ATTR_ID = 'data-referid' export let info = { component: { amount: 0,
} export let getId = () => Math.random().toString(36).substr(2) export let pipe = (fn1, fn2) => function(...args) { fn1.apply(this, args) return fn2.apply(this, args) } export let createCallbackStore = name => { let store = [] return { name, clear() { while (store.length) { store.shift()() } }, ...
mounts: 0, unmounts: 0 }
random_line_split
sensor.py
"""Bitcoin information service that uses blockchain.info.""" from datetime import timedelta import logging from blockchain import exchangerates, statistics import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_CURRENCY, CONF_DISPLAY...
elif self.type == "estimated_btc_sent": self._state = "{0:.2f}".format(stats.estimated_btc_sent * 0.00000001) elif self.type == "total_btc": self._state = "{0:.2f}".format(stats.total_btc * 0.00000001) elif self.type == "total_blocks": self._state = "{0:.0f}"...
self._state = "{0:.2f}".format(stats.total_btc_sent * 0.00000001)
conditional_block
sensor.py
"""Bitcoin information service that uses blockchain.info.""" from datetime import timedelta import logging from blockchain import exchangerates, statistics import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_CURRENCY, CONF_DISPLAY...
@property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit the value is expressed in."...
"""Initialize the sensor.""" self.data = data self._name = OPTION_TYPES[option_type][0] self._unit_of_measurement = OPTION_TYPES[option_type][1] self._currency = currency self.type = option_type self._state = None
identifier_body
sensor.py
"""Bitcoin information service that uses blockchain.info.""" from datetime import timedelta import logging from blockchain import exchangerates, statistics import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_CURRENCY, CONF_DISPLAY...
elif self.type == "trade_volume_usd": self._state = "{0:.1f}".format(stats.trade_volume_usd) elif self.type == "difficulty": self._state = "{0:.0f}".format(stats.difficulty) elif self.type == "minutes_between_blocks": self._state = "{0:.2f}".format(stats.minut...
self._state = "{0:.1f}".format(stats.trade_volume_btc) elif self.type == "miners_revenue_usd": self._state = "{0:.0f}".format(stats.miners_revenue_usd) elif self.type == "btc_mined": self._state = "{}".format(stats.btc_mined * 0.00000001)
random_line_split
sensor.py
"""Bitcoin information service that uses blockchain.info.""" from datetime import timedelta import logging from blockchain import exchangerates, statistics import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_CURRENCY, CONF_DISPLAY...
(hass, config, add_entities, discovery_info=None): """Set up the Bitcoin sensors.""" currency = config.get(CONF_CURRENCY) if currency not in exchangerates.get_ticker(): _LOGGER.warning("Currency %s is not available. Using USD", currency) currency = DEFAULT_CURRENCY data = BitcoinData(...
setup_platform
identifier_name
main.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
let threadpool = threadpool::ThreadPool::new(2); let (tx, rx) = channel(); let (tx_sub, rx_sub) = channel(); let (tx_pub, rx_pub) = channel(); start_pubsub("consensus", vec!["net.tx", "jsonrpc.new_tx", "net.msg", "chain.status"], tx_sub, rx_pub); thread::spawn(move || loop { ...
{ thread::spawn(move || { thread::sleep(Duration::new(prof_start, 0)); println!("******Profiling Start******"); PROFILER.lock().unwrap().start("./consensus_poa.profile").expect("Couldn't start"); thread::slee...
conditional_block
main.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
() { dotenv::dotenv().ok(); // Always print backtrace on panic. ::std::env::set_var("RUST_BACKTRACE", "1"); cita_log::format(LogLevelFilter::Info); println!("CITA:consensus:poa"); let matches = App::new("authority_round") .version("0.1") .author("Cryptape") .about("CITA...
main
identifier_name
main.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
let seal = engine.clone(); let dur = engine.duration(); let mut old_height = 0; let mut new_height = 0; let tx_pub = tx_pub.clone(); thread::spawn(move || loop { let seal = seal.clone(); trace!("seal worker lock!"); loop { ...
thread::spawn(move || loop { let process = process.clone(); handler::process(process, &rx, tx_pub1.clone()); });
random_line_split
main.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
{ dotenv::dotenv().ok(); // Always print backtrace on panic. ::std::env::set_var("RUST_BACKTRACE", "1"); cita_log::format(LogLevelFilter::Info); println!("CITA:consensus:poa"); let matches = App::new("authority_round") .version("0.1") .author("Cryptape") .about("CITA Bl...
identifier_body
nccl_ops_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def _NcclBroadcast(tensors, devices): sender = np.random.randint(0, len(devices)) with ops.device(devices[sender]): tensor = array_ops.identity(tensors[0]) broadcast = nccl.broadcast(tensor) return _DeviceTensors([broadcast] * len(devices), devices) class NcclTestCase(test.TestCase): def _Test(sel...
receiver = np.random.randint(0, len(devices)) with ops.device(devices[receiver]): return [nccl_fun(_DeviceTensors(tensors, devices))]
identifier_body
nccl_ops_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(tensors, devices): res = [] for t, d in zip(tensors, devices): with ops.device(d): res.append(array_ops.identity(t)) return res def _NcclAllReduce(nccl_fun, tensors, devices): return nccl_fun(_DeviceTensors(tensors, devices)) def _NcclReduce(nccl_fun, tensors, devices): receiver = np.random.ran...
_DeviceTensors
identifier_name
nccl_ops_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
np_ans = tensors[0] for t in tensors[1:]: np_ans = numpy_fn(np_ans, t) reduce_tensors = nccl_reduce(tensors, devices) self.assertNotEmpty(reduce_tensors) # Test shape inference. for r in reduce_tensors: self.assertEqual(shape, r.get_...
tensors.append(random.astype(dtype))
conditional_block
nccl_ops_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
for devices in device_sets: shape = (3, 4) random = (np.random.random_sample(shape) - .5) * 1024 tensors = [] for _ in devices: tensors.append(random.astype(dtype)) np_ans = tensors[0] for t in tensors[1:]: np_ans = numpy_fn(np...
with self.test_session(use_gpu=True) as sess:
random_line_split
runner.rs
use regex::Regex; use state::Cucumber; use event::request::{InvokeArgument, Request}; use event::response::{InvokeResponse, Response, StepMatchesResponse}; use definitions::registration::{CucumberRegistrar, SimpleStep}; use std::panic::{self, AssertUnwindSafe}; use std::str::FromStr; /// The step runner for [Cucumber...
fn when(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) { self.cuke.when(file, line, regex, step) } fn then(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) { self.cuke.then(file, line, regex, step) } } pub fn invoke_to_response<World>(test_body: &Sim...
{ self.cuke.given(file, line, regex, step) }
identifier_body
runner.rs
use regex::Regex; use state::Cucumber; use event::request::{InvokeArgument, Request}; use event::response::{InvokeResponse, Response, StepMatchesResponse}; use definitions::registration::{CucumberRegistrar, SimpleStep}; use std::panic::{self, AssertUnwindSafe}; use std::str::FromStr; /// The step runner for [Cucumber...
} }, }; InvokeResponse::fail_from_str(msg) }, } }
random_line_split
runner.rs
use regex::Regex; use state::Cucumber; use event::request::{InvokeArgument, Request}; use event::response::{InvokeResponse, Response, StepMatchesResponse}; use definitions::registration::{CucumberRegistrar, SimpleStep}; use std::panic::{self, AssertUnwindSafe}; use std::str::FromStr; /// The step runner for [Cucumber...
, Request::EndScenario(_) => { self.cuke.tags = Vec::new(); Response::EndScenario }, // TODO: For some reason, cucumber prints the ruby snippet too. Fix that Request::SnippetText(params) => { let text = format!(" // In a step registration block where cuke: &mut \ ...
{ let matches = self.cuke.find_match(&params.name_to_match); if matches.len() == 0 { Response::StepMatches(StepMatchesResponse::NoMatch) } else { Response::StepMatches(StepMatchesResponse::Match(matches)) } }
conditional_block
runner.rs
use regex::Regex; use state::Cucumber; use event::request::{InvokeArgument, Request}; use event::response::{InvokeResponse, Response, StepMatchesResponse}; use definitions::registration::{CucumberRegistrar, SimpleStep}; use std::panic::{self, AssertUnwindSafe}; use std::str::FromStr; /// The step runner for [Cucumber...
(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) { self.cuke.when(file, line, regex, step) } fn then(&mut self, file: &str, line: u32, regex: Regex, step: SimpleStep<World>) { self.cuke.then(file, line, regex, step) } } pub fn invoke_to_response<World>(test_body: &SimpleStep<Wor...
when
identifier_name
counting.py
# python3 # Copyright 2018 DeepMind Technologies Limited. 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 re...
if self._prefix and self._return_only_prefixed: counts = dict([(key[len(self._prefix) + 1:], value) for key, value in counts.items() if key.startswith(f'{self._prefix}_')]) return counts def save(self) -> Mapping[str, Mapping[str, Number]]: return {'count...
counts[key] = counts.get(key, 0) + value
conditional_block
counting.py
# python3 # Copyright 2018 DeepMind Technologies Limited. 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 re...
"""Return a dictionary with prefixed keys. Args: dictionary: dictionary to return a copy of. prefix: string to use as the prefix. Returns: Return a copy of the given dictionary whose keys are replaced by "{prefix}_{key}". If the prefix is the empty string it returns the given dictionary unchan...
identifier_body
counting.py
# python3 # Copyright 2018 DeepMind Technologies Limited. 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 re...
(dictionary: Dict[str, Number], prefix: str): """Return a dictionary with prefixed keys. Args: dictionary: dictionary to return a copy of. prefix: string to use as the prefix. Returns: Return a copy of the given dictionary whose keys are replaced by "{prefix}_{key}". If the prefix is the empty s...
_prefix_keys
identifier_name
counting.py
# python3 # Copyright 2018 DeepMind Technologies Limited. 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 re...
with self._lock: counts = _prefix_keys(self._counts, self._prefix) # Reset the local counts, as they will be merged into the parent and the # cache. self._counts = {} self._cache = self._parent.increment(**counts) self._last_sync_time = now # Potentially prefix the...
random_line_split
edwards.js
'use strict'; var curve = require('../curve'); var elliptic = require('../../elliptic'); var bn = require('bn.js'); var inherits = require('inherits'); var Base = curve.base; var assert = elliptic.utils.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() this.twisted ...
// B = Y1^2 var b = this.y.redSqr(); // C = 2 * Z1^2 var c = this.z.redSqr(); c = c.redIAdd(c); // D = a * A var d = this.curve._mulA(a); // E = (X1 + Y1)^2 - A - B var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); // G = D + B var g = d.redAdd(b); // F = G - C var f = g.redSub(c);...
// #doubling-dbl-2008-hwcd // 4M + 4S // A = X1^2 var a = this.x.redSqr();
random_line_split
edwards.js
'use strict'; var curve = require('../curve'); var elliptic = require('../../elliptic'); var bn = require('bn.js'); var inherits = require('inherits'); var Base = curve.base; var assert = elliptic.utils.assert; function
(conf) { // NOTE: Important as we are creating point in Base.call() this.twisted = (conf.a | 0) !== 1; this.mOneA = this.twisted && (conf.a | 0) === -1; this.extended = this.mOneA; Base.call(this, 'edwards', conf); this.a = new bn(conf.a, 16).mod(this.red.m).toRed(this.red); this.c = new bn(conf.c, 16)....
EdwardsCurve
identifier_name
edwards.js
'use strict'; var curve = require('../curve'); var elliptic = require('../../elliptic'); var bn = require('bn.js'); var inherits = require('inherits'); var Base = curve.base; var assert = elliptic.utils.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() this.twisted ...
inherits(Point, Base.BasePoint); EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); }; EdwardsCurve.prototype.point = function point(x, y, z, t) { return new Point(this, x, y, z, t); }; Point.fromJSON = function fromJSON(curve, obj) { return new Point(curve,...
{ Base.BasePoint.call(this, curve, 'projective'); if (x === null && y === null && z === null) { this.x = this.curve.zero; this.y = this.curve.one; this.z = this.curve.one; this.t = this.curve.zero; this.zOne = true; } else { this.x = new bn(x, 16); this.y = new bn(y, 16); this.z = ...
identifier_body
IncreaseStat.ts
/// <reference path="../Dialogs/DialogAction.ts" /> @DialogActionClass class IncreaseStat extends ActionClass { public Display(id: number, values: string[], updateFunction?: string): string { var html = ""; html += this.Label("Stat"); html += this.OptionList(id, 0, world.Stats.map(c =>...
if (!this.Execute.caller) { play.devTools = true; world.Player.InformServer(); return; } if (!values[0]) throw "The action 'Increase Stat' requires a name."; if (!env) env = new CodeEnvironement(); var val = 0;...
identifier_body
IncreaseStat.ts
/// <reference path="../Dialogs/DialogAction.ts" /> @DialogActionClass class IncreaseStat extends ActionClass { public Display(id: number, values: string[], updateFunction?: string): string { var html = ""; html += this.Label("Stat"); html += this.OptionList(id, 0, world.Stats.map(c =>...
try { val = CodeParser.ExecuteStatement(values[1], env.variables).GetNumber(); } catch (ex) { throw "The expression used in 'Increase Stat' for the quantity is invalid."; } world.Player.SetStat(values[0], world.Player.GetStat(values[0]) + ...
if (!env) env = new CodeEnvironement(); var val = 0;
random_line_split
IncreaseStat.ts
/// <reference path="../Dialogs/DialogAction.ts" /> @DialogActionClass class IncreaseStat extends ActionClass { public Display(id: number, values: string[], updateFunction?: string): string { var html = ""; html += this.Label("Stat"); html += this.OptionList(id, 0, world.Stats.map(c =>...
alues: string[], env?: CodeEnvironement): void { if (!this.Execute.caller) { play.devTools = true; world.Player.InformServer(); return; } if (!values[0]) throw "The action 'Increase Stat' requires a name."; if (!env) ...
ecute(v
identifier_name
0009_auto_20160517_2016.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-05-17 20:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('samaritan', '0008_member_baptismal_place'), ] opera...
migrations.RemoveField( model_name='membership', name='type', ), migrations.RemoveField( model_name='member', name='membership', ), migrations.AddField( model_name='member', name='membership_date', ...
random_line_split
0009_auto_20160517_2016.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-05-17 20:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ('samaritan', '0008_member_baptismal_place'), ] operations = [ migrations.RemoveField( model_name='membership', name='type', ), migrations.RemoveField( model_name='member', name='membership', ), mig...
identifier_body
0009_auto_20160517_2016.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-05-17 20:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('samaritan', '0008_member_baptismal_place'), ] operations = [ migrations.RemoveField( model_name='membership', name='type', ), migrations.RemoveField( model_name='member', name='member...
Migration
identifier_name
be2bill.py
# -*- coding: utf-8 -*- from decimal import Decimal from be2bill_sdk import Be2BillForm from cartridge_external_payment.providers.base import PaymentProvider class Be2BillProvider(PaymentProvider): def get_start_payment_form(self, request, order): total = Decimal(order.total * 100).quantize(Decima...
def get_transaction_id(self, notification_request): return notification_request.GET.get('TRANSACTIONID', None) def get_cart_id(self, notification_request): raise notification_request.GET.get('EXTRADATA', None)
return notification_request.GET.get('ORDERID', None)
identifier_body
be2bill.py
# -*- coding: utf-8 -*- from decimal import Decimal from be2bill_sdk import Be2BillForm from cartridge_external_payment.providers.base import PaymentProvider class Be2BillProvider(PaymentProvider): def get_start_payment_form(self, request, order): total = Decimal(order.total * 100).quantize(Decima...
def get_cart_id(self, notification_request): raise notification_request.GET.get('EXTRADATA', None)
random_line_split
be2bill.py
# -*- coding: utf-8 -*- from decimal import Decimal from be2bill_sdk import Be2BillForm from cartridge_external_payment.providers.base import PaymentProvider class Be2BillProvider(PaymentProvider): def
(self, request, order): total = Decimal(order.total * 100).quantize(Decimal('0')) fullname = order.billing_detail_first_name + ' ' + \ order.billing_detail_last_name client_ident = "{} ({})".format(fullname, order.billing_detail_email) return Be2BillForm(operatio...
get_start_payment_form
identifier_name
quick.rs
//! An example using the Builder pattern API to configure the logger at run-time based on command //! line arguments. //! //! The default output is `module::path: message`, and the "tag", which is the text to the left of //! the colon, is colorized. This example allows the user to dynamically change the output based //...
{ // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10. // // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_sup...
identifier_body
quick.rs
//! An example using the Builder pattern API to configure the logger at run-time based on command //! line arguments. //! //! The default output is `module::path: message`, and the "tag", which is the text to the left of //! the colon, is colorized. This example allows the user to dynamically change the output based //...
() { // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10. // // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_...
main
identifier_name
quick.rs
//! An example using the Builder pattern API to configure the logger at run-time based on command //! line arguments. //! //! The default output is `module::path: message`, and the "tag", which is the text to the left of //! the colon, is colorized. This example allows the user to dynamically change the output based //...
// // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is // conditionally compiled and only exists for Windows builds. To avoid build errors on // non-windows platfor...
use clap::{Arg, App}; fn main() { // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10.
random_line_split
httpInterceptor.spec.js
import { module, inject } from "angular-mocks"; import "../../../app/auth/auth.module"; (function () { 'use strict'; describe('HttpHeaderInterceptor', function () { var httpHeaderInterceptor, CookiesServiceMock; beforeEach(module('xr.auth')); beforeEach(module(function (...
it('should add Authorization header if token exists', function () { var token = '1234'; spyOn(CookiesServiceMock, 'get').and.returnValue(token); var config = httpHeaderInterceptor.request({ headers: {} }); expect(config.headers.Authorization)...
})); describe('request', function () {
random_line_split
CryptoProvider.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ICrypto, PkceCodes } from "@azure/msal-common"; import { GuidGenerator } from "./GuidGenerator"; import { EncodingUtils } from "../utils/EncodingUtils"; import { PkceGenerator } from "./PkceGenerator"; impor...
/** * Decodes input string from base64. * @param input - string to be decoded */ base64Decode(input: string): string { return EncodingUtils.base64Decode(input); } /** * Generates PKCE codes used in Authorization Code Flow. */ generatePkceCodes(): Promise<PkceCodes...
{ return EncodingUtils.base64Encode(input); }
identifier_body
CryptoProvider.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ICrypto, PkceCodes } from "@azure/msal-common"; import { GuidGenerator } from "./GuidGenerator"; import { EncodingUtils } from "../utils/EncodingUtils"; import { PkceGenerator } from "./PkceGenerator"; impor...
(input: string): string { return EncodingUtils.base64Decode(input); } /** * Generates PKCE codes used in Authorization Code Flow. */ generatePkceCodes(): Promise<PkceCodes> { return this.pkceGenerator.generatePkceCodes(); } /** * Generates a keypair, stores it and re...
base64Decode
identifier_name
CryptoProvider.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ICrypto, PkceCodes } from "@azure/msal-common"; import { GuidGenerator } from "./GuidGenerator"; import { EncodingUtils } from "../utils/EncodingUtils"; import { PkceGenerator } from "./PkceGenerator"; impor...
throw new Error("Method not implemented."); } /** * Removes all cryptographic keys from Keystore */ clearKeystore(): Promise<boolean> { throw new Error("Method not implemented."); } /** * Signs the given object as a jwt payload with private key retrieved by given kid...
/** * Removes cryptographic keypair from key store matching the keyId passed in * @param kid */ removeTokenBindingKey(): Promise<boolean> {
random_line_split
deserialization.rs
use alias::Alias; use config::Config; use consts::*; use itertools::Itertools; use family::Family; use glib::functions; use pango::Context; use pango::ContextExt; use pango::FontMapExt; use pango::FontFamilyExt; use range::Range; use sxd_document::dom::Comment; use sxd_document::dom::ChildOfElement; use sxd_document::d...
fn child_element<'a: 'd, 'd>(name: &'a str, e: Element<'d>) -> Option<Element<'d>> { children_element(name, e).next() } fn children_element<'a: 'd, 'd>( name: &'a str, e: Element<'d>, ) -> impl Iterator<Item = Element<'d>> + 'd { e.children() .into_iter() .filter_map(|x| x.element()) ...
{ child_element(name, e).expect(&format!( "Element {} has no {} child!", e.name().local_part(), name )) }
identifier_body
deserialization.rs
use alias::Alias; use config::Config; use consts::*; use itertools::Itertools; use family::Family; use glib::functions; use pango::Context; use pango::ContextExt; use pango::FontMapExt; use pango::FontFamilyExt; use range::Range; use sxd_document::dom::Comment; use sxd_document::dom::ChildOfElement; use sxd_document::d...
.stripped_ranges = ranges; } matched_family } fn parse_alias<'a>(e: Element, families: &'a Vec<RefCell<Family>>) -> Alias<'a> { let alias_name = checked_text(checked_child_element("family", e)).text(); let p_list = children_element("family", checked_child_element("prefer", e)) .filt...
.collect_vec(); matched_family .unwrap() .borrow_mut() .deref_mut()
random_line_split
deserialization.rs
use alias::Alias; use config::Config; use consts::*; use itertools::Itertools; use family::Family; use glib::functions; use pango::Context; use pango::ContextExt; use pango::FontMapExt; use pango::FontFamilyExt; use range::Range; use sxd_document::dom::Comment; use sxd_document::dom::ChildOfElement; use sxd_document::d...
(context: &Context) -> Vec<RefCell<Family>> { match context.get_font_map() { Some(map) => { map.list_families() .iter() .filter_map(|x| x.get_name()) .filter(|x| !["Sans", "Serif", "Monospace"].contains(&x.as_str())) .map(|x| { ...
list_families
identifier_name
email_test.py
import bountyfunding from bountyfunding.core.const import * from bountyfunding.core.data import clean_database from test import to_object from nose.tools import * USER = "bountyfunding" class Email_Test: def setup(self): self.app = bountyfunding.app.test_client() clean_database() def ...
r = self.app.get("/issue/1") eq_(r.status_code, 200) r = self.app.put('/issue/1', data=dict( status=IssueStatus.to_string(IssueStatus.STARTED))) eq_(r.status_code, 200) emails = self.get_emails() eq_(len(emails), 1) email = emails[0] eq_(ema...
random_line_split
email_test.py
import bountyfunding from bountyfunding.core.const import * from bountyfunding.core.data import clean_database from test import to_object from nose.tools import * USER = "bountyfunding" class Email_Test: def setup(self): self.app = bountyfunding.app.test_client() clean_database() def
(self): eq_(len(self.get_emails()), 0) r = self.app.post('/issues', data=dict(ref=1, status='READY', title='Title', link='/issue/1')) eq_(r.status_code, 200) r = self.app.post('/issue/1/sponsorships', data=dict(user=USER, amount=10)) eq_(r.status_c...
test_email
identifier_name