text
stringlengths
2
6.14k
// // Lunar.h // // Lunar Unity Mobile Console // https://github.com/SpaceMadness/lunar-unity-console // // Copyright 2017 Alex Lementuev, SpaceMadness. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "LUUtils.h" #import "LUActionButton.h" #import "LUActionController.h" #import "LUActionRegistry.h" #import "LUConsole.h" #import "LUConsoleController.h" #import "LUConsoleLogController.h" #import "LUConsoleLogDetailsController.h" #import "LUConsoleLogEntry.h" #import "LUConsoleLogEntryList.h" #import "LUConsoleLogEntryLookupTable.h" #import "LUConsoleLogEntryTableViewCell.h" #import "LUConsoleLogMenuController.h" #import "LUConsoleLogTypeButton.h" #import "LUConsolePlugin.h" #import "LUConsolePluginSettings.h" #import "LUConsolePopupController.h" #import "LUConsoleResizeController.h" #import "LUConsoleSettingsController.h" #import "LUCVar.h" #import "LUEntry.h" #import "LUEntryTableViewCell.h" #import "LUExceptionWarningController.h" #import "LUPanViewGestureRecognizer.h" #import "LUPassTouchView.h" #import "LUSwitch.h" #import "LUSlider.h" #import "LUTableView.h" #import "LUTextField.h" #import "LUTheme.h" #import "LUToggleButton.h" #import "LUUnityScriptMessenger.h" #import "LUViewController.h" #import "LUWindow.h"
/**************************************************************************** * Copyright (C) 2014-2019 Jaroslaw Stanczyk <[email protected]>* * The source code presented on my lectures: "C Programming Language" * ****************************************************************************/ // Program to generate a table of prime numbers up to 50 - rewritten #include <stdio.h> #include <stdbool.h> int main (void) { int p, d; bool isPrime; for (p = 2; p <= 50; ++p) { isPrime = true; for (d = 2; d < p; ++d) if (p % d == 0) isPrime = false; if (isPrime) printf ("%i ", p); } printf ("\n"); return 0; } /* eof. */
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys from resource_management import * from shared_initialization import * class BeforeStartHook(Hook): def hook(self, env): import params self.run_custom_hook('before-ANY') env.set_params(params) setup_hadoop() setup_configs() create_javahome_symlink() if __name__ == "__main__": BeforeStartHook().execute()
#!/usr/bin/env python # # NEPI, a framework to manage network experiments # Copyright (C) 2013 INRIA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author: Alina Quereilhac <[email protected]> from nepi.execution.ec import ExperimentController ec = ExperimentController(exp_id = "ns3-local-p2p-ping") # Simulation will executed in the local machine node = ec.register_resource("linux::Node") ec.set(node, "hostname", "localhost") # Add a simulation resource simu = ec.register_resource("linux::ns3::Simulation") ec.set(simu, "verbose", True) ec.register_connection(simu, node) ## Add a ns-3 node with its protocol stack nsnode1 = ec.register_resource("ns3::Node") ec.register_connection(nsnode1, simu) ipv4 = ec.register_resource("ns3::Ipv4L3Protocol") ec.register_connection(nsnode1, ipv4) arp = ec.register_resource("ns3::ArpL3Protocol") ec.register_connection(nsnode1, arp) icmp = ec.register_resource("ns3::Icmpv4L4Protocol") ec.register_connection(nsnode1, icmp) # Add a point to point net device to the node dev1 = ec.register_resource("ns3::PointToPointNetDevice") ec.set(dev1, "ip", "10.0.0.1") ec.set(dev1, "prefix", "30") ec.register_connection(nsnode1, dev1) queue1 = ec.register_resource("ns3::DropTailQueue") ec.register_connection(dev1, queue1) ## Add another ns-3 node with its protocol stack nsnode2 = ec.register_resource("ns3::Node") ec.register_connection(nsnode2, simu) ipv4 = ec.register_resource("ns3::Ipv4L3Protocol") ec.register_connection(nsnode2, ipv4) arp = ec.register_resource("ns3::ArpL3Protocol") ec.register_connection(nsnode2, arp) icmp = ec.register_resource("ns3::Icmpv4L4Protocol") ec.register_connection(nsnode2, icmp) # Add a point to point net device to the node dev2 = ec.register_resource("ns3::PointToPointNetDevice") ec.set(dev2, "ip", "10.0.0.2") ec.set(dev2, "prefix", "30") ec.register_connection(nsnode2, dev2) queue2 = ec.register_resource("ns3::DropTailQueue") ec.register_connection(dev2, queue2) # Add a point to point channel chan = ec.register_resource("ns3::PointToPointChannel") ec.set(chan, "Delay", "0s") ec.register_connection(chan, dev1) ec.register_connection(chan, dev2) ### create pinger ping = ec.register_resource("ns3::V4Ping") ec.set (ping, "Remote", "10.0.0.2") ec.set (ping, "Interval", "1s") ec.set (ping, "Verbose", True) ec.set (ping, "StartTime", "0s") ec.set (ping, "StopTime", "20s") ec.register_connection(ping, nsnode1) ec.deploy() ec.wait_finished([ping]) stdout = ec.trace(simu, "stdout") ec.shutdown() print "PING OUTPUT", stdout
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2008-08-31 // Updated : 2008-08-31 // Licence : This source is under MIT License // File : test/core/type_mat2x3.cpp /////////////////////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> static int test_operators() { glm::mat2x3 l(1.0f); glm::mat2x3 m(1.0f); glm::vec2 u(1.0f); glm::vec3 v(1.0f); float x = 1.0f; glm::vec3 a = m * u; glm::vec2 b = v * m; glm::mat2x3 n = x / m; glm::mat2x3 o = m / x; glm::mat2x3 p = x * m; glm::mat2x3 q = m * x; bool R = m != q; bool S = m == l; return (S && !R) ? 0 : 1; } int main() { int Error = 0; Error += test_operators(); return Error; }
#!/usr/bin/env python # encoding: utf-8 import rest class ParamsError(rest.RestError): type = 'PARAMS_ERROR' message = 'Params Error' app = rest.RestApp() class UserResource(rest.RestResource): def GET(self, id): return {'id': id, 'username': 'Steve'} def POST(self, username, password): return {'id': 123} class BlogResource(rest.RestResource): @rest.as_method('GET') def get_one(self, id): if not id: raise ParamsError() return {'id': id, 'title': 'First Blog', 'text': 'blabla..'} @rest.as_method('GET') def get_user_blogs(self, user_id): return [ {'id': 1, 'title': 'aaa', 'text': '...'}, {'id': 2, 'title': 'bbb', 'text': '...'}, ] def DIGG(self, id): return {'id':id, 'is_digg':True} # Route Detail: # GET /user/123/ -> UserResource().GET(id=123) # GET /blog/123/ -> BlogResource().get_one(id=123) # POST /blog/123/_digg/ -> BlogResource().DIGG(id=123) # GET /user/123/blog/ -> BlogResource().get_user_blogs(user_id=123) app.map('user', UserResource) # or user decorator: @app.mapper('user') on UserResource instead app.map('blog', BlogResource) # embeded in django def django_view(request, path): import json method = request.method if method == 'GET': params = dict(request.GET.items()) else: params = json.loads(request.raw_post_data) resp = app.request(method, path, params, context=request) return json.dumps(resp, indent=2) if __name__ == '__main__': app.run(port=9888)
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import sys import TestSCons import os test = TestSCons.TestSCons() e = test.Environment() fooflags = e['SHCCFLAGS'] + ' -DFOO' barflags = e['SHCCFLAGS'] + ' -DBAR' if os.name == 'posix': os.environ['LD_LIBRARY_PATH'] = '.' if sys.platform.find('irix') > -1: os.environ['LD_LIBRARYN32_PATH'] = '.' test.write('SConstruct', """ foo = Environment(SHCCFLAGS = '%s', WINDOWS_INSERT_DEF=1) bar = Environment(SHCCFLAGS = '%s', WINDOWS_INSERT_DEF=1) foo_obj = foo.SharedObject(target = 'foo', source = 'prog.c') foo.SharedLibrary(target = 'foo', source = foo_obj) bar_obj = bar.SharedObject(target = 'bar', source = 'prog.c') bar.SharedLibrary(target = 'bar', source = bar_obj) fooMain = foo.Clone(LIBS='foo', LIBPATH='.') foomain_obj = fooMain.Object(target='foomain', source='main.c') fooMain.Program(target='fooprog', source=foomain_obj) barMain = bar.Clone(LIBS='bar', LIBPATH='.') barmain_obj = barMain.Object(target='barmain', source='main.c') barMain.Program(target='barprog', source=barmain_obj) """ % (fooflags, barflags)) test.write('foo.def', r""" LIBRARY "foo" DESCRIPTION "Foo Shared Library" EXPORTS doIt """) test.write('bar.def', r""" LIBRARY "bar" DESCRIPTION "Bar Shared Library" EXPORTS doIt """) test.write('prog.c', r""" #include <stdio.h> void doIt() { #ifdef FOO printf("prog.c: FOO\n"); #endif #ifdef BAR printf("prog.c: BAR\n"); #endif } """) test.write('main.c', r""" void doIt(); int main(int argc, char* argv[]) { doIt(); return 0; } """) test.run(arguments = '.') test.run(program = test.workpath('fooprog'), stdout = "prog.c: FOO\n") test.run(program = test.workpath('barprog'), stdout = "prog.c: BAR\n") test.write('SConstruct', """ bar = Environment(SHCCFLAGS = '%s', WINDOWS_INSERT_DEF=1) foo_obj = bar.SharedObject(target = 'foo', source = 'prog.c') bar.SharedLibrary(target = 'foo', source = foo_obj) bar_obj = bar.SharedObject(target = 'bar', source = 'prog.c') bar.SharedLibrary(target = 'bar', source = bar_obj) barMain = bar.Clone(LIBS='bar', LIBPATH='.') foomain_obj = barMain.Object(target='foomain', source='main.c') barmain_obj = barMain.Object(target='barmain', source='main.c') barMain.Program(target='barprog', source=foomain_obj) barMain.Program(target='fooprog', source=barmain_obj) """ % (barflags)) test.run(arguments = '.') test.run(program = test.workpath('fooprog'), stdout = "prog.c: BAR\n") test.run(program = test.workpath('barprog'), stdout = "prog.c: BAR\n") test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs Octane 2.0 javascript benchmark. Octane 2.0 is a modern benchmark that measures a JavaScript engine's performance by running a suite of tests representative of today's complex and demanding web applications. Octane's goal is to measure the performance of JavaScript code found in large, real-world web applications. Octane 2.0 consists of 17 tests, four more than Octane v1. """ import os from core import perf_benchmark from telemetry import page as page_module from telemetry.page import legacy_page_test from telemetry import story from telemetry.util import statistics from telemetry.value import scalar from metrics import power _GB = 1024 * 1024 * 1024 DESCRIPTIONS = { 'CodeLoad': 'Measures how quickly a JavaScript engine can start executing code ' 'after loading a large JavaScript program, social widget being a ' 'common example. The source for test is derived from open source ' 'libraries (Closure, jQuery) (1,530 lines).', 'Crypto': 'Encryption and decryption benchmark based on code by Tom Wu ' '(1698 lines).', 'DeltaBlue': 'One-way constraint solver, originally written in Smalltalk by John ' 'Maloney and Mario Wolczko (880 lines).', 'EarleyBoyer': 'Classic Scheme benchmarks, translated to JavaScript by Florian ' 'Loitsch\'s Scheme2Js compiler (4684 lines).', 'Gameboy': 'Emulate the portable console\'s architecture and runs a demanding 3D ' 'simulation, all in JavaScript (11,097 lines).', 'Mandreel': 'Runs the 3D Bullet Physics Engine ported from C++ to JavaScript via ' 'Mandreel (277,377 lines).', 'NavierStokes': '2D NavierStokes equations solver, heavily manipulates double ' 'precision arrays. Based on Oliver Hunt\'s code (387 lines).', 'PdfJS': 'Mozilla\'s PDF Reader implemented in JavaScript. It measures decoding ' 'and interpretation time (33,056 lines).', 'RayTrace': 'Ray tracer benchmark based on code by Adam Burmister (904 lines).', 'RegExp': 'Regular expression benchmark generated by extracting regular ' 'expression operations from 50 of the most popular web pages ' '(1761 lines).', 'Richards': 'OS kernel simulation benchmark, originally written in BCPL by Martin ' 'Richards (539 lines).', 'Splay': 'Data manipulation benchmark that deals with splay trees and exercises ' 'the automatic memory management subsystem (394 lines).', } class _OctaneMeasurement(legacy_page_test.LegacyPageTest): def __init__(self): super(_OctaneMeasurement, self).__init__() self._power_metric = None def CustomizeBrowserOptions(self, options): power.PowerMetric.CustomizeBrowserOptions(options) def WillStartBrowser(self, platform): self._power_metric = power.PowerMetric(platform) def WillNavigateToPage(self, page, tab): memory_stats = tab.browser.memory_stats if ('SystemTotalPhysicalMemory' in memory_stats and memory_stats['SystemTotalPhysicalMemory'] < 1 * _GB): skipBenchmarks = '"zlib"' else: skipBenchmarks = '' page.script_to_evaluate_on_commit = """ var __results = []; var __real_log = window.console.log; window.console.log = function(msg) { __results.push(msg); __real_log.apply(this, [msg]); } skipBenchmarks = [%s] """ % (skipBenchmarks) def DidNavigateToPage(self, page, tab): self._power_metric.Start(page, tab) def ValidateAndMeasurePage(self, page, tab, results): tab.WaitForJavaScriptExpression('window.completed', 10) tab.WaitForJavaScriptExpression( '!document.getElementById("progress-bar-container")', 1200) self._power_metric.Stop(page, tab) self._power_metric.AddResults(tab, results) results_log = tab.EvaluateJavaScript('__results') all_scores = [] for output in results_log: # Split the results into score and test name. # results log e.g., "Richards: 18343" score_and_name = output.split(': ', 2) assert len(score_and_name) == 2, \ 'Unexpected result format "%s"' % score_and_name if 'Skipped' not in score_and_name[1]: name = score_and_name[0] score = float(score_and_name[1]) results.AddValue(scalar.ScalarValue( results.current_page, name, 'score', score, important=False, description=DESCRIPTIONS.get(name))) # Collect all test scores to compute geometric mean. all_scores.append(score) total = statistics.GeometricMean(all_scores) results.AddSummaryValue( scalar.ScalarValue(None, 'Total.Score', 'score', total, description='Geometric mean of the scores of each ' 'individual benchmark in the Octane ' 'benchmark collection.')) class Octane(perf_benchmark.PerfBenchmark): """Google's Octane JavaScript benchmark. http://octane-benchmark.googlecode.com/svn/latest/index.html """ test = _OctaneMeasurement @classmethod def Name(cls): return 'octane' def CreateStorySet(self, options): ps = story.StorySet( archive_data_file='../page_sets/data/octane.json', base_dir=os.path.dirname(os.path.abspath(__file__)), cloud_storage_bucket=story.PUBLIC_BUCKET) ps.AddStory(page_module.Page( 'http://octane-benchmark.googlecode.com/svn/latest/index.html?auto=1', ps, ps.base_dir, make_javascript_deterministic=False)) return ps
import json from functools import wraps from django.utils.decorators import available_attrs from django.http import HttpResponse from django.template.loader import render_to_string import settings from django.core.cache import cache def json_view( view_func ): @wraps( view_func, assigned = available_attrs( view_func ) ) def _wrapped_view( request, *args, **kwargs ): response = view_func( request, *args, **kwargs ) status_code = 200 if isinstance( response, HttpResponse ): return response elif isinstance( response, tuple ): response, status_code = response if not isinstance( response, str ): response = json.dumps( response ) return HttpResponse( response, mimetype = 'application/json', status = status_code ) return _wrapped_view def cacheable( view_func ): @wraps( view_func, assigned = available_attrs( view_func ) ) def _wrapped_view( request, *args, **kwargs ): if request.method == 'GET': #key = settings.CACHE_PREFIX % (request.get_full_path(), 'ajax', request.is_ajax()) # cached = cache.get(key) #if cached: # print 'HIT CACHE' # return cached response = view_func( request, *args, **kwargs ) #cache.set(key, response, settings.CACHE_TIME) return response else: return view_func( request, *args, **kwargs ) return _wrapped_view
from __future__ import unicode_literals from django.test import TestCase from django.core.urlresolvers import reverse from django.test.client import RequestFactory from happenings.utils.common import get_net class GetNetTest(TestCase): def setUp(self): self.factory = RequestFactory() self.url = reverse('calendar:list') def test_valid_next(self): url = self.url + '?cal_next=1' req = self.factory.get(url) net = get_net(req) self.assertEqual(net, 1) def test_valid_prev(self): url = self.url + '?cal_prev=1' req = self.factory.get(url) net = get_net(req) self.assertEqual(net, -1) def test_invalid(self): url = self.url + '?cal_next=nann' req = self.factory.get(url) net = get_net(req) self.assertEqual(net, 0) def test_valid_next_and_prev(self): url = self.url + '?cal_next=1&cal_prev=2' req = self.factory.get(url) net = get_net(req) self.assertEqual(net, -1)
"""Python interface to GenoLogics LIMS via its REST API. Entities and their descriptors for the LIMS interface. Per Kraulis, Science for Life Laboratory, Stockholm, Sweden. Copyright (C) 2012 Per Kraulis """ import re from xml.etree import ElementTree _NSMAP = dict( art='http://genologics.com/ri/artifact', artgr='http://genologics.com/ri/artifactgroup', cnf='http://genologics.com/ri/configuration', con='http://genologics.com/ri/container', ctp='http://genologics.com/ri/containertype', exc='http://genologics.com/ri/exception', file='http://genologics.com/ri/file', inst='http://genologics.com/ri/instrument', lab='http://genologics.com/ri/lab', prc='http://genologics.com/ri/process', prj='http://genologics.com/ri/project', prop='http://genologics.com/ri/property', protcnf='http://genologics.com/ri/protocolconfiguration', protstepcnf='http://genologics.com/ri/stepconfiguration', prx='http://genologics.com/ri/processexecution', ptm='http://genologics.com/ri/processtemplate', ptp='http://genologics.com/ri/processtype', res='http://genologics.com/ri/researcher', ri='http://genologics.com/ri', rt='http://genologics.com/ri/routing', rtp='http://genologics.com/ri/reagenttype', kit='http://genologics.com/ri/reagentkit', lot='http://genologics.com/ri/reagentlot', smp='http://genologics.com/ri/sample', stg='http://genologics.com/ri/stage', stp='http://genologics.com/ri/step', udf='http://genologics.com/ri/userdefined', ver='http://genologics.com/ri/version', wkfcnf='http://genologics.com/ri/workflowconfiguration' ) for prefix, uri in _NSMAP.items(): ElementTree._namespace_map[uri] = prefix _NSPATTERN = re.compile(r'(\{)(.+?)(\})') def nsmap(tag): "Convert from normal XML-ish namespace tag to ElementTree variant." parts = tag.split(':') if len(parts) != 2: raise ValueError("no namespace specifier in tag") return "{%s}%s" % (_NSMAP[parts[0]], parts[1])
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. Shortest Path")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Shortest Path")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9a9c3169-beff-4dab-a364-7e8d179325cd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/delay'; import { UserModel } from './../../models/auth/user.model'; @Injectable() export class AuthService { auth_email: string; auth_token: string; auth_role: string; auth_id: string; auth_user: any; // customer_servicer_id : string; // customer_servicer_urlname : string; // store the URL so we can redirect after logging in redirectUrl: string; currentUser: UserModel; login(user) { localStorage.setItem('currentUser', JSON.stringify(user)); this.auth_email = user.username; this.auth_token = user.token; this.auth_role = user.role; this.auth_id = user._id; this.auth_user = user.user; localStorage.setItem('profilePicPath', JSON.stringify(user.user.profile_picture)); } isLoggedIn() { this.currentUser = JSON.parse(localStorage.getItem('currentUser')); if (this.currentUser) { //this.setBodyClass(); return true; }else { return false; } } getLoginUser() { this.currentUser = JSON.parse(localStorage.getItem('currentUser')); this.auth_email = this.currentUser.username; this.auth_token = this.currentUser.token; this.auth_role = this.currentUser.role; this.auth_id = this.currentUser._id; this.auth_user = this.currentUser.user; return this.currentUser; } // getUserProfile(user_data){ // this.customer_servicer_id = user_data._id; // this.customer_servicer_urlname = user_data.urlname; // } logout(): void { //this.removeBodyClass(); localStorage.removeItem('currentUser'); this.auth_email = ''; this.auth_token = ''; this.auth_role = ''; this.auth_id = ''; this.auth_user = ''; // this.customer_servicer_id = ''; // this.customer_servicer_urlname = ''; } }
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> */ #include "vertexbuffer.hpp" #include "renderdevice.hpp" uint32_t VertexBuffer::count() const { return size() / stride(); } uint32_t VertexBuffer::usedMemory() { return RenderDevice::instance().usedVertexBufferMemory(); } void VertexBuffer::bind(VertexBuffer* buffer, uint8_t slot, uint32_t offset) { RenderDevice::instance().bind(buffer, slot, offset); }
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com) # Author : Vincent Renaville from openerp.tools.translate import _ from openerp.osv import fields, osv class report_webkit_actions(osv.osv_memory): _name = "report.webkit.actions" _description = "Webkit Actions" _columns = { 'print_button':fields.boolean('Add print button', help="Check this to add a Print action for this Report in the sidebar of the corresponding document types"), 'open_action':fields.boolean('Open added action', help="Check this to view the newly added internal print action after creating it (technical view) "), } _defaults = { 'print_button': lambda *a: True, 'open_action': lambda *a: False, } def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Changes the view dynamically @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch of view. """ if not context: context = {} res = super(report_webkit_actions, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False) record_id = context and context.get('active_id', False) or False active_model = context.get('active_model') if not record_id or (active_model and active_model != 'ir.actions.report.xml'): return res report = self.pool['ir.actions.report.xml'].browse( cr, uid, context.get('active_id'), context=context ) ir_values_obj = self.pool['ir.values'] ids = ir_values_obj.search( cr, uid, [('value','=',report.type+','+str(context.get('active_id')))] ) if ids: res['arch'] = '''<form string="Add Print Buttons"> <label string="Report Action already exist for this report."/> </form> ''' return res def do_action(self, cr, uid, ids, context=None): """ This Function Open added Action. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of report.webkit.actions's ID @param context: A standard dictionary @return: Dictionary of ir.values form. """ if context is None: context = {} report_obj = self.pool['ir.actions.report.xml'] for current in self.browse(cr, uid, ids, context=context): report = report_obj.browse( cr, uid, context.get('active_id'), context=context ) if current.print_button: ir_values_obj = self.pool['ir.values'] res = ir_values_obj.set( cr, uid, 'action', 'client_print_multi', report.report_name, [report.model], 'ir.actions.report.xml,%d' % context.get('active_id', False), isobject=True ) else: ir_values_obj = self.pool['ir.values'] res = ir_values_obj.set( cr, uid, 'action', 'client_print_multi', report.report_name, [report.model,0], 'ir.actions.report.xml,%d' % context.get('active_id', False), isobject=True ) if res[0]: if not current.open_action: return {'type': 'ir.actions.act_window_close'} return { 'name': _('Client Actions Connections'), 'view_type': 'form', 'view_mode': 'form', 'res_id' : res[0], 'res_model': 'ir.values', 'view_id': False, 'type': 'ir.actions.act_window', }
<?php /** * TOP API: taobao.wlb.order.jz.consign request * * @author auto create * @since 1.0, 2016.02.23 */ class WlbOrderJzConsignRequest { /** * 安装收货人信息,如果为空,则取默认收货人信息 **/ private $insReceiverTo; /** * 安装公司信息,需要安装时,才填写 **/ private $insTpDto; /** * 家装收货人信息,如果为空,则取默认收货信息 **/ private $jzReceiverTo; /** * 发货参数 **/ private $jzTopArgs; /** * 物流公司信息 **/ private $lgTpDto; /** * 卖家联系人地址库ID,可以通过taobao.logistics.address.search接口查询到地址库ID。如果为空,取的卖家的默认取货地址 **/ private $senderId; /** * 交易号 **/ private $tid; private $apiParas = array(); public function setInsReceiverTo($insReceiverTo) { $this->insReceiverTo = $insReceiverTo; $this->apiParas["ins_receiver_to"] = $insReceiverTo; } public function getInsReceiverTo() { return $this->insReceiverTo; } public function setInsTpDto($insTpDto) { $this->insTpDto = $insTpDto; $this->apiParas["ins_tp_dto"] = $insTpDto; } public function getInsTpDto() { return $this->insTpDto; } public function setJzReceiverTo($jzReceiverTo) { $this->jzReceiverTo = $jzReceiverTo; $this->apiParas["jz_receiver_to"] = $jzReceiverTo; } public function getJzReceiverTo() { return $this->jzReceiverTo; } public function setJzTopArgs($jzTopArgs) { $this->jzTopArgs = $jzTopArgs; $this->apiParas["jz_top_args"] = $jzTopArgs; } public function getJzTopArgs() { return $this->jzTopArgs; } public function setLgTpDto($lgTpDto) { $this->lgTpDto = $lgTpDto; $this->apiParas["lg_tp_dto"] = $lgTpDto; } public function getLgTpDto() { return $this->lgTpDto; } public function setSenderId($senderId) { $this->senderId = $senderId; $this->apiParas["sender_id"] = $senderId; } public function getSenderId() { return $this->senderId; } public function setTid($tid) { $this->tid = $tid; $this->apiParas["tid"] = $tid; } public function getTid() { return $this->tid; } public function getApiMethodName() { return "taobao.wlb.order.jz.consign"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkNotNull($this->tid,"tid"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
import * as React from 'react'; import { StandardProps } from '..'; export interface ListProps extends StandardProps<React.HTMLAttributes<HTMLUListElement>, ListClassKey> { component?: React.ReactType<ListProps>; dense?: boolean; disablePadding?: boolean; subheader?: React.ReactElement<any>; } export type ListClassKey = 'root' | 'padding' | 'dense' | 'subheader'; declare const List: React.ComponentType<ListProps>; export default List;
package com.borneq.usesevenzipjbind; import java.io.IOException; import java.io.RandomAccessFile; import net.sf.sevenzipjbinding.ArchiveFormat; import net.sf.sevenzipjbinding.ISevenZipInArchive; import net.sf.sevenzipjbinding.SevenZip; import net.sf.sevenzipjbinding.SevenZipException; import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; public class PrintCountOfItems { public static int getCount(String archiveFilename) { RandomAccessFile randomAccessFile = null; ISevenZipInArchive inArchive = null; try { randomAccessFile = new RandomAccessFile(archiveFilename, "r"); inArchive = SevenZip.openInArchive(null, // autodetect archive type new RandomAccessFileInStream(randomAccessFile)); ArchiveFormat archiveFormat = inArchive.getArchiveFormat(); System.out.printf("%s --->", archiveFormat.toString()); return inArchive.getNumberOfItems(); } catch (Exception e) { return -1; } finally { if (inArchive != null) { try { inArchive.close(); } catch (SevenZipException e) { System.err.println("Error closing archive: " + e); } } if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { System.err.println("Error closing file: " + e); } } } } }
# -*- coding: utf-8 -*- from django.contrib.auth.middleware import RemoteUserMiddleware from django.core.exceptions import ImproperlyConfigured from django.core import signals from django.db import close_connection from django.contrib import auth class WebtestUserMiddleware(RemoteUserMiddleware): """ Middleware for utilizing django-webtest simplified auth ('user' arg for self.app.post and self.app.get). Mostly copied from RemoteUserMiddleware, but the auth backend is changed (by changing ``auth.authenticate`` arguments) in order to keep RemoteUser backend untouched during django-webtest auth. """ header = "WEBTEST_USER" def process_request(self, request): # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise ImproperlyConfigured( "The django-webtest auth middleware requires the " "'django.contrib.auth.middleware.AuthenticationMiddleware' " "to be installed. Add it to your MIDDLEWARE_CLASSES setting " "or disable django-webtest auth support " "by setting 'setup_auth' property of your WebTest subclass " "to False." ) try: username = request.META[self.header] except KeyError: # If specified header doesn't exist then return (leaving # request.user set to AnonymousUser by the # AuthenticationMiddleware). return # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. if request.user.is_authenticated(): if request.user.username == self.clean_username(username, request): return # We are seeing this user for the first time in this session, attempt # to authenticate the user. user = auth.authenticate(django_webtest_user=username) if user: # User is valid. Set request.user and persist user in the session # by logging the user in. request.user = user auth.login(request, user) class DisableCSRFCheckMiddleware(object): def process_request(self, request): request._dont_enforce_csrf_checks = True class DjangoWsgiFix(object): """Django closes the database connection after every request; this breaks the use of transactions in your tests. This wraps around Django's WSGI interface and will disable the critical signal handler for every request served. Note that we really do need to do this individually a every request, not just once when our WSGI hook is installed, since Django's own test client does the same thing; it would reinstall the signal handler if used in combination with us. From django-test-utils. Note: that's WSGI middleware, not django's. """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): signals.request_finished.disconnect(close_connection) try: return self.app(environ, start_response) finally: signals.request_finished.connect(close_connection)
#!/usr/bin/python # -*- coding: ISO-8859-15 -*- # ============================================================================= # Copyright (c) 2009 Tom Kralidis # # Authors : Tom Kralidis <[email protected]> # # Contact email: [email protected] # ============================================================================= """ API for OGC Filter Encoding (FE) constructs and metadata. Filter Encoding: http://www.opengeospatial.org/standards/filter Currently supports version 1.1.0 (04-095). """ from owslib.etree import etree from owslib import util # default variables schema = 'http://schemas.opengis.net/filter/1.1.0/filter.xsd' namespaces = { None : 'http://www.opengis.net/ogc', 'gml': 'http://www.opengis.net/gml', 'ogc': 'http://www.opengis.net/ogc', 'xs' : 'http://www.w3.org/2001/XMLSchema', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance' } schema_location = '%s %s' % (namespaces['ogc'], schema) class FilterRequest(object): """ filter class """ def __init__(self, version='1.1.0'): """ filter Constructor Parameters ---------- - parent: parent etree.Element object (default is None) - version: version (default is '1.1.0') """ self.version = version def setfilter(self, parent=None): if parent is None: tmp = etree.Element(util.nspath('Filter', namespaces['ogc'])) tmp.set(util.nspath('schemaLocation', namespaces['xsi']), schema_location) return tmp else: etree.SubElement(parent, util.nspath('Filter', namespaces['ogc'])) def setpropertyisequalto(self, parent, propertyname, literal, matchcase=True): """ construct a PropertyIsEqualTo Parameters ---------- - parent: parent etree.Element object - propertyname: the PropertyName - literal: the Literal value - matchcase: whether to perform a case insensitve query (default is True) """ tmp = etree.SubElement(parent, util.nspath('PropertyIsEqualTo', namespaces['ogc'])) if matchcase is False: tmp.set('matchCase', 'false') etree.SubElement(tmp, util.nspath('PropertyName', namespaces['ogc'])).text = propertyname etree.SubElement(tmp, util.nspath('Literal', namespaces['ogc'])).text = literal def setbbox(self, parent, bbox): """ construct a BBOX search predicate Parameters ---------- - parent: parent etree.Element object - bbox: the bounding box in the form [minx,miny,maxx,maxy] """ tmp = etree.SubElement(parent, util.nspath('BBOX', namespaces['ogc'])) etree.SubElement(tmp, util.nspath('PropertyName', namespaces['ogc'])).text = 'ows:BoundingBox' tmp2 = etree.SubElement(tmp, util.nspath('Envelope', namespaces['gml'])) etree.SubElement(tmp2, util.nspath('lowerCorner', namespaces['gml'])).text = '%s %s' % (bbox[0], bbox[1]) etree.SubElement(tmp2, util.nspath('upperCorner', namespaces['gml'])).text = '%s %s' % (bbox[2], bbox[3]) def setpropertyislike(self, parent, propertyname, literal, wildcard='%', singlechar='_', escapechar='\\'): """ construct a PropertyIsLike Parameters ---------- - parent: parent etree.Element object - propertyname: the PropertyName - literal: the Literal value - wildcard: the wildCard character (default is '%') - singlechar: the singleChar character (default is '_') - escapechar: the escapeChar character (default is '\') """ tmp = etree.SubElement(parent, util.nspath('PropertyIsLike', namespaces['ogc'])) tmp.set('wildCard', wildcard) tmp.set('singleChar', singlechar) tmp.set('escapeChar', escapechar) etree.SubElement(tmp, util.nspath('PropertyName', namespaces['ogc'])).text = propertyname etree.SubElement(tmp, util.nspath('Literal', namespaces['ogc'])).text = literal def setsortby(self, parent, propertyname, order='ASC'): """ constructs a SortBy element Parameters ---------- - parent: parent etree.Element object - propertyname: the PropertyName - order: the SortOrder (default is 'ASC') """ tmp = etree.SubElement(parent, util.nspath('SortBy', namespaces['ogc'])) tmp2 = etree.SubElement(tmp, util.nspath('SortProperty', namespaces['ogc'])) etree.SubElement(tmp2, util.nspath('PropertyName', namespaces['ogc'])).text = propertyname etree.SubElement(tmp2, util.nspath('SortOrder', namespaces['ogc'])).text = order class FilterCapabilities(object): """ Abstraction for Filter_Capabilities """ def __init__(self, elem): # Spatial_Capabilities self.spatial_operands = [f.text for f in elem.findall(util.nspath('Spatial_Capabilities/GeometryOperands/GeometryOperand', namespaces['ogc']))] self.spatial_operators = [] for f in elem.findall(util.nspath('Spatial_Capabilities/SpatialOperators/SpatialOperator', namespaces['ogc'])): self.spatial_operators.append(f.attrib['name']) # Temporal_Capabilities self.temporal_operands = [f.text for f in elem.findall(util.nspath('Temporal_Capabilities/TemporalOperands/TemporalOperand', namespaces['ogc']))] self.temporal_operators = [] for f in elem.findall(util.nspath('Temporal_Capabilities/TemporalOperators/TemporalOperator', namespaces['ogc'])): self.temporal_operators.append(f.attrib['name']) # Scalar_Capabilities self.scalar_comparison_operators = [f.text for f in elem.findall(util.nspath('Scalar_Capabilities/ComparisonOperators/ComparisonOperator', namespaces['ogc']))]
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.metron.enrichment.stellar; import org.apache.metron.enrichment.cache.ObjectCache; import org.apache.metron.enrichment.cache.ObjectCacheConfig; import org.apache.metron.stellar.dsl.Context; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.apache.metron.enrichment.cache.ObjectCacheConfig.OBJECT_CACHE_EXPIRATION_KEY; import static org.apache.metron.enrichment.cache.ObjectCacheConfig.OBJECT_CACHE_MAX_FILE_SIZE_KEY; import static org.apache.metron.enrichment.cache.ObjectCacheConfig.OBJECT_CACHE_SIZE_KEY; import static org.apache.metron.enrichment.cache.ObjectCacheConfig.OBJECT_CACHE_TIME_UNIT_KEY; import static org.apache.metron.enrichment.stellar.EnrichmentObjectGet.ENRICHMENT_OBJECT_GET_SETTINGS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; @RunWith(PowerMockRunner.class) @PrepareForTest({EnrichmentObjectGet.class, ObjectCache.class}) public class EnrichmentObjectGetTest { @Rule public ExpectedException thrown = ExpectedException.none(); private EnrichmentObjectGet enrichmentObjectGet; private ObjectCache objectCache; private Context context; @Before public void setup() throws Exception { enrichmentObjectGet = new EnrichmentObjectGet(); objectCache = mock(ObjectCache.class); context = new Context.Builder() .with(Context.Capabilities.GLOBAL_CONFIG, HashMap::new) .build(); whenNew(ObjectCache.class).withNoArguments().thenReturn(objectCache); } @Test public void shouldInitializeWithDefaultSettings() throws Exception { when(objectCache.isInitialized()).thenReturn(true); enrichmentObjectGet.initialize(context); ObjectCacheConfig expectedConfig = new ObjectCacheConfig(new HashMap<>()); verify(objectCache, times(1)).initialize(expectedConfig); assertTrue(enrichmentObjectGet.isInitialized()); } @Test public void shouldInitializeWithCustomSettings() throws Exception { Map<String, Object> globalConfig = new HashMap<String, Object>() {{ put(ENRICHMENT_OBJECT_GET_SETTINGS, new HashMap<String, Object>() {{ put(OBJECT_CACHE_SIZE_KEY, 1); put(OBJECT_CACHE_EXPIRATION_KEY, 2); put(OBJECT_CACHE_TIME_UNIT_KEY, "SECONDS"); put(OBJECT_CACHE_MAX_FILE_SIZE_KEY, 3); }}); }}; when(objectCache.isInitialized()).thenReturn(true); context = new Context.Builder() .with(Context.Capabilities.GLOBAL_CONFIG, () -> globalConfig) .build(); assertFalse(enrichmentObjectGet.isInitialized()); enrichmentObjectGet.initialize(context); ObjectCacheConfig expectedConfig = new ObjectCacheConfig(new HashMap<>()); expectedConfig.setCacheSize(1); expectedConfig.setCacheExpiration(2); expectedConfig.setTimeUnit(TimeUnit.SECONDS); expectedConfig.setMaxFileSize(3); verify(objectCache, times(1)).initialize(expectedConfig); assertTrue(enrichmentObjectGet.isInitialized()); } @Test public void shouldApplyEnrichmentObjectGet() { Map<String, Object> enrichment = new HashMap<String, Object>() {{ put("key", "value"); }}; when(objectCache.get("/path")).thenReturn(enrichment); assertNull(enrichmentObjectGet.apply(Arrays.asList("/path", "key"), context)); when(objectCache.isInitialized()).thenReturn(true); enrichmentObjectGet.initialize(context); assertNull(enrichmentObjectGet.apply(Arrays.asList(null, null), context)); assertEquals("value", enrichmentObjectGet.apply(Arrays.asList("/path", "key"), context)); } @Test public void shouldThrowExceptionOnIncorrectObjectFormat() { thrown.expect(ClassCastException.class); thrown.expectMessage("The object stored in HDFS at '/path' must be serialized in JSON format."); when(objectCache.get("/path")).thenReturn("incorrect format"); when(objectCache.isInitialized()).thenReturn(true); enrichmentObjectGet.initialize(context); enrichmentObjectGet.apply(Arrays.asList("/path", "key"), context); } @Test public void restGetShouldThrownExceptionOnMissingParameter() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("All parameters are mandatory, submit 'hdfs path', 'indicator'"); enrichmentObjectGet.apply(new ArrayList<>(), context); } }
#!/usr/bin/env python # -*- coding: utf-8 -*- """Provides unit tests for the APT backend.""" # Copyright (C) 2011 Sebastian Heinlein <[email protected]> # # Licensed under the GNU General Public License Version 2 # # 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 program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Licensed under the GNU General Public License Version 2 __author__ = "Sebastian Heinlein <[email protected]>" import os import unittest import apt_pkg import mox from core import get_tests_dir, Chroot from packagekit import enums import aptBackend REPO_PATH = os.path.join(get_tests_dir(), "repo") class GetUpdatesTests(mox.MoxTestBase): """Test cases for detecting available updates.""" def setUp(self): mox.MoxTestBase.setUp(self) self.chroot = Chroot() self.chroot.setup() self.chroot.install_debfile(os.path.join(REPO_PATH, "silly-base_0.1-0_all.deb")) self.addCleanup(self.chroot.remove) self.backend = aptBackend.PackageKitAptBackend([]) def _catch_callbacks(self, *args): methods = list(args) methods.extend(("error", "finished")) for meth in methods: self.mox.StubOutWithMock(self.backend, meth) def test_get_updates(self): """Test checking for updates.""" self._catch_callbacks("package") self.backend.package("silly-base;0.1-0update1;all;", enums.INFO_NORMAL, mox.IsA(str)) self.backend.finished() self.mox.ReplayAll() self.chroot.add_test_repository() self.backend._open_cache() self.backend.dispatch_command("get-updates", ["None"]) def test_get_security_updates(self): """Test checking for security updates.""" self._catch_callbacks("package") self.backend.package("silly-base;0.1-0update1;all;Debian-Security", enums.INFO_SECURITY, "working package") self.backend.finished() self.mox.ReplayAll() self.chroot.add_repository(os.path.join(get_tests_dir(), "repo/security")) self.backend._open_cache() self.backend.dispatch_command("get-updates", ["None"]) def test_get_backports(self): """Test checking for backports.""" self._catch_callbacks("package") self.backend.package("silly-base;0.1-0update1;all;", enums.INFO_ENHANCEMENT, "working package") self.backend.finished() self.mox.ReplayAll() self.chroot.add_repository(os.path.join(get_tests_dir(), "repo/backports")) self.backend._open_cache() self.backend.dispatch_command("get-updates", ["None"]) if __name__ == "__main__": unittest.main() # vim: ts=4 et sts=4
/* MPI program that uses a monte carlo method to compute the value of PI */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdio.h> #include <mpi.h> #include <time.h> #define USE_MPI #define PI 3.14159265358979323 #define DEBUG 0 /* Define the max number of accurate values until termination*/ #define MAX 10 double get_eps(void); int main(int argc, char *argv[]) { double x, y; int i; int count= 0, mycount; /* # of points in the 1st quadrant of unit circle */ double z; double pi = 0.0; int myid, numprocs, proc; MPI_Status status; int master = 0; int tag = 123; long int myiter = 1; int done = 0; long int iterval = 1000000; /* how many points per iteration to increase */ long int niter = iterval; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); srand48(time(NULL)*myid); double epsilon; // if(myid==0)epsilon=get_eps(); if (argc <= 1) { fprintf(stderr,"Usage: monte_pi_mpi epsilon(0.0001)\n"); MPI_Finalize(); exit(-1); } epsilon = atof(argv[1]); while(done != MAX){ mycount = 0; myiter= niter/numprocs; /* initialize random numbers */ for (i = 0; i < myiter; i++) { x = (double)drand48(); y = (double)drand48(); z = x*x + y*y; if (z <= 1) mycount++; } if (myid == 0) { /* if I am the master process gather results from others */ count = mycount; for (proc = 1; proc<numprocs; proc++) { MPI_Recv(&mycount,1,MPI_INT,proc,tag,MPI_COMM_WORLD,&status); count += mycount; } pi = (double)count/(myiter*numprocs)*4; /* 4 quadrants of circle */ if (DEBUG) printf("procs= %d, trials= %ld, estimate= %2.10f, PI= %2.10f, error= %2.10f \n", numprocs,myiter*numprocs,pi, PI,fabs(pi-PI)); if (fabs(pi - PI) <= (epsilon * fabs(pi))) { printf("\n# (%d) Accuracy Met: iters = %ld, PI= %2.10f, pi= %2.10f, error= %2.10f, eps= %2.10f\n", done,numprocs*myiter,PI,pi,fabs(pi-PI),epsilon); done++; } /* Tell everyone we are done*/ MPI_Bcast(&done,1,MPI_INT,myid,MPI_COMM_WORLD); } else { /* for all the slave processes send results to the master */ /* printf("Processor %d sending results= %d to master process\n",myid,mycount); */ MPI_Send(&mycount,1,MPI_INT,master,tag,MPI_COMM_WORLD); /* Have we received a done command */ MPI_Bcast(&done,1,MPI_INT,0,MPI_COMM_WORLD); } } MPI_Finalize(); return 0; } /* get machine epsilon */ double get_eps(){ double xxeps=1.0; int i; for(i=1; i<55; i++) { /* we know about 52 bits */ xxeps=xxeps/2.0; if(1.0-xxeps == 1.0) break; } xxeps=2.0*xxeps; printf("type double eps=%24.17E \n", xxeps); return xxeps; }
'use strict'; function WorkbenchSrvs() { this.presets = [ { width: null, height: null, name: 'None' }, { width: '768px', height: '1024px', name: 'iPad' }, { width: '320px', height: '480px', name: 'iPhone 4' }, { width: '320px', height: '568px', name: 'iPhone 5' }, { width: '375px', height: '667px', name: 'iPhone 6' }, { width: '360px', height: '640px', name: 'Nexus 5' } ]; this.isRotated = false; this.selectedSize = this.presets[0]; } module.exports = WorkbenchSrvs;
'use strict'; var events = require('events'); var util = require('util'); var sinon = require('sinon'); var errors = {}; /* SFTPStream mock */ function SFTPStreamMock() { sinon.spy(this, 'createReadStream'); sinon.spy(this, 'createWriteStream'); sinon.spy(this, 'fastGet'); sinon.spy(this, 'fastPut'); sinon.spy(this, 'mkdir'); sinon.spy(this, 'readdir'); sinon.spy(this, 'rmdir'); sinon.spy(this, 'unlink'); } SFTPStreamMock.prototype.createReadStream = function (path, options) { return {readable: true, path: path, options: options}; }; SFTPStreamMock.prototype.createWriteStream = function (path, options) { return {writable: true, path: path, options: options}; }; SFTPStreamMock.prototype.fastGet = function (remote, local, callback) { return errors.hasOwnProperty('fastGet') ? callback(errors.fastGet) : callback(null); }; SFTPStreamMock.prototype.fastPut = function (local, remote, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } return errors.hasOwnProperty('fastPut') ? callback(errors.fastPut) : callback(null); }; SFTPStreamMock.prototype.mkdir = function (path, mode, callback) { if (typeof mode === 'function') { callback = mode; mode = null; } return errors.hasOwnProperty('mkdir') ? callback(errors.mkdir) : callback(null); }; SFTPStreamMock.prototype.readdir = function (path, callback) { if (errors.hasOwnProperty('readdir')) { return callback(errors.readdir); } return callback(null, [ {filename: 'file1'}, {filename: 'file2'}, {filename: 'file3'}, {filename: 'file4'}, {filename: 'file5'}, {filename: 'file6'} ]); }; SFTPStreamMock.prototype.rmdir = function (path, callback) { return errors.hasOwnProperty('rmdir') ? callback(errors.rmdir) : callback(null); }; SFTPStreamMock.prototype.unlink = function (path, callback) { return errors.hasOwnProperty('unlink') ? callback(errors.unlink) : callback(null); }; /* ssh2 Client mock */ function ClientMock(options) { this.options = options; sinon.spy(this, 'connect'); sinon.spy(this, 'sftp'); sinon.spy(this, 'end'); } util.inherits(ClientMock, events.EventEmitter); ClientMock.prototype.connect = function () { if (errors.hasOwnProperty('connect')) { this.emit('error', errors.connect); } else { this.emit('ready'); } }; ClientMock.prototype.sftp = function (callback) { if (errors.hasOwnProperty('sftp')) { return callback(errors.sftp); } return callback(null, new SFTPStreamMock()); }; ClientMock.prototype.end = function () { return null; }; module.exports = { Client: ClientMock, setError: function (method, error) { errors[method] = error; }, clear: function () { errors = {}; } };
/* * Copyright (c) 2007, Rutgers, The State University of New Jersey. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Rutgers, The State University of New Jersey, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY Rutgers, The State University of New Jersey * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Rutgers, The State University of * New Jersey BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: Vivek Pathak * Wed Mar 21 02:43:10 EDT 2007 * * */ #ifndef __CONFIG_FILE_H__ #define __CONFIG_FILE_H__ #include <string> #include <map> #include "regex.h" /* *------------------------------------------------------------------------ * Read only configuration file * * Configuration parameters have name = value format * Configuration parameters exist within sections * * Test if exists * Get default value * support int, float, string, char * Assert validity i.e. duplicates */ class ConfigFile { std::map<std::string, std::map<std::string, std::string> > section_config_value_map; bool nofile; bool invalid; regex_t commentexpr; regex_t namevalueexpr; regex_t namestringexpr; regex_t sectionexpr; public: ConfigFile() ; ~ConfigFile(); bool Init (std::string filename); std::string GetStringValue (std::string section, std::string name, std::string default_value, bool * found = 0) ; long GetNumericValue (std::string section, std::string name, long default_value, bool * found = 0) ; float GetStringValue (std::string section, std::string name, float default_value, bool * found = 0) ; }; #endif
/* * Copyright (C) 2014-2015 CS-SI ([email protected]) * Copyright (C) 2013-2015 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.s2tbx.dataio.s2.ortho.plugins; import org.esa.s2tbx.dataio.s2.ortho.S2OrthoProduct60MReaderPlugIn; /** * Reader plugin for S2 MSI L1C over WGS84 / UTM Zone 14 S */ public class Sentinel2L1CProduct_60M_UTM14S_ReaderPlugIn extends S2OrthoProduct60MReaderPlugIn { @Override public String getEPSG() { return "EPSG:32714"; } }
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## from unittest.mock import patch from attribution.models.attribution_new import AttributionNew from attribution.tests.factories.attribution_charge_new import AttributionChargeNewFactory from attribution.tests.factories.attribution_new import AttributionNewFactory from base.tests.factories.learning_component_year import LecturingLearningComponentYearFactory, \ PracticalLearningComponentYearFactory from base.tests.factories.learning_unit_year import LearningUnitYearFullFactory, LearningUnitYearPartimFactory from base.tests.factories.person import PersonWithPermissionsFactory from base.views.mixins import RulesRequiredMixin class TestChargeRepartitionMixin: @classmethod def setUpTestData(cls): cls.learning_unit_year = LearningUnitYearPartimFactory() cls.lecturing_component = LecturingLearningComponentYearFactory(learning_unit_year=cls.learning_unit_year) cls.practical_component = PracticalLearningComponentYearFactory(learning_unit_year=cls.learning_unit_year) cls.full_learning_unit_year = LearningUnitYearFullFactory( learning_container_year=cls.learning_unit_year.learning_container_year, academic_year=cls.learning_unit_year.academic_year ) cls.lecturing_component_full = LecturingLearningComponentYearFactory( learning_unit_year=cls.full_learning_unit_year ) cls.practical_component_full = PracticalLearningComponentYearFactory( learning_unit_year=cls.full_learning_unit_year ) cls.person = PersonWithPermissionsFactory('can_access_learningunit') def setUp(self): self.attribution = AttributionNewFactory( learning_container_year=self.learning_unit_year.learning_container_year ) attribution_id = self.attribution.id self.charge_lecturing = AttributionChargeNewFactory( attribution=self.attribution, learning_component_year=self.lecturing_component ) self.charge_practical = AttributionChargeNewFactory( attribution=self.attribution, learning_component_year=self.practical_component ) self.attribution_full = self.attribution self.attribution_full.id = None self.attribution_full.save() self.charge_lecturing_full = AttributionChargeNewFactory( attribution=self.attribution_full, learning_component_year=self.lecturing_component_full ) self.charge_practical_full = AttributionChargeNewFactory( attribution=self.attribution_full, learning_component_year=self.practical_component_full ) self.attribution = AttributionNew.objects.get(id=attribution_id) self.client.force_login(self.person.user) self.patcher = patch.object(RulesRequiredMixin, "test_func", return_value=True) self.mocked_permission_function = self.patcher.start() self.addCleanup(self.patcher.stop) def clean_partim_charges(self): self.charge_practical.delete() self.charge_lecturing.delete() self.attribution.delete()
#!/usr/bin/env python # Copyright (C) 2014-2015 Thomas Huang # # 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, version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class Connection(object): """Base Database Connection class :param db_options: db optional configuration, defaults to None :type db_options: dict, optional """ def __init__(self, db_options=None): db_options = db_options or {} #: database optional configuration, defaults to None self._db_options = self.default_options() self._db_options.update(db_options) #: database real connection self._connect = None self.initialize() def initialize(self): """Initialize customize configuration in subclass""" pass def default_options(self): """Defalut options for intailize sql connection""" return {} def connect(self): """connects database""" raise NotImplementedError('Must implement connect in Subclass') def close(self): """Close connect""" if self._connect is not None: self._connect.close() self._connect = None def ensure_connect(self): """Ensure the connetion is useable""" raise NotImplementedError('Must implement ensure_connect in Subclass') def cursor(self, as_dict=False): """Gets the cursor by type , if ``as_dict is ture, make a dict sql connection cursor""" self.ensure_connect() ctype = self.real_ctype(as_dict) return self._connect.cursor(ctype) def real_ctype(self, as_dict): """The real sql cursor type""" raise NotImplementedError('Must implement real_ctype in Subclass') def driver(self): """Get database driver""" return None def commit(self): """Commit batch execute""" self._connect.commit() def rollback(self): """Rollback database process""" self._connect.rollback() def autocommit(self, enable=True): """Sets commit to auto if True""" self._connect.autocommit(enable)
<?php /** * @author: gareth */ namespace SWCO\AppNexusAPI; abstract class AbstractCoreService extends AbstractService { protected $id; /** * @return boolean */ public function supportsSince() { return true; } /** * @return string */ public function getRequestVerb() { return 'get'; } /** * @return int */ public function getId() { return $this->id; } }
# Copyright 2014 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for address logic.""" import datetime import unittest from melange.logic import education as education_logic from melange.models import education as education_model TEST_SCHOOL_ID = 'school_id' TEST_SCHOOL_COUNTRY = 'United States' TEST_EXPECTED_GRADUATION = datetime.date.today().year + 1 TEST_MAJOR = 'Test Major' TEST_DEGREE = education_model.Degree.MASTERS class CreatePostSecondaryEducationTest(unittest.TestCase): """Unit tests for createPostSecondaryEducation function.""" def testValidData(self): """Tests that education entity is created properly if all data is valid.""" result = education_logic.createPostSecondaryEducation( TEST_SCHOOL_ID, TEST_SCHOOL_COUNTRY, TEST_EXPECTED_GRADUATION, TEST_MAJOR, TEST_DEGREE) self.assertTrue(result) education = result.extra self.assertEqual(education.school_id, TEST_SCHOOL_ID) self.assertEqual(education.school_country, TEST_SCHOOL_COUNTRY) self.assertEqual(education.expected_graduation, TEST_EXPECTED_GRADUATION) self.assertEqual(education.major, TEST_MAJOR) self.assertEqual(education.degree, TEST_DEGREE) def testInvalidData(self): """Tests that education entity is not created if data is not valid.""" # non-existing country result = education_logic.createPostSecondaryEducation( TEST_SCHOOL_ID, 'Neverland', TEST_EXPECTED_GRADUATION, TEST_MAJOR, TEST_DEGREE) self.assertFalse(result) # graduation year is not a number result = education_logic.createPostSecondaryEducation( TEST_SCHOOL_ID, TEST_SCHOOL_COUNTRY, str(TEST_EXPECTED_GRADUATION), TEST_MAJOR, TEST_DEGREE) self.assertFalse(result)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import importlib import inspect import itertools from neutron.conf.policies import address_group from neutron.conf.policies import address_scope from neutron.conf.policies import agent from neutron.conf.policies import auto_allocated_topology from neutron.conf.policies import availability_zone from neutron.conf.policies import base from neutron.conf.policies import flavor from neutron.conf.policies import floatingip from neutron.conf.policies import floatingip_pools from neutron.conf.policies import floatingip_port_forwarding from neutron.conf.policies import l3_conntrack_helper from neutron.conf.policies import logging from neutron.conf.policies import metering from neutron.conf.policies import network from neutron.conf.policies import network_ip_availability from neutron.conf.policies import network_segment_range from neutron.conf.policies import port from neutron.conf.policies import qos from neutron.conf.policies import quotas from neutron.conf.policies import rbac from neutron.conf.policies import router from neutron.conf.policies import security_group from neutron.conf.policies import segment from neutron.conf.policies import service_type from neutron.conf.policies import subnet from neutron.conf.policies import subnetpool from neutron.conf.policies import trunk def list_rules(): return itertools.chain( base.list_rules(), address_group.list_rules(), address_scope.list_rules(), agent.list_rules(), auto_allocated_topology.list_rules(), availability_zone.list_rules(), flavor.list_rules(), floatingip.list_rules(), floatingip_pools.list_rules(), floatingip_port_forwarding.list_rules(), l3_conntrack_helper.list_rules(), logging.list_rules(), metering.list_rules(), network.list_rules(), network_ip_availability.list_rules(), network_segment_range.list_rules(), port.list_rules(), qos.list_rules(), quotas.list_rules(), rbac.list_rules(), router.list_rules(), security_group.list_rules(), segment.list_rules(), service_type.list_rules(), subnet.list_rules(), subnetpool.list_rules(), trunk.list_rules(), ) def reload_default_policies(): for name, module in globals().items(): if (inspect.ismodule(module) and module.__name__.startswith(__package__)): # NOTE: pylint checks function args wrongly. # pylint: disable=too-many-function-args importlib.reload(module)
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {InvalidArgumentsException} from '../exception/invalid_arguments_exception'; import {SecurityException} from '../exception/security_exception'; const SUPPORTED_AES_KEY_SIZES: number[] = [16, 32]; /** * Validates AES key sizes, at the moment only 128-bit and 256-bit keys are * supported. * * @param n the key size in bytes * @throws {!InvalidArgumentsException} * @static */ export function validateAesKeySize(n: number) { if (!SUPPORTED_AES_KEY_SIZES.includes(n)) { throw new InvalidArgumentsException('unsupported AES key size: ' + n); } } /** * Validates that the input is a non null Uint8Array. * * @throws {!InvalidArgumentsException} * @static */ export function requireUint8Array(input: Uint8Array) { if (input == null || !(input instanceof Uint8Array)) { throw new InvalidArgumentsException('input must be a non null Uint8Array'); } } /** * Validates version, throws exception if candidate version is negative or * bigger than expected. * * @param candidate - version to be validated * @param maxVersion - upper bound on version * @throws {!SecurityException} * @static */ export function validateVersion(candidate: number, maxVersion: number) { if (candidate < 0 || candidate > maxVersion) { throw new SecurityException( 'Version is out of bound, must be ' + 'between 0 and ' + maxVersion + '.'); } } /** * Validates ECDSA parameters. * * @throws {!SecurityException} */ export function validateEcdsaParams(curve: string, hash: string) { switch (curve) { case 'P-256': if (hash != 'SHA-256') { throw new SecurityException( 'expected SHA-256 (because curve is P-256) but got ' + hash); } break; case 'P-384': if (hash != 'SHA-384' && hash != 'SHA-512') { throw new SecurityException( 'expected SHA-384 or SHA-512 (because curve is P-384) but got ' + hash); } break; case 'P-521': if (hash != 'SHA-512') { throw new SecurityException( 'expected SHA-512 (because curve is P-521) but got ' + hash); } break; default: throw new SecurityException('unsupported curve: ' + curve); } }
/** * 开发版本的文件导入 */ (function (){ var paths = [ 'editor.js', 'core/browser.js', 'core/utils.js', 'core/EventBase.js', 'core/dtd.js', 'core/domUtils.js', 'core/Range.js', 'core/Selection.js', 'core/Editor.js', 'core/filterword.js', 'core/node.js', 'core/htmlparser.js', 'core/filternode.js', 'plugins/inserthtml.js', 'plugins/image.js', 'plugins/justify.js', 'plugins/font.js', 'plugins/link.js', 'plugins/print.js', 'plugins/paragraph.js', 'plugins/horizontal.js', 'plugins/cleardoc.js', 'plugins/undo.js', 'plugins/paste.js', 'plugins/list.js', 'plugins/source.js', 'plugins/enterkey.js', 'plugins/preview.js', 'plugins/basestyle.js', 'plugins/video.js', 'plugins/selectall.js', 'plugins/removeformat.js', 'plugins/keystrokes.js', 'plugins/autosave.js', 'plugins/autoupload.js', 'plugins/formula.js', 'plugins/xssFilter.js', 'ui/widget.js', 'ui/button.js', 'ui/toolbar.js', 'ui/menu.js', 'ui/dropmenu.js', 'ui/splitbutton.js', 'ui/colorsplitbutton.js', 'ui/popup.js', 'ui/scale.js', 'ui/colorpicker.js', 'ui/combobox.js', 'ui/buttoncombobox.js', 'ui/modal.js', 'ui/tooltip.js', 'ui/tab.js', 'ui/separator.js', 'ui/scale.js', 'adapter/adapter.js', 'adapter/button.js', 'adapter/fullscreen.js', 'adapter/dialog.js', 'adapter/popup.js', 'adapter/imagescale.js', 'adapter/autofloat.js', 'adapter/source.js', 'adapter/combobox.js' ], baseURL = '../app/umeditor/_src/'; for (var i=0,pi;pi = paths[i++];) { document.write('<script type="text/javascript" src="'+ baseURL + pi +'"></script>'); } })();
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.extensions.api.projects; import com.google.gerrit.extensions.common.GitPerson; import com.google.gerrit.extensions.common.WebLinkInfo; import java.util.List; public class TagInfo extends RefInfo { public String object; public String message; public GitPerson tagger; public List<WebLinkInfo> webLinks; public TagInfo(String ref, String revision, Boolean canDelete, List<WebLinkInfo> webLinks) { this.ref = ref; this.revision = revision; this.canDelete = canDelete; this.webLinks = webLinks; } public TagInfo( String ref, String revision, String object, String message, GitPerson tagger, Boolean canDelete, List<WebLinkInfo> webLinks) { this(ref, revision, canDelete, webLinks); this.object = object; this.message = message; this.tagger = tagger; this.webLinks = webLinks; } }
// ------------------------------------------------------------ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace MetricReliableCollections { using System; /// <summary> /// Wrapper struct around arbitrary binary data. /// </summary> internal struct BinaryValue : IComparable<BinaryValue>, IEquatable<BinaryValue> { /// <summary> /// Direct access to the buffer that holds the actual data. Be careful. /// </summary> internal byte[] Buffer { get; } /// <summary> /// Creates a new BinaryValue. /// </summary> /// <param name="buffer"></param> /// <param name="copyBuffer"> /// Set to false if the given buffer does not owned by any other entity, such as a stream. /// When set to false, the buffer reference will be saved but the buffer contents will not be copied. /// Default is true. /// </param> public BinaryValue(byte[] buffer, bool copyBuffer = true) { if (buffer.Length > 0) { if (copyBuffer) { this.Buffer = new byte[buffer.Length]; Array.Copy(buffer, 0, this.Buffer, 0, buffer.Length); } else { this.Buffer = buffer; } } else { this.Buffer = new byte[0]; } } public override bool Equals(object obj) { if (!(obj is BinaryValue)) { return false; } return this.Equals((BinaryValue) obj); } /// <summary> /// There will be collisions. Needs improvement! /// </summary> /// <returns></returns> public override int GetHashCode() { if (this.Buffer != null) { int sum = this.Buffer.Length; for (int i = 0; i < this.Buffer.Length; ++i) { sum += this.Buffer[i]; } return sum; } return 0; } public int CompareTo(BinaryValue other) { if (this.Buffer == null && other.Buffer == null) { return 0; } if (this.Buffer == null) { return -1; } if (other.Buffer == null) { return 1; } int len = Math.Min(this.Buffer.Length, other.Buffer.Length); for (int i = 0; i < len; ++i) { int c = this.Buffer[i].CompareTo(other.Buffer[i]); if (c != 0) { return c; } } return this.Buffer.Length.CompareTo(other.Buffer.Length); } public bool Equals(BinaryValue other) { if (this.Buffer == null && other.Buffer == null) { return true; } if (this.Buffer == null ^ other.Buffer == null) { return false; } int len = Math.Min(this.Buffer.Length, other.Buffer.Length); for (int i = 0; i < len; ++i) { if (!this.Buffer[i].Equals(other.Buffer[i])) { return false; } } return this.Buffer.Length.Equals(other.Buffer.Length); } } }
#ifndef _NOFX_TYPES_H_ #define _NOFX_TYPES_H_ enum NOFX_TYPES { OFVEC3F = 0, OFVEC2F, OFVEC4F, OFSTYLE, OFCOLOR, OFIMAGE, OFBASEAPP, OFMATRIX4X4, OFMATRIX3X3, OFRECTANGLE, OFQUATERNION, OFTRUETYPEFONT, OFAPPBASEWINDOW, NUMBERPOINTER, OFPIXELS, OFTEXTURE, OFTEXTUREDATA, FLOATPTR, INTPTR, DOUBLEPTR, UNSIGNEDCHARPTR, UNSIGNEDSHORTPTR, VOIDPTR, OFBUFFER, OFFILE, CHARPTR }; #define DepNewInstance(name) (NanNew(name)->Call(args.This(), 0, nullptr)) #endif // !_NOFX_TYPES_H_
package com.suscipio_solutions.consecro_mud.Abilities.Spells; import java.util.Enumeration; import java.util.Vector; import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability; import com.suscipio_solutions.consecro_mud.Behaviors.interfaces.Behavior; import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg; import com.suscipio_solutions.consecro_mud.Exits.interfaces.Exit; import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room; import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB; import com.suscipio_solutions.consecro_mud.core.CMClass; import com.suscipio_solutions.consecro_mud.core.CMLib; import com.suscipio_solutions.consecro_mud.core.CMParms; import com.suscipio_solutions.consecro_mud.core.Directions; import com.suscipio_solutions.consecro_mud.core.interfaces.Physical; @SuppressWarnings("rawtypes") public class Spell_Augury extends Spell { @Override public String ID() { return "Spell_Augury"; } private final static String localizedName = CMLib.lang().L("Augury"); @Override public String name() { return localizedName; } @Override public int abstractQuality(){ return Ability.QUALITY_INDIFFERENT;} @Override protected int canTargetCode(){return 0;} @Override public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_DIVINATION;} @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { if((commands.size()<1)&&(givenTarget==null)) { mob.tell(L("Divine the fate of which direction?")); return false; } final String targetName=CMParms.combine(commands,0); Exit exit=null; Exit opExit=null; Room room=null; final int dirCode=Directions.getGoodDirectionCode(targetName); if(dirCode>=0) { exit=mob.location().getExitInDir(dirCode); room=mob.location().getRoomInDir(dirCode); if(room!=null) opExit=mob.location().getReverseExit(dirCode); } else { mob.tell(L("Divine the fate of which direction?")); return false; } if((exit==null)||(room==null)) { mob.tell(L("You couldn't go that way if you wanted to!")); return false; } if(!super.invoke(mob,commands,null,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> point(s) <S-HIS-HER> finger @x1, incanting.^?",Directions.getDirectionName(dirCode))); if(mob.location().okMessage(mob,msg)) { boolean aggressiveMonster=false; for(int m=0;m<room.numInhabitants();m++) { final MOB mon=room.fetchInhabitant(m); if(mon!=null) for(final Enumeration<Behavior> e=mob.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if((B!=null)&&(B.grantsAggressivenessTo(mob))) { aggressiveMonster=true; break; } } } mob.location().send(mob,msg); if((aggressiveMonster) ||CMLib.flags().isDeadlyOrMaliciousEffect(room) ||CMLib.flags().isDeadlyOrMaliciousEffect(exit) ||((opExit!=null)&&(CMLib.flags().isDeadlyOrMaliciousEffect(opExit)))) mob.tell(L("You feel going that way would be bad.")); else mob.tell(L("You feel going that way would be ok.")); } } else beneficialWordsFizzle(mob,null,L("<S-NAME> point(s) <S-HIS-HER> finger @x1, incanting, but then loses concentration.",Directions.getDirectionName(dirCode))); // return whether it worked return success; } }
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Constructor * PartModelEvent * * @see * @since: 2015.09.21 * @author: hw.shim */ // @formatter:off define([ 'webida-lib/util/genetic', 'webida-lib/util/logger/logger-client' ], function( genetic, Logger ) { 'use strict'; // @formatter:on var logger = new Logger(); //logger.setConfig('level', Logger.LEVELS.log); //logger.off(); function PartModelEvent() { logger.info('new PartModelEvent()'); } genetic.inherits(PartModelEvent, Object, { /** * @param {Object} delta */ setDelta: function(delta) { this.delta = delta; }, /** * @return {Object} */ getDelta: function() { return this.delta; }, /** * @param {Object} contents */ setContents: function(contents) { this.contents = contents; }, /** * @return {Object} */ getContents: function() { return this.contents; } }); return PartModelEvent; });