file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
types.js
the root directory of this source tree. * * @flow */ import type {ReactContext} from 'shared/ReactTypes'; import type {Source} from 'shared/ReactElementType'; import type {Fiber} from 'react-reconciler/src/ReactFiber'; import type { ComponentFilter, ElementType, } from 'react-devtools-shared/src/types'; import...
scheduleUpdate?: ?(fiber: Object) => void, setSuspenseHandler?: ?(shouldSuspend: (fiber: Object) => boolean) => void, // Only injected by React v16.8+ in order to support hooks inspection. currentDispatcherRef?: {|current: null | Dispatcher|}, // Only injected by React v16.9+ in DEV mode. // Enables DevTo...
random_line_split
ErrorReporting.py
# xVector Engine Client # Copyright (c) 2011 James Buchwald # 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 2 # of the License, or (at your option) any later version. # # This pr...
(parent=None): ''' Configures the logging mechanism to report errors as dialog boxes. @type parent: QtGui.QWidget @param parent: Parent widget for errors to be displayed under. ''' # Set up the error handler (output to a message box). handler = ErrorMessageHandler(parent) formatter ...
ConfigureLogging
identifier_name
ErrorReporting.py
# xVector Engine Client # Copyright (c) 2011 James Buchwald # 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 2 # of the License, or (at your option) any later version. # # This pr...
mainlog.addHandler(handler) # Send lower-level messages to stderr. lowhandler = logging.StreamHandler() lowhandler.setFormatter(formatter) lowhandler.setLevel(logging.DEBUG) mainlog.addHandler(lowhandler) # Make sure that the logger catches all levels of messages. mainlog.setLe...
handler.setFormatter(formatter) handler.setLevel(logging.ERROR)
random_line_split
ErrorReporting.py
# xVector Engine Client # Copyright (c) 2011 James Buchwald # 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 2 # of the License, or (at your option) any later version. # # This pr...
def _ShowError(self, message): ''' Shows an error message and returns immediately. @type message: string @param message: Message to display. ''' app = ClientGlobals.Application wnd = QtGui.QMessageBox(parent=self.Parent) wnd.setIcon(QtGu...
''' Creates a new handler. @type parent: QtGui.QWidget @param parent: Parent widget for errors to be displayed under. ''' super(ErrorMessageHandler,self).__init__() self.Parent = parent '''Parent widget for errors to be displayed under.'''
identifier_body
ErrorReporting.py
# xVector Engine Client # Copyright (c) 2011 James Buchwald # 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 2 # of the License, or (at your option) any later version. # # This pr...
elif severity == WarningError: dlg.setIcon(QtGui.QMessageBox.Warning) dlg.setWindowTitle("Warning") elif severity == NoticeError: dlg.setIcon(QtGui.QMessageBox.Information) dlg.setWindowTitle("Notice") else: dlg.setIcon(QtGui.QMessageBox.NoIcon) dlg.setWindow...
dlg.setIcon(QtGui.QMessageBox.Critical) dlg.setWindowTitle("Error")
conditional_block
optimize.js
/** * Created by joonkukang on 2014. 1. 16.. */ var math = require('./utils').math; let optimize = module.exports; optimize.hillclimb = function(options){ var domain = options['domain']; var costf = options['costf']; var i; var vec = []; for(i=0 ; i<domain.length ; i++) vec.push(math.ran...
(vec) { var idx = math.randInt(0,domain.length - 1); var newVec = []; var i; for(i=0; i<domain.length ; i++) newVec.push(vec[i]); newVec[idx] += (Math.random() < 0.5) ? 1 : -1; if(newVec[idx] < domain[idx][0]) newVec[idx] = domain[idx][0]; if(newVec[id...
mutate
identifier_name
optimize.js
/** * Created by joonkukang on 2014. 1. 16.. */ var math = require('./utils').math; let optimize = module.exports; optimize.hillclimb = function(options){ var domain = options['domain']; var costf = options['costf']; var i; var vec = []; for(i=0 ; i<domain.length ; i++) vec.push(math.ran...
} } current = costf(vec); best = current; for(i=0 ; i<neighbors.length ; i++) { var cost = costf(neighbors[i]); if(cost < best) { best = cost; vec = neighbors[i]; } } if(best === current) ...
random_line_split
optimize.js
/** * Created by joonkukang on 2014. 1. 16.. */ var math = require('./utils').math; let optimize = module.exports; optimize.hillclimb = function(options){ var domain = options['domain']; var costf = options['costf']; var i; var vec = []; for(i=0 ; i<domain.length ; i++) vec.push(math.ran...
};
{ var a = [0.0]; var i; for(i=0;i<vec.length;i++) { a.push(a[i] + vec[i]); } var rand = Math.random(); for(i=0;i< a.length;i++) { if(rand > a[i] && rand <= a[i+1]) return i; } return -1; }
identifier_body
index.js
'use strict'; var oauth2orize = require('oauth2orize'), passport = require('passport'), mongoose = require('mongoose'), randomstring = require('randomstring'), logger = require('../core/logger'), OAuthAuthorizationCode = mongoose.model('OAuthAuthorizationCode'), OAuthAccessToken = mongoose.mode...
var uid = randomstring.generate(40); var oauthAccessToken = new OAuthAccessToken({ accessToken: uid, clientId: clientId, userId: oauthauthorizationcode.userId }); oauthAccessToken.save(function(error, result) { if (error) { return done(error); } return done(n...
{ return done(null, false); }
conditional_block
index.js
'use strict'; var oauth2orize = require('oauth2orize'), passport = require('passport'), mongoose = require('mongoose'), randomstring = require('randomstring'), logger = require('../core/logger'), OAuthAuthorizationCode = mongoose.model('OAuthAuthorizationCode'), OAuthAccessToken = mongoose.mode...
var clientId = client._id || client; return done(null, clientId); }); server.deserializeClient(function(id, done) { OAuthClient.findById(id, function(error, client) { if (error) { return done(error); } return done(null, client); }); }); server.grant(oauth2orize.grant.code(function(client, re...
random_line_split
video_search_result.py
# coding: utf-8 """ Picarto.TV API Documentation The Picarto.TV API documentation Note, for fixed access tokens, the header that needs to be sent is of the format: `Authorization: Bearer yourTokenHere` This can be generated at https://oauth.picarto.tv/ For chat API, see https://docs.picarto.tv/chat/chat.pr...
Returns true if both objects are not equal """ return not self == other
random_line_split
video_search_result.py
# coding: utf-8 """ Picarto.TV API Documentation The Picarto.TV API documentation Note, for fixed access tokens, the header that needs to be sent is of the format: `Authorization: Bearer yourTokenHere` This can be generated at https://oauth.picarto.tv/ For chat API, see https://docs.picarto.tv/chat/chat.pr...
def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, VideoSearchResult): return False return self.__dict__...
""" Returns the string representation of the model """ return pformat(self.to_dict())
identifier_body
video_search_result.py
# coding: utf-8 """ Picarto.TV API Documentation The Picarto.TV API documentation Note, for fixed access tokens, the header that needs to be sent is of the format: `Authorization: Bearer yourTokenHere` This can be generated at https://oauth.picarto.tv/ For chat API, see https://docs.picarto.tv/chat/chat.pr...
(self): """ Gets the video of this VideoSearchResult. :return: The video of this VideoSearchResult. :rtype: ChannelVideo """ return self._video @video.setter def video(self, video): """ Sets the video of this VideoSearchResult. :param vi...
video
identifier_name
video_search_result.py
# coding: utf-8 """ Picarto.TV API Documentation The Picarto.TV API documentation Note, for fixed access tokens, the header that needs to be sent is of the format: `Authorization: Bearer yourTokenHere` This can be generated at https://oauth.picarto.tv/ For chat API, see https://docs.picarto.tv/chat/chat.pr...
else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return sel...
result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() ))
conditional_block
provider.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
() { } /** * Defines the metadata of Provider * * @returns {object} metadata of Provider * */ mapper() { return { required: false, serializedName: 'Provider', type: { name: 'Composite', className: 'Provider', modelProperties: { id: { ...
constructor
identifier_name
provider.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
} }, namespace: { required: false, serializedName: 'namespace', type: { name: 'String' } }, registrationState: { required: false, readOnly: true, serializedName: 'registr...
type: { name: 'String'
random_line_split
service_http_transport.py
#!/usr/bin/python # service_http_transport.py # # Copyright (C) 2008-2018 Veselin Penev, https://bitdust.io # # This file (service_http_transport.py) is part of BitDust Software. # # BitDust is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as publishe...
oldvalue, value, path)) network_connector.A('reconnect')
from p2p import network_connector from logs import lg lg.out(2, 'service_http_transport._on_receiving_enabled_disabled : %s->%s : %s' % (
random_line_split
service_http_transport.py
#!/usr/bin/python # service_http_transport.py # # Copyright (C) 2008-2018 Veselin Penev, https://bitdust.io # # This file (service_http_transport.py) is part of BitDust Software. # # BitDust is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as publishe...
def start(self): from twisted.internet import reactor from twisted.internet.defer import Deferred from transport.http import http_interface from transport import network_transport from transport import gateway from main.config import conf self.starting_defer...
return ['service_http_connections', 'service_gateway', ]
identifier_body
service_http_transport.py
#!/usr/bin/python # service_http_transport.py # # Copyright (C) 2008-2018 Veselin Penev, https://bitdust.io # # This file (service_http_transport.py) is part of BitDust Software. # # BitDust is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as publishe...
(LocalService): service_name = 'service_http_transport' config_path = 'services/http-transport/enabled' proto = 'http' def enabled(self): # development started return False def dependent_on(self): return ['service_http_connections', 'service_gateway', ...
HTTPTransportService
identifier_name
service_http_transport.py
#!/usr/bin/python # service_http_transport.py # # Copyright (C) 2008-2018 Veselin Penev, https://bitdust.io # # This file (service_http_transport.py) is part of BitDust Software. # # BitDust is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as publishe...
def _on_enabled_disabled(self, path, value, oldvalue, result): from p2p import network_connector from logs import lg lg.out(2, 'service_http_transport._on_enabled_disabled : %s->%s : %s' % ( oldvalue, value, path)) network_connector.A('reconnect') def _on_receiving...
self.starting_deferred.callback(newstate) self.starting_deferred = None
conditional_block
test_cron.py
from unittest import mock from olympia.amo.cron import gc from olympia.amo.tests import TestCase from olympia.files.models import FileUpload @mock.patch('olympia.amo.cron.storage') class TestGC(TestCase): def test_file_uploads_deletion(self, storage_mock): fu_new = FileUpload.objects.create(path='/tmp/ne...
assert storage_mock.delete.call_count == 2 assert storage_mock.delete.call_args_list[0][0][0] == fu_older.path assert storage_mock.delete.call_args_list[1][0][0] == fu_old.path
random_line_split
test_cron.py
from unittest import mock from olympia.amo.cron import gc from olympia.amo.tests import TestCase from olympia.files.models import FileUpload @mock.patch('olympia.amo.cron.storage') class TestGC(TestCase): def test_file_uploads_deletion(self, storage_mock): fu_new = FileUpload.objects.create(path='/tmp/ne...
(self, storage_mock): fu_older = FileUpload.objects.create(path='/tmp/older', name='older') fu_older.update(created=self.days_ago(300)) fu_old = FileUpload.objects.create(path='/tmp/old', name='old') fu_old.update(created=self.days_ago(8)) storage_mock.delete.side_effect = OSErr...
test_file_uploads_deletion_oserror
identifier_name
test_cron.py
from unittest import mock from olympia.amo.cron import gc from olympia.amo.tests import TestCase from olympia.files.models import FileUpload @mock.patch('olympia.amo.cron.storage') class TestGC(TestCase):
def test_file_uploads_deletion_oserror(self, storage_mock): fu_older = FileUpload.objects.create(path='/tmp/older', name='older') fu_older.update(created=self.days_ago(300)) fu_old = FileUpload.objects.create(path='/tmp/old', name='old') fu_old.update(created=self.days_ago(8)) ...
def test_file_uploads_deletion(self, storage_mock): fu_new = FileUpload.objects.create(path='/tmp/new', name='new') fu_new.update(created=self.days_ago(6)) fu_old = FileUpload.objects.create(path='/tmp/old', name='old') fu_old.update(created=self.days_ago(8)) gc() asser...
identifier_body
31_file_package_verify.py
#!/usr/bin/env python3 import json import os import sys import anchore_engine.analyzers.utils analyzer_name = "file_package_verify" try: config = anchore_engine.analyzers.utils.init_analyzer_cmdline( sys.argv, analyzer_name ) except Exception as err: print(str(err)) sys.exit(1) imgname = con...
if resultlist: ofile = os.path.join(outputdir, "distro.pkgfilemeta") anchore_engine.analyzers.utils.write_kvfile_fromdict(ofile, resultlist) sys.exit(0)
try: resultlist[f] = json.dumps(result[f], sort_keys=True) except Exception as err: print("WARN: " + str(err)) resultlist[f] = ""
conditional_block
31_file_package_verify.py
#!/usr/bin/env python3 import json import os import sys import anchore_engine.analyzers.utils analyzer_name = "file_package_verify" try: config = anchore_engine.analyzers.utils.init_analyzer_cmdline( sys.argv, analyzer_name )
imgname = config["imgid"] imgid = config["imgid_full"] outputdir = config["dirs"]["outputdir"] unpackdir = config["dirs"]["unpackdir"] squashtar = os.path.join(unpackdir, "squashed.tar") meta = anchore_engine.analyzers.utils.get_distro_from_squashtar( squashtar, unpackdir=unpackdir ) distrodict = anchore_engine.a...
except Exception as err: print(str(err)) sys.exit(1)
random_line_split
parser_tests.rs
#[cfg(test)] mod tests { use model::{Model, TemplateParameter}; use std::fs::File; use std::io::Write; use clang::{Clang, Index}; use tempdir::TempDir; use serde_json; use std::fmt::Debug; use response_file::ExtendWithResponseFile; const INTERFACE: &'static str = r#" namespace fo...
#[test] fn should_list_template_parameters() { let model = create_model(TEMPLATE_INTERFACE); assert!(model.interfaces.len() > 0); assert_eq!(model.interfaces[0] .clone() .template_parameters .unwrap(), ...
{ create_model(TEMPLATE_INTERFACE); }
identifier_body
parser_tests.rs
#[cfg(test)] mod tests { use model::{Model, TemplateParameter}; use std::fs::File; use std::io::Write; use clang::{Clang, Index}; use tempdir::TempDir; use serde_json; use std::fmt::Debug; use response_file::ExtendWithResponseFile; const INTERFACE: &'static str = r#" namespace fo...
() { create_model(TEMPLATE_INTERFACE); } #[test] fn should_list_template_parameters() { let model = create_model(TEMPLATE_INTERFACE); assert!(model.interfaces.len() > 0); assert_eq!(model.interfaces[0] .clone() .template_paramete...
should_parse_template_class
identifier_name
parser_tests.rs
#[cfg(test)]
use model::{Model, TemplateParameter}; use std::fs::File; use std::io::Write; use clang::{Clang, Index}; use tempdir::TempDir; use serde_json; use std::fmt::Debug; use response_file::ExtendWithResponseFile; const INTERFACE: &'static str = r#" namespace foo { namespace sample { s...
mod tests {
random_line_split
detectWithExtension.js
var path = require("path"); var fs = require("fs"); function
(filename, extensions = [""], folders = [""]) { if (extensions === null) { extensions = [""]; } if (folders === null) folders = [""]; extensions = [].concat(extensions); return new Promise(function (ok, oh) { filename = filename.replace(/\$/g, '/'); var prefix = 0; va...
detectWithExtension
identifier_name
detectWithExtension.js
var path = require("path"); var fs = require("fs"); function detectWithExtension(filename, extensions = [""], folders = [""]) { if (extensions === null) { extensions = [""]; } if (folders === null) folders = [""];
return new Promise(function (ok, oh) { filename = filename.replace(/\$/g, '/'); var prefix = 0; var aftfix = 0; var findedFolder; var run = function () { if (aftfix >= extensions.length) { if (prefix + 1 < folders.length) { pre...
extensions = [].concat(extensions);
random_line_split
detectWithExtension.js
var path = require("path"); var fs = require("fs"); function detectWithExtension(filename, extensions = [""], folders = [""]) { if (extensions === null) { extensions = [""]; } if (folders === null) folders = [""]; extensions = [].concat(extensions); return new Promise(function (ok, oh) { ...
return oh(`路径<gray>${filename}</gray>不存在`); } } var f = path.join(folders[prefix], filename) + extensions[aftfix++]; if (fs.existsSync(f)) { fs.stat(f, function (error, stats) { if (error) return run(); ...
{ return ok(findedFolder); }
conditional_block
detectWithExtension.js
var path = require("path"); var fs = require("fs"); function detectWithExtension(filename, extensions = [""], folders = [""])
return ok(findedFolder); } return oh(`路径<gray>${filename}</gray>不存在`); } } var f = path.join(folders[prefix], filename) + extensions[aftfix++]; if (fs.existsSync(f)) { fs.stat(f, function ...
{ if (extensions === null) { extensions = [""]; } if (folders === null) folders = [""]; extensions = [].concat(extensions); return new Promise(function (ok, oh) { filename = filename.replace(/\$/g, '/'); var prefix = 0; var aftfix = 0; var findedFolder; ...
identifier_body
cci_no_inline_lib.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 ...
// same as cci_iter_lib, more-or-less, but not marked inline pub fn iter<F>(v: Vec<uint> , mut f: F) where F: FnMut(uint) { let mut i = 0_usize; let n = v.len(); while i < n { f(v[i]); i += 1_usize; } }
#![crate_name="cci_no_inline_lib"]
random_line_split
cci_no_inline_lib.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 ...
<F>(v: Vec<uint> , mut f: F) where F: FnMut(uint) { let mut i = 0_usize; let n = v.len(); while i < n { f(v[i]); i += 1_usize; } }
iter
identifier_name
cci_no_inline_lib.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 ...
{ let mut i = 0_usize; let n = v.len(); while i < n { f(v[i]); i += 1_usize; } }
identifier_body
dump-rename.js
#!/usr/bin/env node var JavaScriptBuffer = require('../type-inference'), fs = require('fs'), clc = require('cli-color'); var filename = process.argv[2]; var text = fs.readFileSync(filename, {encoding:"utf8"});
buffer.add(filename, text); var groups = buffer.renamePropertyName(process.argv[3] || "add"); groups.forEach(function(group) { console.log(clc.green("---------------- (" + group.length + ")")); group.forEach(function (item,index) { if (index > 0) console.log(clc.blackBright("--")); var idx = ite...
var lines = text.split(/\r?\n|\r/); var buffer = new JavaScriptBuffer;
random_line_split
test.rs
use intern::intern; use grammar::repr::*; use lr1::Lookahead; use lr1::Lookahead::EOF; use test_util::{normalized_grammar}; use super::FirstSets; pub fn nt(t: &str) -> Symbol { Symbol::Nonterminal(NonterminalString(intern(t))) } pub fn term(t: &str) -> Symbol { Symbol::Terminal(TerminalString::Quoted(intern(t...
"D" => Some(1); => None; }; "#); let first_sets = FirstSets::new(&grammar); assert_eq!( first(&first_sets, &[nt("A")], EOF), vec![la("C"), la("D")]); assert_eq!( first(&first_sets, &[nt("B")], EOF), vec![EOF, la("D")]); assert_eq!( first(&fi...
let grammar = normalized_grammar(r#" grammar; extern { enum Tok { } } A = B "C"; B: Option<u32> = {
random_line_split
test.rs
use intern::intern; use grammar::repr::*; use lr1::Lookahead; use lr1::Lookahead::EOF; use test_util::{normalized_grammar}; use super::FirstSets; pub fn nt(t: &str) -> Symbol { Symbol::Nonterminal(NonterminalString(intern(t))) } pub fn
(t: &str) -> Symbol { Symbol::Terminal(TerminalString::Quoted(intern(t))) } fn la(t: &str) -> Lookahead { Lookahead::Terminal(TerminalString::Quoted(intern(t))) } fn first(first: &FirstSets, symbols: &[Symbol], lookahead: Lookahead) -> Vec<Lookahead> { let mut v = first.first(symbols, lookahead); v.so...
term
identifier_name
test.rs
use intern::intern; use grammar::repr::*; use lr1::Lookahead; use lr1::Lookahead::EOF; use test_util::{normalized_grammar}; use super::FirstSets; pub fn nt(t: &str) -> Symbol { Symbol::Nonterminal(NonterminalString(intern(t))) } pub fn term(t: &str) -> Symbol
fn la(t: &str) -> Lookahead { Lookahead::Terminal(TerminalString::Quoted(intern(t))) } fn first(first: &FirstSets, symbols: &[Symbol], lookahead: Lookahead) -> Vec<Lookahead> { let mut v = first.first(symbols, lookahead); v.sort(); v } #[test] fn basic() { let grammar = normalized_grammar(r#" gr...
{ Symbol::Terminal(TerminalString::Quoted(intern(t))) }
identifier_body
auth.service.ts
/** * Copyright (c) 2017 Francois-Xavier Soubirou. * * This file is part of tam4. * * tam4 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 lat...
logout() { this.afAuth.auth.signOut(); } }
{ return this.afAuth.auth.signInWithPopup( new firebase.auth.GoogleAuthProvider() ); }
identifier_body
auth.service.ts
/** * Copyright (c) 2017 Francois-Xavier Soubirou. * * This file is part of tam4. * * tam4 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 lat...
() { return this.afAuth.auth.signInWithPopup( new firebase.auth.GoogleAuthProvider() ); } logout() { this.afAuth.auth.signOut(); } }
loginWithGoogle
identifier_name
auth.service.ts
/** * Copyright (c) 2017 Francois-Xavier Soubirou. * * This file is part of tam4. * * tam4 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 lat...
*/ import { Injectable } from '@angular/core'; import { AngularFireAuth } from 'angularfire2/auth'; import * as firebase from 'firebase/app'; import { Observable } from 'rxjs/Observable'; @Injectable() export class AuthService { user: Observable<firebase.User>; constructor(public afAuth: AngularFireAuth) { ...
* GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with tam4. If not, see <http://www.gnu.org/licenses/>.
random_line_split
protected-routes.js
var memoryController = require('../../db/controllers/memoryController'); var express = require('express'); var jwt = require('express-jwt'); var multer = require('multer'); var bodyParser = require('body-parser'); var jsonParser = bodyParser.json(); var storage = multer.diskStorage({ destination: function (req, file...
module.exports = router;
//User searches for a specific tag router.route('/search/:query').get(memoryController.searchMemories);
random_line_split
test_fixes.py
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD import numpy as np from nose.tools import assert_equal, assert_raises from numpy.testing import assert_array...
assert_array_equal(_copysign(b, a), a) def test_firwin2(): """Test firwin2 backport """ taps1 = mne_firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) taps2 = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) assert_array_equal(taps1, taps2) def test_filtfilt(): """Test IIR filtfilt repl...
"""Test numpy.copysign() replacement""" a = np.array([-1, 1, -1]) b = np.array([1, -1, 1]) assert_array_equal(_copysign(a, b), b)
random_line_split
test_fixes.py
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD import numpy as np from nose.tools import assert_equal, assert_raises from numpy.testing import assert_array...
def test_unravel_index(): """Test numpy.unravel_index() replacement""" assert_equal(_unravel_index(2, (2, 3)), (0, 2)) assert_equal(_unravel_index(2, (2, 2)), (1, 0)) assert_equal(_unravel_index(254, (17, 94)), (2, 66)) assert_equal(_unravel_index((2 * 3 + 1) * 6 + 4, (4, 3, 6)), (2, 1, 4)) a...
"""Test numpy.tril_indices() replacement""" il1 = _tril_indices(4) il2 = _tril_indices(4, -1) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) assert_array_equal(a[il1], np.array([1, 5, 6, 9, 10, ...
identifier_body
test_fixes.py
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD import numpy as np from nose.tools import assert_equal, assert_raises from numpy.testing import assert_array...
def test_unique(): """Test unique() replacement """ # skip test for np version < 1.5 if LooseVersion(np.__version__) < LooseVersion('1.5'): return for arr in [np.array([]), np.random.rand(10), np.ones(10)]: # basic assert_array_equal(np.unique(arr), _unique(arr)) #...
assert_equal(a[key], b[key])
conditional_block
test_fixes.py
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD import numpy as np from nose.tools import assert_equal, assert_raises from numpy.testing import assert_array...
(): """Test numpy.copysign() replacement""" a = np.array([-1, 1, -1]) b = np.array([1, -1, 1]) assert_array_equal(_copysign(a, b), b) assert_array_equal(_copysign(b, a), a) def test_firwin2(): """Test firwin2 backport """ taps1 = mne_firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) ...
test_copysign
identifier_name
compile.rs
use basm; use beast; use core::error::*; use std::env; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::str::FromStr; const BAKERVM_IMAGE_EXTENSION: &str = "img"; pub const DEFAULT_LANG: Lang = Lang::Beast; #[derive(Debug)] pub enum
{ Beast, Basm, } impl FromStr for Lang { type Err = &'static str; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { match s { "basm" => Ok(Lang::Basm), "beast" | "bst" => Ok(Lang::Beast), _ => bail!("unknown language. Language must be one of [...
Lang
identifier_name
compile.rs
use basm; use beast; use core::error::*; use std::env; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::str::FromStr; const BAKERVM_IMAGE_EXTENSION: &str = "img"; pub const DEFAULT_LANG: Lang = Lang::Beast; #[derive(Debug)] pub enum Lang { Beast, Basm, } impl FromStr for Lang { typ...
pub fn compile(lang: Option<Lang>, input: PathBuf, output: Option<PathBuf>) -> Result<()> { let input = input .canonicalize() .chain_err(|| "unable to canonicalize input path")?; // We don't want to fail at recognizing the language, so we just default to // Beast let lang = lang.unwrap_...
random_line_split
compile.rs
use basm; use beast; use core::error::*; use std::env; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::str::FromStr; const BAKERVM_IMAGE_EXTENSION: &str = "img"; pub const DEFAULT_LANG: Lang = Lang::Beast; #[derive(Debug)] pub enum Lang { Beast, Basm, } impl FromStr for Lang { typ...
ensure!( fallback_output.set_extension(BAKERVM_IMAGE_EXTENSION), "unable to set file extension" ); let output = output.unwrap_or(fallback_output); let start_dir = env::current_dir().chain_err(|| "unable to get current directory")?; let program = match lang { Lang::Basm =>...
{ let input = input .canonicalize() .chain_err(|| "unable to canonicalize input path")?; // We don't want to fail at recognizing the language, so we just default to // Beast let lang = lang.unwrap_or_else(|| { if let Some(extension) = input.extension() { if let Some(...
identifier_body
wmlparser3.py
For example: [unit] name=A name=B [attack] [/attack] [attack] [/attack] [/unit] unit.get_all(att = "name") will return two nodes for "name=A" and "name=B" unit.get_all(tag = "attack") will return ...
if self.verbose: print((" ".join(commandline))) p = subprocess.Popen(commandline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if self.verbose: print((out + err).decode("utf8")) self.preprocessed ...
commandline += ["--preprocess-defines", defines]
conditional_block
wmlparser3.py
unit] name=A name=B [attack] [/attack] [attack] [/attack] [/unit] unit.get_all(att = "name") will return two nodes for "name=A" and "name=B" unit.get_all(tag = "attack") will return two nodes for the two [a...
def parse_line_without_commands(self, line): while True:
random_line_split
wmlparser3.py
self.temp_dir = None self.no_preprocess = (wesnoth_exe is None) self.preprocessed = None self.verbose = False self.last_wml_line = "?" self.parser_line = 0 self.line_in_file = 42424242 self.chunk_start = "?" def parse_file(self, path, defines="") ->...
""" Parse preprocessed WML into a tree of tags and attributes. """ # parsing state self.temp_string = b"" self.temp_string_node = None self.commas = 0 self.temp_key_nodes = [] self.in_string = False self.in_arrows = False self.textdomain =...
identifier_body
wmlparser3.py
For example: [unit] name=A name=B [attack] [/attack] [attack] [/attack] [/unit] unit.get_all(att = "name") will return two nodes for "name=A" and "name=B" unit.get_all(tag = "attack") will return ...
(self, defines): """ This is called by the parse functions to preprocess the input from a normal WML .cfg file into a preprocessed .plain file. """ if self.keep_temp_dir: output = self.keep_temp_dir else: output = tempfile.mkdtemp(prefix="w...
preprocess
identifier_name
cfloop.js
/* globals require, exports */ // jshint devel:true, curly: false, asi:true, -W084, -W061 var utils = require('../utils') exports.hasBody = true exports.tagMatch = /<[\/]?cfloop[^>]*>/gi exports.render = function(tag, vars, renderFn){ var out = '' if (typeof tag.attributes.from != 'undefined' && typeof tag.attribute...
} } else if (tag.attributes.array && tag.attributes.index){ var array = vars[tag.attributes.array.replace(/#/g, '')] if (! array) eval ("array = vars." + tag.attributes.array.replace(/#/g,'')) for (var l=0,m=array.length; l < m; l++){ vars[tag.attributes.index] = array[l]; out += renderFn(tag.parsedBody...
random_line_split
cfloop.js
/* globals require, exports */ // jshint devel:true, curly: false, asi:true, -W084, -W061 var utils = require('../utils') exports.hasBody = true exports.tagMatch = /<[\/]?cfloop[^>]*>/gi exports.render = function(tag, vars, renderFn){ var out = '' if (typeof tag.attributes.from != 'undefined' && typeof tag.attribute...
} } else if (tag.attributes.array && tag.attributes.index){ var array = vars[tag.attributes.array.replace(/#/g, '')] if (! array) eval ("array = vars." + tag.attributes.array.replace(/#/g,'')) for (var l=0,m=array.length; l < m; l++){ vars[tag.attributes.index] = array[l]; out += renderFn(tag.parsedBod...
{ delete vars.__BREAKLOOP break; }
conditional_block
types.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation ...
elif value.get() == 'date': mytypes[key] = library.DateType() else: raise ConfigValueError( u"unknown type '{0}' for the '{1}' field" .format(value, key)) return mytypes
@property def item_types(self): return self._types() @property def album_types(self): return self._types() def _types(self): if not self.config.exists(): return {} mytypes = {} for key, value in self.config.items(): if value.get() == 'in...
identifier_body
types.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation ...
from __future__ import (division, absolute_import, print_function, unicode_literals) from beets.plugins import BeetsPlugin from beets.dbcore import types from beets.util.confit import ConfigValueError from beets import library class TypesPlugin(BeetsPlugin): @property def item_types...
random_line_split
types.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation ...
elif value.get() == 'date': mytypes[key] = library.DateType() else: raise ConfigValueError( u"unknown type '{0}' for the '{1}' field" .format(value, key)) return mytypes
mytypes[key] = types.BOOLEAN
conditional_block
types.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation ...
(self): return self._types() def _types(self): if not self.config.exists(): return {} mytypes = {} for key, value in self.config.items(): if value.get() == 'int': mytypes[key] = types.INTEGER elif value.get() == 'float': ...
album_types
identifier_name
sign.py
import chainer from chainer import backend from chainer import utils def
(x): """Elementwise sign function. For a given input :math:`x`, this function returns :math:`sgn(x)` defined as .. math:: sgn(x) = \\left \\{ \\begin{array}{cc} -1 & {\\rm if~x < 0} \\\\ 0 & {\\rm if~x = 0} \\\\ 1 & {\\rm if~x > 0} \\\\ \\end{array} \\right. ...
sign
identifier_name
sign.py
import chainer from chainer import backend from chainer import utils def sign(x): """Elementwise sign function. For a given input :math:`x`, this function returns :math:`sgn(x)` defined as .. math:: sgn(x) = \\left \\{ \\begin{array}{cc} -1 & {\\rm if~x < 0} \\\\ 0 & {\\rm i...
Returns: ~chainer.Variable: Output variable. """ if isinstance(x, chainer.variable.Variable): x = x.array xp = backend.get_array_module(x) return chainer.as_variable(utils.force_array(xp.sign(x)))
x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable for which the sign is computed.
random_line_split
sign.py
import chainer from chainer import backend from chainer import utils def sign(x):
Input variable for which the sign is computed. Returns: ~chainer.Variable: Output variable. """ if isinstance(x, chainer.variable.Variable): x = x.array xp = backend.get_array_module(x) return chainer.as_variable(utils.force_array(xp.sign(x)))
"""Elementwise sign function. For a given input :math:`x`, this function returns :math:`sgn(x)` defined as .. math:: sgn(x) = \\left \\{ \\begin{array}{cc} -1 & {\\rm if~x < 0} \\\\ 0 & {\\rm if~x = 0} \\\\ 1 & {\\rm if~x > 0} \\\\ \\end{array} \\right. .. not...
identifier_body
sign.py
import chainer from chainer import backend from chainer import utils def sign(x): """Elementwise sign function. For a given input :math:`x`, this function returns :math:`sgn(x)` defined as .. math:: sgn(x) = \\left \\{ \\begin{array}{cc} -1 & {\\rm if~x < 0} \\\\ 0 & {\\rm i...
xp = backend.get_array_module(x) return chainer.as_variable(utils.force_array(xp.sign(x)))
x = x.array
conditional_block
mediawiki.Upload.BookletLayout.js
InsertForm} */ /* Methods */ /** * Initialize for a new upload * * @return {jQuery.Promise} Promise resolved when everything is initialized */ mw.Upload.BookletLayout.prototype.initialize = function () { this.clear(); this.upload = this.createUpload(); this.setPage( 'upload' ); return $.Deferred(...
} ); this.descriptionWidget = new OO.ui.TextInputWidget( { indicator: 'required', required: true, validate: /.+/,
random_line_split
mediawiki.Upload.BookletLayout.js
) { // Parent constructor mw.Upload.BookletLayout.parent.call( this, config ); this.$overlay = config.$overlay; this.renderUploadForm(); this.renderInfoForm(); this.renderInsertForm(); this.addPages( [ new OO.ui.PageLayout( 'upload', { scrollable: true, padded: true, content: [ this.upl...
{ // Change the name if the current name isn't acceptable // TODO This might not really be the best place to do this this.filenameWidget.setValue( warnings.badfilename ); return new OO.ui.Error( $( '<p>' ).msg( 'badfilename', warnings.badfilename ) ); }
conditional_block
theplatform.tinymce.plugin.js
/* thePlatform Video Manager Wordpress Plugin Copyright (C) 2013-2014 thePlatform for Media Inc. 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 2 of the License, or (at your opt...
} );
tinymce.init( { plugins: 'theplatform'
random_line_split
jquery-galleria.d.ts
// Type definitions for galleria.js v1.4.2 // Project: https://github.com/aino/galleria // Definitions by: Robert Imig <https://github.com/rimig> // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module GalleriaJS { interface GalleriaOptions { dataSource: GalleriaEntry[]; autopla...
interface GalleriaFactory { run(): GalleriaFactory; run(selector: String): GalleriaFactory; run(selector: String, options: GalleriaOptions): GalleriaFactory; loadTheme(url : String): GalleriaFactory; configure(options: GalleriaOptions): GalleriaFactory; ready( method: () => any):...
image?: string; thumbnail?: string; title?: string; description?: string; }
random_line_split
compose.js
? proto.prototype : proto || Object.prototype); } : function(proto){ Create.prototype = typeof proto == "function" ? proto.prototype : proto; var instance = new Create(); Create.prototype = null; return instance; }; function validArg(arg){ if(!arg){ throw new Error("Compose arguments must be fu...
// this does the work of combining mixins/prototypes function mixin(instance, args, i){ // use prototype inheritance for first arg var value, argsLength = args.length; for(; i < argsLength; i++){ var arg = args[i]; if(typeof arg == "function"){ // the arg is a function, use the prototype for the prop...
random_line_split
compose.js
proto.prototype : proto || Object.prototype); } : function(proto){ Create.prototype = typeof proto == "function" ? proto.prototype : proto; var instance = new Create(); Create.prototype = null; return instance; }; function validArg(arg){ if(!arg){ throw new Error("Compose arguments must be func...
return instance; } // create a function that can retrieve the bases (constructors or prototypes) Constructor._getBases = function(prototype){ return prototype ? prototypes : constructors; }; // now get the prototypes and the constructors var constructors = getBases(args), constructorsLength = con...
{ var constructor = constructors[i]; var result = constructor.apply(instance, arguments); if(typeof result == "object"){ if(result instanceof Constructor){ instance = result; }else{ for(var j in result){ if(result.hasOwnProperty(j)){ instance[j] = result[j]; } ...
conditional_block
compose.js
proto.prototype : proto || Object.prototype); } : function(proto){ Create.prototype = typeof proto == "function" ? proto.prototype : proto; var instance = new Create(); Create.prototype = null; return instance; }; function validArg(arg){ if(!arg){ throw new Error("Compose arguments must be func...
Decorator.install = install; return Decorator; } Compose.Decorator = Decorator; // aspect applier function aspect(handler){ return function(advice){ return Decorator(function install(key){ var baseMethod = this[key]; (advice = this[key] = baseMethod ? handler(this, baseMethod, advice) : advice).i...
{ if(direct){ return direct.apply(this, arguments); } throw new Error("Decorator not applied"); }
identifier_body
compose.js
? proto.prototype : proto || Object.prototype); } : function(proto){ Create.prototype = typeof proto == "function" ? proto.prototype : proto; var instance = new Create(); Create.prototype = null; return instance; }; function validArg(arg){ if(!arg){ throw new Error("Compose arguments must be fu...
(){ var instance; if(this instanceof Constructor){ // called with new operator, can proceed as is instance = this; }else{ // we allow for direct calls without a new operator, in this case we need to // create the instance ourself. Create.prototype = prototype; instance = new Create(); ...
Constructor
identifier_name
strategies.py
""" Implementation of various trading strategies. """ from cointrol.core.models import ( Order, TradingSession, RelativeStrategyProfile, FixedStrategyProfile ) class TradeAction: BUY, SELL = Order.BUY, Order.SELL def __init__(self, action, price): self.action = action self.price = p...
class RelativeStrategy(BaseTradingStrategy): profile = None """:type: RelativeStrategyProfile""" def get_buy_price(self): return self.last_order.price * (self.profile.buy / 100) def get_sell_price(self): return self.last_order.price * (self.profile.sell / 100) # {Profile model cla...
profile = None """:type: FixedStrategyProfile""" def get_buy_price(self): return self.profile.buy def get_sell_price(self): return self.profile.sell
identifier_body
strategies.py
""" Implementation of various trading strategies. """ from cointrol.core.models import ( Order, TradingSession, RelativeStrategyProfile, FixedStrategyProfile ) class TradeAction: BUY, SELL = Order.BUY, Order.SELL def __init__(self, action, price): self.action = action self.price = p...
profile = None """:type: FixedStrategyProfile""" def get_buy_price(self): return self.profile.buy def get_sell_price(self): return self.profile.sell class RelativeStrategy(BaseTradingStrategy): profile = None """:type: RelativeStrategyProfile""" def get_buy_price(self): ...
random_line_split
strategies.py
""" Implementation of various trading strategies. """ from cointrol.core.models import ( Order, TradingSession, RelativeStrategyProfile, FixedStrategyProfile ) class TradeAction: BUY, SELL = Order.BUY, Order.SELL def __init__(self, action, price): self.action = action self.price = p...
def get_buy_price(self): raise NotImplementedError def get_sell_price(self): raise NotImplementedError class FixedStrategy(BaseTradingStrategy): profile = None """:type: FixedStrategyProfile""" def get_buy_price(self): return self.profile.buy def get_sell_price(sel...
return TradeAction(action=Order.SELL, price=self.get_sell_price())
conditional_block
strategies.py
""" Implementation of various trading strategies. """ from cointrol.core.models import ( Order, TradingSession, RelativeStrategyProfile, FixedStrategyProfile ) class TradeAction: BUY, SELL = Order.BUY, Order.SELL def __init__(self, action, price): self.action = action self.price = p...
(BaseTradingStrategy): profile = None """:type: FixedStrategyProfile""" def get_buy_price(self): return self.profile.buy def get_sell_price(self): return self.profile.sell class RelativeStrategy(BaseTradingStrategy): profile = None """:type: RelativeStrategyProfile""" de...
FixedStrategy
identifier_name
price-indicator.js
/* Highstock JS v9.0.1 (2021-02-15) Advanced Highstock tools (c) 2010-2021 Highsoft AS Author: Torstein Honsi License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/price-ind...
})});c(a,"masters/modules/price-indicator.src.js",[],function(){})}); //# sourceMappingURL=price-indicator.js.map
{var n=this.xAxis,b=this.yAxis,p=b.crosshair,q=b.cross,r=b.crossLabel,g=this.points,h=g.length,k=this.xData[this.xData.length-1],l=this.yData[this.yData.length-1];e&&e.enabled&&(b.crosshair=b.options.crosshair=a.lastPrice,b.cross=this.lastPrice,e=f(l)?l[3]:l,b.drawCrosshair(null,{x:k,y:e,plotX:n.toPixels(k,!0),plotY:b....
conditional_block
price-indicator.js
/* Highstock JS v9.0.1 (2021-02-15) Advanced Highstock tools (c) 2010-2021 Highsoft AS Author: Torstein Honsi License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/price-ind...
(a,d,c,f){a.hasOwnProperty(d)||(a[d]=f.apply(null,c))}a=a?a._modules:{};c(a,"Extensions/PriceIndication.js",[a["Core/Series/Series.js"],a["Core/Utilities.js"]],function(a, c){var d=c.addEvent,f=c.isArray,m=c.merge;d(a,"afterRender",function(){var a=this.options,c=a.pointRange,d=a.lastVisiblePrice,e=a.lastPrice;if((d||e...
c
identifier_name
price-indicator.js
/* Highstock JS v9.0.1 (2021-02-15) Advanced Highstock tools (c) 2010-2021 Highsoft AS Author: Torstein Honsi License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/price-ind...
a=a?a._modules:{};c(a,"Extensions/PriceIndication.js",[a["Core/Series/Series.js"],a["Core/Utilities.js"]],function(a, c){var d=c.addEvent,f=c.isArray,m=c.merge;d(a,"afterRender",function(){var a=this.options,c=a.pointRange,d=a.lastVisiblePrice,e=a.lastPrice;if((d||e)&&"highcharts-navigator-series"!==a.id){var n=this.xA...
{a.hasOwnProperty(d)||(a[d]=f.apply(null,c))}
identifier_body
price-indicator.js
/* Highstock JS v9.0.1 (2021-02-15) Advanced Highstock tools (c) 2010-2021 Highsoft AS Author: Torstein Honsi License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/price-ind...
//# sourceMappingURL=price-indicator.js.map
random_line_split
check-api-contrail-9081.py
# !/usr/bin/python # # Copyright 2016 Mirantis, 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 ...
(): signal.signal(signal.SIGCHLD, signal.SIG_DFL) def log_verbose(msg): collectd.info('%s plugin [verbose]: %s' % (plugin_name, msg)) def payload(): config = ConfigParser.RawConfigParser() config.read(CONF_FILE) API = OSAPI(config) payload = API.check_api(url, "contrail") return paylo...
restore_sigchld
identifier_name
check-api-contrail-9081.py
# !/usr/bin/python # # Copyright 2016 Mirantis, 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 ...
def payload_callback(): log_verbose('Read callback called') value = payload() # log_verbose( # 'Sending value: %s.%s=%s' % (plugin_name, '-'.join([val.plugin, val.type]), value)) val = collectd.Values( plugin=plugin_name, # metric source plugin_instance=plugin_instance, ...
config = ConfigParser.RawConfigParser() config.read(CONF_FILE) API = OSAPI(config) payload = API.check_api(url, "contrail") return payload
identifier_body
check-api-contrail-9081.py
# !/usr/bin/python # # Copyright 2016 Mirantis, 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 ...
print "Plugin: " + plugin_name payload = payload() print("%s" % (payload)) sys.exit(0) else: import collectd collectd.register_init(restore_sigchld) collectd.register_config(configure_callback) collectd.register_read(payload_callback, plugin_interval)
print "Please provide URL" sys.exit(1)
conditional_block
check-api-contrail-9081.py
# !/usr/bin/python # # Copyright 2016 Mirantis, 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 ...
sys.exit(1) def check_api(self, url, service): try: request = urllib2.Request( url, headers={ 'X-Auth-Token': self.token, }) start_time = time.time() p = urllib2.urlopen(request, timeout=self.get...
return except Exception as e: print("Got exception '%s'" % e)
random_line_split
template.component.ts
import { Component, ComponentFactoryResolver, ComponentRef, Input, OnChanges, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { JsonSchemaFormService } from '../library/json-schema-form.service'; @Component({ selector: 'template-widget', template: `<div #widgetContainer></div>`, }) export c...
if (this.newComponent) { for (let input of ['formID', 'layoutNode', 'layoutIndex', 'dataIndex']) { this.newComponent.instance[input] = this[input]; } } } }
{ this.newComponent = this.widgetContainer.createComponent( this.componentFactory.resolveComponentFactory(this.layoutNode.options.template) ); }
conditional_block
template.component.ts
import { Component, ComponentFactoryResolver, ComponentRef, Input, OnChanges, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { JsonSchemaFormService } from '../library/json-schema-form.service'; @Component({ selector: 'template-widget', template: `<div #widgetContainer></div>`, }) export c...
ngOnInit() { this.updateComponent(); } ngOnChanges() { this.updateComponent(); } private updateComponent() { if (!this.newComponent && this.layoutNode.options.template) { this.newComponent = this.widgetContainer.createComponent( this.componentFactory.resolveComponentFactory(this.la...
private jsf: JsonSchemaFormService ) { }
random_line_split
template.component.ts
import { Component, ComponentFactoryResolver, ComponentRef, Input, OnChanges, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { JsonSchemaFormService } from '../library/json-schema-form.service'; @Component({ selector: 'template-widget', template: `<div #widgetContainer></div>`, }) export c...
() { this.updateComponent(); } private updateComponent() { if (!this.newComponent && this.layoutNode.options.template) { this.newComponent = this.widgetContainer.createComponent( this.componentFactory.resolveComponentFactory(this.layoutNode.options.template) ); } if (this.newCom...
ngOnChanges
identifier_name
RotateLeft.js
/** * @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Moves the element at the start of the array to the end, shifting all items in the process. * The "rotation" happens to the left. * * @function Phaser.Utils.Array.RotateLeft * @since 3.0.0 * ...
random_line_split
RotateLeft.js
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Moves the element at the start of the array to the end, shifting all items in the process. * The "rotation" happens to the left. * * @...
return element; }; module.exports = RotateLeft;
{ element = array.shift(); array.push(element); }
conditional_block
domui.resizing.ts
/// <reference types="jquery" /> /// <reference types="jqueryui" /> /// <reference path="domui.jquery.d.ts" /> /// <reference path="domui.webui.ts" /> //import WebUI from "domui.webui.util"; namespace WebUI { /** * This adds a "resize" listener to the window, and every window "resize" it will call a method * to r...
$(middle).height(height+"px"); $(middle).css({"overflow-y": "auto"}); } export function autoHeight(flexid, bottom) { $(window).bind("resize", function() { autoHeightRecalc(flexid, bottom); }); autoHeightRecalc(flexid, bottom); } export function autoHeightRecalc(flexid, bottom) { var tbot = $(flex...
{ height = 0; }
conditional_block
domui.resizing.ts
/// <reference types="jquery" /> /// <reference types="jqueryui" /> /// <reference path="domui.jquery.d.ts" /> /// <reference path="domui.webui.ts" /> //import WebUI from "domui.webui.util"; namespace WebUI { /** * This adds a "resize" listener to the window, and every window "resize" it will call a method * to r...
theight = top; } //-- Get height of bottom, if present var bheight = 0; if(typeof bottom === "string") { bheight = $("#"+bottom).height(); } else if(bottom) { bheight = $(bottom).height(); } height -= theight - bheight; if(height < 0) { height = 0; } $(middle).height(height+"px"); $(m...
theight = $("#"+top).height(); // Get the end of the "top" element } else if(top) {
random_line_split
domui.resizing.ts
/// <reference types="jquery" /> /// <reference types="jqueryui" /> /// <reference path="domui.jquery.d.ts" /> /// <reference path="domui.webui.ts" /> //import WebUI from "domui.webui.util"; namespace WebUI { /** * This adds a "resize" listener to the window, and every window "resize" it will call a method * to r...
if(height < 0) { height = 0; } $(middle).height(height+"px"); $(middle).css({"overflow-y": "auto"}); } export function autoHeight(flexid, bottom) { $(window).bind("resize", function() { autoHeightRecalc(flexid, bottom); }); autoHeightRecalc(flexid, bottom); } export function autoHeightRecalc...
{ // try { middle = "#"+middle; var height = $(middle).parent().height(); // Assigned height of the container var theight = 0; if(typeof top === "string") { theight = $("#"+top).height(); // Get the end of the "top" element } else if(top) { theight = top; } //-- Get height of bottom, if pres...
identifier_body
domui.resizing.ts
/// <reference types="jquery" /> /// <reference types="jqueryui" /> /// <reference path="domui.jquery.d.ts" /> /// <reference path="domui.webui.ts" /> //import WebUI from "domui.webui.util"; namespace WebUI { /** * This adds a "resize" listener to the window, and every window "resize" it will call a method * to r...
(topid, flexid, bottom) { $(window).bind("resize", function() { recalculateAutoHeight(topid, flexid, bottom); }); recalculateAutoHeight(topid, flexid, bottom); } export function recalculateAutoHeight(topid, flexid, bottom) { try { var tbot = $(topid).offset().top + $(topid).height(); var height = $(...
autoHeightReset
identifier_name
get_user_by_email_address.py
#!/usr/bin/env python # # 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 requir...
(client, email_address): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. statement = (ad_manager.StatementBuilder(version='v201805') .Where('email = :email') .WithBindVariable('email', email_...
main
identifier_name
get_user_by_email_address.py
#!/usr/bin/env python # # 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 requir...
if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, EMAIL_ADDRESS)
user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. statement = (ad_manager.StatementBuilder(version='v201805') .Where('email = :email') .WithBindVariable('email', email_address)) # Retrieve a small amount of users at a time, pagi...
identifier_body
get_user_by_email_address.py
#!/usr/bin/env python # # 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 requir...
print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, EMAIL_ADDRESS)
else: break
random_line_split
get_user_by_email_address.py
#!/usr/bin/env python # # 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 requir...
statement.offset += statement.limit else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, EMAIL_ADDRESS)
print('User with ID "%d" and name "%s" was found.\n' % (user['id'], user['name']))
conditional_block
test_cromu70_caching.py
import nose from nose.plugins.attrib import attr import logging import colorguard import os bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) @attr(speed='slow') def test_cromu_00070_caching(): # Test exploitation of CROMU_00070 given an input which causes a leak. Th...
(): functions = globals() all_functions = dict(filter((lambda kv: kv[0].startswith('test_')), functions.items())) for f in sorted(all_functions.keys()): if hasattr(all_functions[f], '__call__'): all_functions[f]() if __name__ == "__main__": logging.getLogger("colorguard").setLevel("...
run_all
identifier_name
test_cromu70_caching.py
import nose from nose.plugins.attrib import attr import logging import colorguard import os bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) @attr(speed='slow') def test_cromu_00070_caching(): # Test exploitation of CROMU_00070 given an input which causes a leak. Th...
def run_all(): functions = globals() all_functions = dict(filter((lambda kv: kv[0].startswith('test_')), functions.items())) for f in sorted(all_functions.keys()): if hasattr(all_functions[f], '__call__'): all_functions[f]() if __name__ == "__main__": logging.getLogger("colorguard...
for _ in range(2): payload = bytes.fromhex("06000006020a00000000000000000000000c030c00000100e1f505000000000000eb") cg = colorguard.ColorGuard(os.path.join(bin_location, "tests/cgc/CROMU_00070"), payload) pov = cg.attempt_exploit() nose.tools.assert_not_equal(pov, None) nose.tool...
identifier_body
test_cromu70_caching.py
import nose from nose.plugins.attrib import attr import logging import colorguard import os bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) @attr(speed='slow')
for _ in range(2): payload = bytes.fromhex("06000006020a00000000000000000000000c030c00000100e1f505000000000000eb") cg = colorguard.ColorGuard(os.path.join(bin_location, "tests/cgc/CROMU_00070"), payload) pov = cg.attempt_exploit() nose.tools.assert_not_equal(pov, None) nose....
def test_cromu_00070_caching(): # Test exploitation of CROMU_00070 given an input which causes a leak. Then test that we can do it again restoring # from the cache.
random_line_split