repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
ginach/msgraph-sdk-dotnet | src/Microsoft.Graph/Models/Generated/WorkbookFunctionsImDivRequestBody.cs | 1461 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Model\MethodRequestBody.cs.tt
namespace Microsoft.Graph
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
/// <summary>
/// The type WorkbookFunctionsImDivRequestBody.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class WorkbookFunctionsImDivRequestBody
{
/// <summary>
/// Gets or sets Inumber1.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "inumber1", Required = Newtonsoft.Json.Required.Default)]
public Newtonsoft.Json.Linq.JToken Inumber1 { get; set; }
/// <summary>
/// Gets or sets Inumber2.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "inumber2", Required = Newtonsoft.Json.Required.Default)]
public Newtonsoft.Json.Linq.JToken Inumber2 { get; set; }
}
}
| mit |
bean-validation-scala/bean-validation-scala | src/main/scala/com/tsukaby/bean_validation_scala/SafeHtmlValidatorForOption.scala | 923 | package com.tsukaby.bean_validation_scala
import javax.validation.{ConstraintValidator, ConstraintValidatorContext}
import org.hibernate.validator.constraints.SafeHtml
import org.hibernate.validator.internal.constraintvalidators.hv.SafeHtmlValidator
/**
* Check the wrapped string.
*/
class SafeHtmlValidatorForOption extends ConstraintValidator[SafeHtml, Option[_]] {
private var constraintAnnotation: SafeHtml = null
override def initialize(constraintAnnotation: SafeHtml): Unit = {
this.constraintAnnotation = constraintAnnotation
}
override def isValid(value: Option[_], context: ConstraintValidatorContext): Boolean = {
value match {
case Some(x:CharSequence) =>
val v = new SafeHtmlValidator
v.initialize(constraintAnnotation)
v.isValid(x, context)
case None =>
true
case Some(_) =>
throw new IllegalStateException("oops.")
}
}
}
| mit |
joshball/raptordb | RaptorDB/RaptorDBServer.cs | 15516 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RaptorDB.Common;
using System.Reflection;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace RaptorDB
{
public class RaptorDBServer
{
public RaptorDBServer(int port, string DataPath)
{
_path = Directory.GetCurrentDirectory();
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
_server = new NetworkServer();
_datapath = DataPath;
if (_datapath.EndsWith(_S) == false)
_datapath += _S;
_raptor = RaptorDB.Open(DataPath);
register = _raptor.GetType().GetMethod("RegisterView", BindingFlags.Instance | BindingFlags.Public);
save = _raptor.GetType().GetMethod("Save", BindingFlags.Instance | BindingFlags.Public);
Initialize();
_server.Start(port, processpayload);
}
void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
//perform cleanup here
log.Debug("process exited");
Shutdown();
}
private string _S = Path.DirectorySeparatorChar.ToString();
private Dictionary<string, uint> _users = new Dictionary<string, uint>();
private string _path = "";
private string _datapath = "";
private ILog log = LogManager.GetLogger(typeof(RaptorDBServer));
private NetworkServer _server;
private RaptorDB _raptor;
private MethodInfo register = null;
private MethodInfo save = null;
private SafeDictionary<Type, MethodInfo> _savecache = new SafeDictionary<Type, MethodInfo>();
private SafeDictionary<string, ServerSideFunc> _ssidecache = new SafeDictionary<string, ServerSideFunc>();
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (File.Exists(args.Name))
return Assembly.LoadFrom(args.Name);
string[] ss = args.Name.Split(',');
string fname = ss[0] + ".dll";
if (File.Exists(fname))
return Assembly.LoadFrom(fname);
fname = "Extensions" + _S + fname;
if (File.Exists(fname))
return Assembly.LoadFrom(fname);
else return null;
}
private MethodInfo GetSave(Type type)
{
MethodInfo m = null;
if (_savecache.TryGetValue(type, out m))
return m;
m = save.MakeGenericMethod(new Type[] { type });
_savecache.Add(type, m);
return m;
}
public void Shutdown()
{
WriteUsers();
_server.Stop();
}
private void WriteUsers()
{
// write users to user.config file
StringBuilder sb = new StringBuilder();
sb.AppendLine("# FORMAT : username , pasword hash");
sb.AppendLine("# To disable a user comment the line with the '#'");
foreach (var kv in _users)
{
sb.AppendLine(kv.Key + " , " + kv.Value);
}
File.WriteAllText(_datapath + "RaptorDB-Users.config", sb.ToString());
}
private object processpayload(object data)
{
Packet p = (Packet)data;
if (Authenticate(p) == false)
return new ReturnPacket(false, "Authentication failed");
ReturnPacket ret = new ReturnPacket(true);
try
{
object[] param = null;
switch (p.Command)
{
case "save":
var m = GetSave(p.Data.GetType());
m.Invoke(_raptor, new object[] { p.Docid, p.Data });
break;
case "savebytes":
ret.OK = _raptor.SaveBytes(p.Docid, (byte[])p.Data);
break;
case "querytype":
param = (object[])p.Data;
Type t = Type.GetType((string)param[0]);
string viewname = _raptor.GetViewName(t);
ret.OK = true;
ret.Data = _raptor.Query(viewname, (string)param[1], p.Start, p.Count, p.OrderBy);
break;
case "querystr":
ret.OK = true;
ret.Data = _raptor.Query(p.Viewname, (string)p.Data, p.Start, p.Count, p.OrderBy);
break;
case "fetch":
ret.OK = true;
ret.Data = _raptor.Fetch(p.Docid);
break;
case "fetchbytes":
ret.OK = true;
ret.Data = _raptor.FetchBytes(p.Docid);
break;
case "backup":
ret.OK = _raptor.Backup();
break;
case "delete":
ret.OK = _raptor.Delete(p.Docid);
break;
case "deletebytes":
ret.OK = _raptor.DeleteBytes(p.Docid);
break;
case "restore":
ret.OK = true;
Task.Factory.StartNew(() => _raptor.Restore());
break;
case "adduser":
param = (object[])p.Data;
ret.OK = AddUser((string)param[0], (string)param[1], (string)param[2]);
break;
case "serverside":
param = (object[])p.Data;
ret.OK = true;
ret.Data = _raptor.ServerSide(GetServerSideFuncCache(param[0].ToString(), param[1].ToString()), param[2].ToString());
break;
case "fulltext":
param = (object[])p.Data;
ret.OK = true;
ret.Data = _raptor.FullTextSearch("" + param[0]);
break;
case "counttype":
// count type
param = (object[])p.Data;
Type t2 = Type.GetType((string)param[0]);
string viewname2 = _raptor.GetViewName(t2);
ret.OK = true;
ret.Data = _raptor.Count(viewname2, (string)param[1]);
break;
case "countstr":
// count str
ret.OK = true;
ret.Data = _raptor.Count(p.Viewname, (string)p.Data);
break;
case "gcount":
Type t3 = Type.GetType(p.Viewname);
string viewname3 = _raptor.GetViewName(t3);
ret.OK = true;
ret.Data = _raptor.Count(viewname3, (string)p.Data);
break;
case "dochistory":
ret.OK = true;
ret.Data = _raptor.FetchHistory(p.Docid);
break;
case "filehistory":
ret.OK = true;
ret.Data = _raptor.FetchBytesHistory(p.Docid);
break;
case "fetchversion":
ret.OK = true;
ret.Data = _raptor.FetchVersion((int)p.Data);
break;
case "fetchfileversion":
ret.OK = true;
ret.Data = _raptor.FetchBytesVersion((int)p.Data);
break;
case "checkassembly":
ret.OK = true;
string typ = "";
ret.Data = _raptor.GetAssemblyForView(p.Viewname, out typ);
ret.Error = typ;
break;
case "fetchhistoryinfo":
ret.OK = true;
ret.Data = _raptor.FetchHistoryInfo(p.Docid);
break;
case "fetchbytehistoryinfo":
ret.OK = true;
ret.Data = _raptor.FetchBytesHistoryInfo(p.Docid);
break;
case "viewdelete":
ret.OK = true;
param = (object[])p.Data;
ret.Data = _raptor.ViewDelete((string)param[0], (string)param[1]);
break;
case "viewdelete-t":
ret.OK = true;
param = (object[])p.Data;
Type t4 = Type.GetType((string)param[0]);
string viewname4 = _raptor.GetViewName(t4);
ret.Data = _raptor.ViewDelete(viewname4, (string)param[1]);
break;
case "viewinsert":
ret.OK = true;
param = (object[])p.Data;
ret.Data = _raptor.ViewInsert((string)param[0], p.Docid, param[1]);
break;
case "viewinsert-t":
ret.OK = true;
param = (object[])p.Data;
Type t5 = Type.GetType((string)param[0]);
string viewname5 = _raptor.GetViewName(t5);
ret.Data = _raptor.ViewInsert(viewname5, p.Docid, param[1]);
break;
case "doccount":
ret.OK = true;
ret.Data = _raptor.DocumentCount();
break;
case "getobjecthf":
ret.OK = true;
ret.Data = _raptor.GetKVHF().GetObjectHF((string)p.Data);
break;
case "setobjecthf":
ret.OK = true;
param = (object[])p.Data;
_raptor.GetKVHF().SetObjectHF((string)param[0], param[1]);
break;
case "deletekeyhf":
ret.OK = true;
ret.Data = _raptor.GetKVHF().DeleteKeyHF((string)p.Data);
break;
case "counthf":
ret.OK = true;
ret.Data = _raptor.GetKVHF().CountHF();
break;
case "containshf":
ret.OK = true;
ret.Data = _raptor.GetKVHF().ContainsHF((string)p.Data);
break;
case "getkeyshf":
ret.OK = true;
ret.Data = _raptor.GetKVHF().GetKeysHF();
break;
case "compactstoragehf":
ret.OK = true;
_raptor.GetKVHF().CompactStorageHF();
break;
}
}
catch (Exception ex)
{
ret.OK = false;
log.Error(ex);
}
return ret;
}
private ServerSideFunc GetServerSideFuncCache(string type, string method)
{
ServerSideFunc func;
log.Debug("Calling Server side Function : " + method + " on type " + type);
if (_ssidecache.TryGetValue(type + method, out func) == false)
{
Type tt = Type.GetType(type);
func = (ServerSideFunc)Delegate.CreateDelegate(typeof(ServerSideFunc), tt, method);
_ssidecache.Add(type + method, func);
}
return func;
}
private uint GenHash(string user, string pwd)
{
return Helper.MurMur.Hash(Encoding.UTF8.GetBytes(user.ToLower() + "|" + pwd));
}
private bool AddUser(string user, string oldpwd, string newpwd)
{
uint hash = 0;
if (_users.TryGetValue(user.ToLower(), out hash) == false)
{
_users.Add(user.ToLower(), GenHash(user, newpwd));
return true;
}
if (hash == GenHash(user, oldpwd))
{
_users[user.ToLower()] = GenHash(user, newpwd);
return true;
}
return false;
}
private bool Authenticate(Packet p)
{
uint pwd;
if (_users.TryGetValue(p.Username.ToLower(), out pwd))
{
uint hash = uint.Parse(p.PasswordHash);
if (hash == pwd) return true;
}
log.Debug("Authentication failed for '" + p.Username + "' hash = " + p.PasswordHash);
return false;
}
private void Initialize()
{
// load users here
if (File.Exists(_datapath + "RaptorDB-Users.config"))
{
foreach (string line in File.ReadAllLines(_datapath + "RaptorDB-Users.config"))
{
if (line.Contains("#") == false)
{
string[] s = line.Split(',');
_users.Add(s[0].Trim().ToLower(), uint.Parse(s[1].Trim()));
}
}
}
// add default admin user if not exists
if (_users.ContainsKey("admin") == false)
_users.Add("admin", GenHash("admin", "admin"));
// exe folder
// |-Extensions
Directory.CreateDirectory(_path + _S + "Extensions");
// open extensions folder
string path = _path + _S + "Extensions";
foreach (var f in Directory.GetFiles(path, "*.dll"))
{
// - load all dll files
// - register views
log.Debug("loading dll for views : " + f);
Assembly a = Assembly.Load(f);
foreach (var t in a.GetTypes())
{
foreach (var att in t.GetCustomAttributes(typeof(RegisterViewAttribute), false))
{
try
{
object o = Activator.CreateInstance(t);
// handle types when view<T> also
Type[] args = t.GetGenericArguments();
if (args.Length == 0)
args = t.BaseType.GetGenericArguments();
Type tt = args[0];
var m = register.MakeGenericMethod(new Type[] { tt });
m.Invoke(_raptor, new object[] { o });
}
catch (Exception ex)
{
log.Error(ex);
}
}
}
}
}
}
}
| mit |
ermshiperete/LfMerge | src/LfMerge.Core/LanguageForge/Infrastructure/ILanguageForgeProxy.cs | 489 | // Copyright (c) 2016 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System.Collections.Generic;
namespace LfMerge.Core.LanguageForge.Infrastructure
{
public interface ILanguageForgeProxy
{
string UpdateCustomFieldViews(string projectCode, List<CustomFieldSpec> customFieldSpecs);
string UpdateCustomFieldViews(string projectCode, List<CustomFieldSpec> customFieldSpecs, bool isTest);
string ListUsers();
}
}
| mit |
Tania123/print | src/Store/NewsBundle/Tests/Controller/NewsControllerTest.php | 396 | <?php
namespace Store\NewsBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class NewsControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| mit |
teerasarn/project1 | src/Five/AdminBundle/Resources/public/coco_theme/assets/js/pages/other-charts.js | 598 | var initCharts = function() {
var charts = $('.percentage');
charts.easyPieChart({
animate: 1000,
lineWidth: 5,
barColor: "#eb5055",
lineCap: "butt",
size: "150",
scaleColor: "transparent",
onStep: function(from, to, percent) {
$(this.el).find('.cpercent').text(Math.round(percent));
}
});
$('.updatePieCharts').on('click', function(e) {
e.preventDefault();
charts.each(function() {
$(this).data('easyPieChart').update(Math.floor(100*Math.random()));
});
});
}
$(function(){
$(".knob").knob();
initCharts();
}) | mit |
leonidboykov/whoami | whoami.go | 269 | package main
import (
"net/http"
"os"
)
func main() {
hostname, _ := os.Hostname()
hostname += "\n"
response := []byte(hostname)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write(response)
})
http.ListenAndServe(":8080", nil)
}
| mit |
gnoling/passenger | lib/phusion_passenger/standalone/start_command.rb | 23393 | # Phusion Passenger - https://www.phusionpassenger.com/
# Copyright (c) 2010-2014 Phusion
#
# "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
#
# 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.
require 'socket'
require 'thread'
require 'etc'
PhusionPassenger.require_passenger_lib 'plugin'
PhusionPassenger.require_passenger_lib 'standalone/command'
PhusionPassenger.require_passenger_lib 'platform_info/operating_system'
# We lazy load as many libraries as possible not only to improve startup performance,
# but also to ensure that we don't require libraries before we've passed the dependency
# checking stage of the runtime installer.
module PhusionPassenger
module Standalone
class StartCommand < Command
def self.description
return "Start Phusion Passenger Standalone."
end
def initialize(args)
super(args)
@console_mutex = Mutex.new
@termination_pipe = IO.pipe
@threads = []
@interruptable_threads = []
@plugin = PhusionPassenger::Plugin.new('standalone/start_command', self, @options)
end
def run
parse_my_options
sanity_check_options
PhusionPassenger.require_passenger_lib 'standalone/runtime_locator'
@runtime_locator = RuntimeLocator.new(@options[:runtime_dir],
@options[:nginx_version])
ensure_runtime_installed
set_stdout_stderr_binmode
exit if @options[:runtime_check_only]
require_app_finder
@app_finder = AppFinder.new(@args, @options)
@apps = @app_finder.scan
@options = @app_finder.global_options
determine_various_resource_locations
@plugin.call_hook(:found_apps, @apps)
extra_controller_options = {}
@plugin.call_hook(:before_creating_nginx_controller, extra_controller_options)
create_nginx_controller(extra_controller_options)
begin
start_nginx
show_intro_message
if @options[:daemonize]
if PlatformInfo.ruby_supports_fork?
daemonize
else
daemonize_without_fork
end
end
Thread.abort_on_exception = true
@plugin.call_hook(:nginx_started, @nginx)
########################
########################
touch_temp_dir_in_background
watch_log_files_in_background if should_watch_logs?
wait_until_nginx_has_exited if should_wait_until_nginx_has_exited?
rescue Interrupt
begin_shutdown
stop_threads
stop_nginx
exit 2
rescue SignalException => signal
begin_shutdown
stop_threads
stop_nginx
if signal.message == 'SIGINT' || signal.message == 'SIGTERM'
exit 2
else
raise
end
rescue Exception => e
begin_shutdown
stop_threads
stop_nginx
raise
ensure
begin_shutdown
begin
stop_threads
ensure
finalize_shutdown
end
end
ensure
@plugin.call_hook(:cleanup)
end
private
def require_file_utils
require 'fileutils' unless defined?(FileUtils)
end
def parse_my_options
description = "Starts Phusion Passenger Standalone and serve one or more Ruby web applications."
parse_options!("start [directory]", description) do |opts|
opts.on("-a", "--address HOST", String,
wrap_desc("Bind to HOST address (default: #{@options[:address]})")) do |value|
@options[:address] = value
@options[:tcp_explicitly_given] = true
end
opts.on("-p", "--port NUMBER", Integer,
wrap_desc("Use the given port number (default: #{@options[:port]})")) do |value|
@options[:port] = value
@options[:tcp_explicitly_given] = true
end
opts.on("-S", "--socket FILE", String,
wrap_desc("Bind to Unix domain socket instead of TCP socket")) do |value|
@options[:socket_file] = value
end
opts.separator ""
opts.on("-e", "--environment ENV", String,
wrap_desc("Framework environment (default: #{@options[:environment]})")) do |value|
@options[:environment] = value
end
opts.on("-R", "--rackup FILE", String,
wrap_desc("Consider application a Ruby Rack app, and use the given rackup file")) do |value|
@options[:app_type] = "rack"
@options[:startup_file] = value
end
opts.on("--app-type NAME", String,
wrap_desc("Force app to be detected as the given type")) do |value|
@options[:app_type] = value
end
opts.on("--startup-file FILENAME", String,
wrap_desc("Force given startup file to be used")) do |value|
@options[:startup_file] = value
end
opts.on("--max-pool-size NUMBER", Integer,
wrap_desc("Maximum number of application processes (default: #{@options[:max_pool_size]})")) do |value|
@options[:max_pool_size] = value
end
opts.on("--min-instances NUMBER", Integer,
wrap_desc("Minimum number of processes per application (default: #{@options[:min_instances]})")) do |value|
@options[:min_instances] = value
end
opts.on("--spawn-method NAME", String,
wrap_desc("The spawn method to use (default: #{@options[:spawn_method]})")) do |value|
@options[:spawn_method] = value
end
opts.on("--concurrency-model NAME", String,
wrap_desc("The concurrency model to use, either 'process' or 'thread' (default: #{@options[:concurrency_model]}) (Enterprise only)")) do |value|
@options[:concurrency_model] = value
end
opts.on("--thread-count NAME", Integer,
wrap_desc("The number of threads to use when using the 'thread' concurrency model (default: #{@options[:thread_count]}) (Enterprise only)")) do |value|
@options[:thread_count] = value
end
opts.on("--rolling-restarts",
wrap_desc("Enable rolling restarts (Enterprise only)")) do
@options[:rolling_restarts] = true
end
opts.on("--resist-deployment-errors",
wrap_desc("Enable deployment error resistance (Enterprise only)")) do
@options[:resist_deployment_errors] = true
end
opts.on("--no-friendly-error-pages",
wrap_desc("Disable passenger_friendly_error_pages")) do
@options[:friendly_error_pages] = false
end
opts.on("--ssl",
wrap_desc("Enable SSL support")) do
@options[:ssl] = true
end
opts.on("--ssl-certificate PATH", String,
wrap_desc("Specify the SSL certificate path")) do |val|
@options[:ssl_certificate] = File.expand_path(val)
end
opts.on("--ssl-certificate-key PATH", String,
wrap_desc("Specify the SSL key path")) do |val|
@options[:ssl_certificate_key] = File.expand_path(val)
end
opts.on("--ssl-port PORT", Integer,
wrap_desc("Listen for SSL on this port, while listening for HTTP on the normal port")) do |val|
@options[:ssl_port] = val
end
opts.on("--static-files-dir PATH", String,
wrap_desc("Specify the static files dir")) do |val|
@options[:static_files_dir] = File.expand_path(val)
end
opts.on("--restart-dir PATH", String,
wrap_desc("Specify the restart dir")) do |val|
@options[:restart_dir] = File.expand_path(val)
end
opts.on("--union-station-gateway HOST:PORT", String,
wrap_desc("Specify Union Station Gateway host and port")) do |value|
host, port = value.split(":", 2)
port = port.to_i
port = 443 if port == 0
@options[:union_station_gateway_address] = host
@options[:union_station_gateway_port] = port.to_i
end
opts.on("--union-station-key KEY", String,
wrap_desc("Specify Union Station key")) do |value|
@options[:union_station_key] = value
end
opts.separator ""
opts.on("--ping-port NUMBER", Integer,
wrap_desc("Use the given port number for checking whether Nginx is alive (default: same as the normal port)")) do |value|
@options[:ping_port] = value
end
@plugin.call_hook(:parse_options, opts)
opts.separator ""
opts.on("-d", "--daemonize",
wrap_desc("Daemonize into the background")) do
@options[:daemonize] = true
end
opts.on("--user USERNAME", String,
wrap_desc("User to run as. Ignored unless running as root.")) do |value|
@options[:user] = value
end
opts.on("--log-file FILENAME", String,
wrap_desc("Where to write log messages (default: console, or /dev/null when daemonized)")) do |value|
@options[:log_file] = value
end
opts.on("--pid-file FILENAME", String,
wrap_desc("Where to store the PID file")) do |value|
@options[:pid_file] = value
end
opts.on("--temp-dir PATH", String,
wrap_desc("Use the given temp dir")) do |value|
ENV['TMPDIR'] = value
@options[:temp_dir] = value
end
opts.separator ""
opts.on("--nginx-bin FILENAME", String,
wrap_desc("Nginx binary to use as core")) do |value|
@options[:nginx_bin] = value
end
opts.on("--nginx-version VERSION", String,
wrap_desc("Nginx version to use as core (default: #{@options[:nginx_version]})")) do |value|
@options[:nginx_version] = value
end
opts.on("--nginx-tarball FILENAME", String,
wrap_desc("If Nginx needs to be installed, then the given tarball will " +
"be used instead of downloading from the Internet")) do |value|
@options[:nginx_tarball] = File.expand_path(value)
end
opts.on("--nginx-config-template FILENAME", String,
wrap_desc("The template to use for generating the Nginx config file")) do |value|
@options[:nginx_config_template] = File.expand_path(value)
end
opts.on("--binaries-url-root URL", String,
wrap_desc("If Nginx needs to be installed, then the specified URL will be " +
"checked for binaries prior to a local build.")) do |value|
@options[:binaries_url_root] = value
end
opts.on("--no-download-binaries",
wrap_desc("Never download binaries")) do
@options[:download_binaries] = false
end
opts.on("--runtime-dir DIRECTORY", String,
wrap_desc("Directory to use for Phusion Passenger Standalone runtime files")) do |value|
@options[:runtime_dir] = File.expand_path(value)
end
opts.on("--runtime-check-only",
wrap_desc("Quit after checking whether the Phusion Passenger Standalone runtime files are installed")) do
@options[:runtime_check_only] = true
end
opts.on("--no-compile-runtime",
wrap_desc("Abort if runtime must be compiled")) do
@options[:dont_compile_runtime] = true
end
end
@plugin.call_hook(:done_parsing_options)
end
def sanity_check_options
if @options[:tcp_explicitly_given] && @options[:socket_file]
error "You cannot specify both --address/--port and --socket. Please choose either one."
exit 1
end
if @options[:ssl] && !@options[:ssl_certificate]
error "You specified --ssl. Please specify --ssl-certificate as well."
exit 1
end
if @options[:ssl] && !@options[:ssl_certificate_key]
error "You specified --ssl. Please specify --ssl-certificate-key as well."
exit 1
end
check_port_bind_permission_and_display_sudo_suggestion
check_port_availability
end
# Most platforms don't allow non-root processes to bind to a port lower than 1024.
# Check whether this is the case for the current platform and if so, tell the user
# that it must re-run Phusion Passenger Standalone with sudo.
def check_port_bind_permission_and_display_sudo_suggestion
if !@options[:socket_file] && @options[:port] < 1024 && Process.euid != 0
begin
TCPServer.new('127.0.0.1', @options[:port]).close
rescue Errno::EACCES
PhusionPassenger.require_passenger_lib 'platform_info/ruby'
myself = `whoami`.strip
error "Only the 'root' user can run this program on port #{@options[:port]}. " <<
"You are currently running as '#{myself}'. Please re-run this program " <<
"with root privileges with the following command:\n\n" <<
" #{PlatformInfo.ruby_sudo_command} passenger start #{@original_args.join(' ')} --user=#{myself}\n\n" <<
"Don't forget the '--user' part! That will make Phusion Passenger Standalone " <<
"drop root privileges and switch to '#{myself}' after it has obtained " <<
"port #{@options[:port]}."
exit 1
end
end
end
if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
require 'java'
def check_port(host_name, port)
channel = java.nio.channels.SocketChannel.open
begin
address = java.net.InetSocketAddress.new(host_name, port)
channel.configure_blocking(false)
if channel.connect(address)
return true
end
deadline = Time.now.to_f + 0.1
done = false
while true
begin
if channel.finish_connect
return true
end
rescue java.net.ConnectException => e
if e.message =~ /Connection refused/i
return false
else
throw e
end
end
# Not done connecting and no error.
sleep 0.01
if Time.now.to_f >= deadline
return false
end
end
ensure
channel.close
end
end
else
def check_port_with_protocol(address, port, protocol)
begin
socket = Socket.new(protocol, Socket::Constants::SOCK_STREAM, 0)
sockaddr = Socket.pack_sockaddr_in(port, address)
begin
socket.connect_nonblock(sockaddr)
rescue Errno::ENOENT, Errno::EINPROGRESS, Errno::EAGAIN, Errno::EWOULDBLOCK
if select(nil, [socket], nil, 0.1)
begin
socket.connect_nonblock(sockaddr)
rescue Errno::EISCONN
rescue Errno::EINVAL
if PlatformInfo.os_name =~ /freebsd/i
raise Errno::ECONNREFUSED
else
raise
end
end
else
raise Errno::ECONNREFUSED
end
end
return true
rescue Errno::ECONNREFUSED
return false
ensure
socket.close if socket && !socket.closed?
end
end
def check_port(address, port)
begin
check_port_with_protocol(address, port, Socket::Constants::AF_INET)
rescue Errno::EAFNOSUPPORT
check_port_with_protocol(address, port, Socket::Constants::AF_INET6)
end
end
end
def check_port_availability
if !@options[:socket_file] && check_port(@options[:address], @options[:port])
error "The address #{@options[:address]}:#{@options[:port]} is already " <<
"in use by another process, perhaps another Phusion Passenger " <<
"Standalone instance.\n\n" <<
"If you want to run this Phusion Passenger Standalone instance on " <<
"another port, use the -p option, like this:\n\n" <<
" passenger start -p #{@options[:port] + 1}"
exit 1
end
end
def should_watch_logs?
return !@options[:daemonize] && @options[:log_file] != "/dev/null"
end
def should_wait_until_nginx_has_exited?
return !@options[:daemonize] || @app_finder.multi_mode?
end
# Returns the URL that Nginx will be listening on.
def listen_url
if @options[:socket_file]
return @options[:socket_file]
else
if @options[:ssl] && !@options[:ssl_port]
scheme = "https"
else
scheme = "http"
end
result = "#{scheme}://"
if @options[:port] == 80
result << @options[:address]
else
result << compose_ip_and_port(@options[:address], @options[:port])
end
result << "/"
return result
end
end
def install_runtime(runtime_locator)
PhusionPassenger.require_passenger_lib 'standalone/runtime_installer'
installer = RuntimeInstaller.new(
:targets => runtime_locator.install_targets,
:support_dir => runtime_locator.support_dir_install_destination,
:nginx_dir => runtime_locator.nginx_binary_install_destination,
:lib_dir => runtime_locator.find_lib_dir || runtime_locator.support_dir_install_destination,
:nginx_version => @options[:nginx_version],
:nginx_tarball => @options[:nginx_tarball],
:binaries_url_root => @options[:binaries_url_root],
:download_binaries => @options.fetch(:download_binaries, true),
:dont_compile_runtime => @options[:dont_compile_runtime],
:plugin => @plugin)
return installer.run
end
def ensure_runtime_installed
if @runtime_locator.everything_installed?
if !File.exist?(@runtime_locator.find_nginx_binary)
error "The web helper binary '#{@runtime_locator.find_nginx_binary}' does not exist."
exit 1
end
else
if !@runtime_locator.find_support_dir && PhusionPassenger.natively_packaged?
error "Your Phusion Passenger Standalone installation is broken: the support " +
"files could not be found. Please reinstall Phusion Passenger Standalone. " +
"If this problem persists, please contact your packager."
exit 1
end
install_runtime(@runtime_locator) || exit(1)
@runtime_locator.reload
end
end
def set_stdout_stderr_binmode
# We already set STDOUT and STDERR to binmode in bin/passenger, which
# fixes https://github.com/phusion/passenger-ruby-heroku-demo/issues/11.
# However RuntimeInstaller sets them to UTF-8, so here we set them back.
STDOUT.binmode
STDERR.binmode
end
def start_nginx
begin
@nginx.start
rescue DaemonController::AlreadyStarted
begin
pid = @nginx.pid
rescue SystemCallError, IOError
pid = nil
end
if pid
error "Phusion Passenger Standalone is already running on PID #{pid}."
else
error "Phusion Passenger Standalone is already running."
end
exit 1
rescue DaemonController::StartError => e
error "Could not start Passenger Nginx core:\n#{e}"
exit 1
end
end
def show_intro_message
puts "=============== Phusion Passenger Standalone web server started ==============="
puts "PID file: #{@options[:pid_file]}"
puts "Log file: #{@options[:log_file]}"
puts "Environment: #{@options[:environment]}"
puts "Accessible via: #{listen_url}"
puts
if @options[:daemonize]
puts "Serving in the background as a daemon."
else
puts "You can stop Phusion Passenger Standalone by pressing Ctrl-C."
end
puts "Problems? Check #{STANDALONE_DOC_URL}#troubleshooting"
puts "==============================================================================="
end
def daemonize_without_fork
STDERR.puts "Unable to daemonize using the current Ruby interpreter " +
"(#{PlatformInfo.ruby_command}) because it does not support forking."
exit 1
end
def daemonize
pid = fork
if pid
# Parent
exit!(0)
else
# Child
trap "HUP", "IGNORE"
STDIN.reopen("/dev/null", "r")
STDOUT.reopen(@options[:log_file], "a")
STDERR.reopen(@options[:log_file], "a")
STDOUT.sync = true
STDERR.sync = true
Process.setsid
end
end
# Wait until the termination pipe becomes readable (a hint for threads
# to shut down), or until the timeout has been reached. Returns true if
# the termination pipe became readable, false if the timeout has been reached.
def wait_on_termination_pipe(timeout)
ios = select([@termination_pipe[0]], nil, nil, timeout)
return !ios.nil?
end
def watch_log_file(log_file)
if File.exist?(log_file)
backward = 0
else
# tail bails out if the file doesn't exist, so wait until it exists.
while !File.exist?(log_file)
sleep 1
end
backward = 10
end
IO.popen("tail -f -n #{backward} \"#{log_file}\"", "rb") do |f|
begin
while true
begin
line = f.readline
@console_mutex.synchronize do
STDOUT.write(line)
STDOUT.flush
end
rescue EOFError
break
end
end
ensure
Process.kill('TERM', f.pid) rescue nil
end
end
end
def watch_log_files_in_background
@apps.each do |app|
thread = Thread.new do
watch_log_file("#{app[:root]}/log/#{@options[:environment]}.log")
end
@threads << thread
@interruptable_threads << thread
end
thread = Thread.new do
watch_log_file(@options[:log_file])
end
@threads << thread
@interruptable_threads << thread
end
def touch_temp_dir_in_background
result = system("#{@runtime_locator.find_agents_dir}/TempDirToucher",
@temp_dir,
"--cleanup",
"--daemonize",
"--pid-file", "#{@temp_dir}/temp_dir_toucher.pid",
"--log-file", @options[:log_file])
if !result
error "Cannot start #{@runtime_locator.find_agents_dir}/TempDirToucher"
exit 1
end
end
def begin_shutdown
return if @shutting_down
@shutting_down = 1
trap("INT", &method(:signal_during_shutdown))
trap("TERM", &method(:signal_during_shutdown))
end
def finalize_shutdown
@shutting_down = nil
trap("INT", "DEFAULT")
trap("TERM", "DEFAULT")
end
def signal_during_shutdown(signal)
if @shutting_down == 1
@shutting_down += 1
puts "Ignoring signal #{signal} during shutdown. Send it again to force exit."
else
exit!(1)
end
end
def stop_touching_temp_dir_in_background
if @toucher
begin
Process.kill('TERM', @toucher.pid)
rescue Errno::ESRCH, Errno::ECHILD
end
@toucher.close
end
end
def wait_until_nginx_has_exited
# Since Nginx is not our child process (it daemonizes or we daemonize)
# we cannot use Process.waitpid to wait for it. A busy-sleep-loop with
# Process.kill(0, pid) isn't very efficient. Instead we do this:
#
# Connect to Nginx and wait until Nginx disconnects the socket because of
# timeout. Keep doing this until we can no longer connect.
while true
if @options[:socket_file]
socket = UNIXSocket.new(@options[:socket_file])
else
socket = TCPSocket.new(@options[:address], nginx_ping_port)
end
begin
socket.read rescue nil
ensure
socket.close rescue nil
end
end
rescue Errno::ECONNREFUSED, Errno::ECONNRESET
end
def stop_nginx
@console_mutex.synchronize do
STDOUT.write("Stopping web server...")
STDOUT.flush
@nginx.stop
STDOUT.puts " done"
STDOUT.flush
end
end
def stop_threads
if !@termination_pipe[1].closed?
@termination_pipe[1].write("x")
@termination_pipe[1].close
end
@interruptable_threads.each do |thread|
thread.terminate
end
@interruptable_threads = []
@threads.each do |thread|
thread.join
end
@threads = []
end
#### Config file template helpers ####
def nginx_listen_address(options = @options, for_ping_port = false)
if options[:socket_file]
return "unix:" + File.expand_path(options[:socket_file])
else
if for_ping_port
port = options[:ping_port]
else
port = options[:port]
end
return compose_ip_and_port(options[:address], port)
end
end
def nginx_listen_address_with_ssl_port(options = @options)
if options[:socket_file]
return "unix:" + File.expand_path(options[:socket_file])
else
return compose_ip_and_port(options[:address], options[:ssl_port])
end
end
def compose_ip_and_port(ip, port)
if ip =~ /:/
# IPv6
return "[#{ip}]:#{port}"
else
return "#{ip}:#{port}"
end
end
def default_group_for(username)
user = Etc.getpwnam(username)
group = Etc.getgrgid(user.gid)
return group.name
end
#################
end
end # module Standalone
end # module PhusionPassenger
| mit |
deech/fltkhs | c-src/Fl_SliderC.cpp | 22359 | #include "Fl_SliderC.h"
#ifdef __cplusplus
EXPORT {
Fl_DerivedSlider::Fl_DerivedSlider(int X, int Y, int W, int H, const char *l, fl_Widget_Virtual_Funcs* funcs) : Fl_Slider(X,Y,W,H,l){
overriddenFuncs = funcs;
other_data = (void*)0;
}
Fl_DerivedSlider::Fl_DerivedSlider(int X, int Y, int W, int H, fl_Widget_Virtual_Funcs* funcs):Fl_Slider(X,Y,W,H){
overriddenFuncs = funcs;
other_data = (void*)0;
}
Fl_DerivedSlider::~Fl_DerivedSlider(){
this->destroy_data();
free(overriddenFuncs);
}
void Fl_DerivedSlider::destroy_data(){
if (this->overriddenFuncs->destroy_data != NULL){
fl_DoNotCall* fps = NULL;
int num_fps = C_to_Fl_Callback::function_pointers_to_free(this->overriddenFuncs,&fps);
fl_Callback* cb = C_to_Fl_Callback::get_callback(this);
Function_Pointers_To_Free* res = C_to_Fl_Callback::gather_function_pointers(num_fps+1,num_fps,fps,(fl_DoNotCall)cb);
this->overriddenFuncs->destroy_data((fl_Slider)this,res);
if (fps) { free(fps); }
free(res);
}
}
void Fl_DerivedSlider::draw(){
if (this->overriddenFuncs->draw != NULL) {
this->overriddenFuncs->draw((fl_Slider) this);
}
else {
Fl_Slider::draw();
}
}
void Fl_DerivedSlider::draw_super(){
Fl_Slider::draw();
}
int Fl_DerivedSlider::handle(int event){
int i;
if (this->overriddenFuncs->handle != NULL) {
i = this->overriddenFuncs->handle((fl_Slider) this,event);
}
else {
i = Fl_Slider::handle(event);
}
return i;
}
int Fl_DerivedSlider::handle_super(int event){
return Fl_Slider::handle(event);
}
void Fl_DerivedSlider::resize(int x, int y, int w, int h){
if (this->overriddenFuncs->resize != NULL) {
this->overriddenFuncs->resize((fl_Slider) this,x,y,w,h);
}
else {
Fl_Slider::resize(x,y,w,h);
}
}
void Fl_DerivedSlider::resize_super(int x, int y, int w, int h){
Fl_Slider::resize(x,y,w,h);
}
void Fl_DerivedSlider::show(){
if (this->overriddenFuncs->show != NULL) {
this->overriddenFuncs->show((fl_Slider) this);
}
else {
Fl_Slider::show();
}
}
void Fl_DerivedSlider::show_super(){
Fl_Slider::show();
}
void Fl_DerivedSlider::hide(){
if (this->overriddenFuncs->hide != NULL) {
this->overriddenFuncs->hide((fl_Slider) this);
}
else {
Fl_Slider::hide();
}
}
void Fl_DerivedSlider::hide_super(){
Fl_Slider::hide();
}
#endif
FL_EXPORT_C(fl_Window,Fl_Slider_as_window_super)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->Fl_Slider::as_window();
}
FL_EXPORT_C(fl_Window,Fl_Slider_as_window )(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->as_window();
}
FL_EXPORT_C(fl_Gl_Window,Fl_Slider_as_gl_window_super)(fl_Slider slider){
return (fl_Gl_Window) (static_cast<Fl_Slider*>(slider))->Fl_Slider::as_gl_window();
}
FL_EXPORT_C(fl_Gl_Window,Fl_Slider_as_gl_window )(fl_Slider slider){
return (fl_Gl_Window) (static_cast<Fl_Slider*>(slider))->as_gl_window();
};
FL_EXPORT_C(fl_Group,Fl_Slider_parent)(fl_Slider slider){
return (fl_Group) (static_cast<Fl_Slider*>(slider))->parent();
}
FL_EXPORT_C(void,Fl_Slider_set_parent)(fl_Slider slider,fl_Group grp){
(static_cast<Fl_Slider*>(slider))->parent((static_cast<Fl_Group*>(grp)));
}
FL_EXPORT_C(uchar,Fl_Slider_type)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->type();
}
FL_EXPORT_C(void,Fl_Slider_set_type)(fl_Slider slider,uchar t){
(static_cast<Fl_Slider*>(slider))->type(t);
}
FL_EXPORT_C(int,Fl_Slider_x)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->x();
}
FL_EXPORT_C(int,Fl_Slider_y)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->y();
}
FL_EXPORT_C(int,Fl_Slider_w)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->w();
}
FL_EXPORT_C(int,Fl_Slider_h)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->h();
}
FL_EXPORT_C(void,Fl_Slider_set_align)(fl_Slider slider, Fl_Align alignment){
(static_cast<Fl_Slider*>(slider))->align(alignment);
}
FL_EXPORT_C(Fl_Align,Fl_Slider_align)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->align();
}
FL_EXPORT_C(Fl_Boxtype,Fl_Slider_box)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->box();
}
FL_EXPORT_C(void,Fl_Slider_set_box)(fl_Slider slider,Fl_Boxtype new_box){
(static_cast<Fl_Slider*>(slider))->box((static_cast<Fl_Boxtype>(new_box)));
}
FL_EXPORT_C(Fl_Color,Fl_Slider_color)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->color();
}
FL_EXPORT_C(void,Fl_Slider_set_color)(fl_Slider slider,Fl_Color bg){
(static_cast<Fl_Slider*>(slider))->color(bg);
}
FL_EXPORT_C(void,Fl_Slider_set_color_with_bg_sel)(fl_Slider slider,Fl_Color bg,Fl_Color a){
(static_cast<Fl_Slider*>(slider))->color(bg,a);
}
FL_EXPORT_C(Fl_Color,Fl_Slider_selection_color)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->selection_color();
}
FL_EXPORT_C(void,Fl_Slider_set_selection_color)(fl_Slider slider,Fl_Color a){
(static_cast<Fl_Slider*>(slider))->selection_color(a);
}
FL_EXPORT_C(const char*,Fl_Slider_label)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->label();
}
FL_EXPORT_C(void,Fl_Slider_copy_label)(fl_Slider slider,const char* new_label){
(static_cast<Fl_Slider*>(slider))->copy_label(new_label);
}
FL_EXPORT_C(void,Fl_Slider_set_label)(fl_Slider slider,const char* text){
(static_cast<Fl_Slider*>(slider))->label(text);
}
FL_EXPORT_C(Fl_Labeltype,Fl_Slider_labeltype)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->labeltype();
}
FL_EXPORT_C(void,Fl_Slider_set_labeltype)(fl_Slider slider,Fl_Labeltype a){
(static_cast<Fl_Slider*>(slider))->labeltype(a);
}
FL_EXPORT_C(Fl_Color,Fl_Slider_labelcolor)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->labelcolor();
}
FL_EXPORT_C(void,Fl_Slider_set_labelcolor)(fl_Slider slider,Fl_Color c){
(static_cast<Fl_Slider*>(slider))->labelcolor(c);
}
FL_EXPORT_C(Fl_Font,Fl_Slider_labelfont)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->labelfont();
}
FL_EXPORT_C(void,Fl_Slider_set_labelfont)(fl_Slider slider,Fl_Font c){
(static_cast<Fl_Slider*>(slider))->labelfont((static_cast<Fl_Font>(c)));
}
FL_EXPORT_C(Fl_Fontsize,Fl_Slider_labelsize)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->labelsize();
}
FL_EXPORT_C(void,Fl_Slider_set_labelsize)(fl_Slider slider,Fl_Fontsize pix){
(static_cast<Fl_Slider*>(slider))->labelsize((static_cast<Fl_Fontsize>(pix)));
}
FL_EXPORT_C(fl_Image,Fl_Slider_image)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->image();
}
FL_EXPORT_C(void,Fl_Slider_set_image)(fl_Slider slider,fl_Image pix){
(static_cast<Fl_Slider*>(slider))->image((static_cast<Fl_Image*>(pix)));
}
FL_EXPORT_C(fl_Image,Fl_Slider_deimage)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->deimage();
}
FL_EXPORT_C(void,Fl_Slider_set_deimage)(fl_Slider slider,fl_Image pix){
(static_cast<Fl_Slider*>(slider))->deimage((static_cast<Fl_Image*>(pix)));
}
FL_EXPORT_C(const char*,Fl_Slider_tooltip)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->tooltip();
}
FL_EXPORT_C(void,Fl_Slider_copy_tooltip)(fl_Slider slider,const char* text){
(static_cast<Fl_Slider*>(slider))->copy_tooltip(text);
}
FL_EXPORT_C(void,Fl_Slider_set_tooltip)(fl_Slider slider,const char* text){
(static_cast<Fl_Slider*>(slider))->tooltip(text);
}
FL_EXPORT_C(void,Fl_Slider_set_callback_with_user_data)(fl_Slider slider,fl_Callback cb,void* p){
Fl_Slider* castedBox = (static_cast<Fl_Slider*>(slider));
new C_to_Fl_Callback(castedBox, cb, p);
}
FL_EXPORT_C(void,Fl_Slider_set_callback)(fl_Slider slider,fl_Callback cb){
Fl_Slider* castedBox = (static_cast<Fl_Slider*>(slider));
new C_to_Fl_Callback(castedBox, cb);
}
FL_EXPORT_C(void*,Fl_Slider_user_data)(fl_Slider slider){
C_to_Fl_Callback* stored_cb = (static_cast<C_to_Fl_Callback*>((static_cast<Fl_Slider*>(slider))->user_data()));
if(stored_cb){
return stored_cb->get_user_data();
}
else {
return (static_cast<Fl_Slider*>(slider))->user_data();
}
}
FL_EXPORT_C(void,Fl_Slider_set_user_data)(fl_Slider slider,void* v){
C_to_Fl_Callback* stored_cb = (static_cast<C_to_Fl_Callback*>((static_cast<Fl_Slider*>(slider))->user_data()));
if (stored_cb) {
stored_cb->set_user_data(v);
(static_cast<Fl_Slider*>(slider))->user_data(stored_cb);
}
else {
(static_cast<Fl_Slider*>(slider))->user_data(v);
}
}
FL_EXPORT_C(long,Fl_Slider_argument)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->argument();
}
FL_EXPORT_C(void,Fl_Slider_set_argument)(fl_Slider slider,long v){
(static_cast<Fl_Slider*>(slider))->argument(v);
}
FL_EXPORT_C(Fl_When,Fl_Slider_when)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->when();
}
FL_EXPORT_C(void,Fl_Slider_set_when)(fl_Slider slider,uchar i){
(static_cast<Fl_Slider*>(slider))->when(i);
}
FL_EXPORT_C(unsigned int,Fl_Slider_visible)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->visible();
}
FL_EXPORT_C(int,Fl_Slider_visible_r)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->visible_r();
}
FL_EXPORT_C(void,Fl_Slider_set_visible)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->visible();
}
FL_EXPORT_C(void,Fl_Slider_clear_visible)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->clear_visible();
}
FL_EXPORT_C(unsigned int,Fl_Slider_active)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->active();
}
FL_EXPORT_C(int,Fl_Slider_active_r)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->active_r();
}
FL_EXPORT_C(void,Fl_Slider_activate)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->activate();
}
FL_EXPORT_C(void,Fl_Slider_deactivate)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->deactivate();
}
FL_EXPORT_C(unsigned int,Fl_Slider_output)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->output();
}
FL_EXPORT_C(void,Fl_Slider_set_output)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->output();
}
FL_EXPORT_C(void,Fl_Slider_clear_output)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->clear_output();
}
FL_EXPORT_C(unsigned int,Fl_Slider_takesevents)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->takesevents();
}
FL_EXPORT_C(void,Fl_Slider_set_changed)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->changed();
}
FL_EXPORT_C(void,Fl_Slider_clear_changed)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->clear_changed();
}
FL_EXPORT_C(int,Fl_Slider_take_focus)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->take_focus();
}
FL_EXPORT_C(void,Fl_Slider_set_visible_focus)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->set_visible_focus();
}
FL_EXPORT_C(void,Fl_Slider_clear_visible_focus)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->clear_visible_focus();
}
FL_EXPORT_C(void,Fl_Slider_modify_visible_focus)(fl_Slider slider,int v){
(static_cast<Fl_Slider*>(slider))->visible_focus(v);
}
FL_EXPORT_C(unsigned int,Fl_Slider_visible_focus)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->visible_focus();
}
FL_EXPORT_C(void,Fl_Slider_do_callback)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->do_callback();
}
FL_EXPORT_C(void,Fl_Slider_do_callback_with_widget_and_user_data)(fl_Slider slider,fl_Widget w,long arg){
(static_cast<Fl_Slider*>(slider))->do_callback((static_cast<Fl_Widget*>(w)),arg);
}
FL_EXPORT_C(void,Fl_Slider_do_callback_with_widget_and_default_user_data)(fl_Slider slider,fl_Widget w){
(static_cast<Fl_Slider*>(slider))->do_callback((static_cast<Fl_Widget*>(w)));
}
FL_EXPORT_C(int,Fl_Slider_contains)(fl_Slider slider,fl_Widget w){
return (static_cast<Fl_Slider*>(slider))->contains((static_cast<Fl_Widget*>(w)));
}
FL_EXPORT_C(int,Fl_Slider_inside)(fl_Slider slider,fl_Widget w){
return (static_cast<Fl_Slider*>(slider))->inside((static_cast<Fl_Widget*>(w)));
}
FL_EXPORT_C(void,Fl_Slider_redraw)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->redraw();
}
FL_EXPORT_C(void,Fl_Slider_redraw_label)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->redraw_label();
}
FL_EXPORT_C(uchar,Fl_Slider_damage)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->damage();
}
FL_EXPORT_C(void,Fl_Slider_clear_damage_with_bitmask)(fl_Slider slider,uchar c){
(static_cast<Fl_Slider*>(slider))->clear_damage(c);
}
FL_EXPORT_C(void,Fl_Slider_clear_damage)(fl_Slider slider){
(static_cast<Fl_Slider*>(slider))->clear_damage();
}
FL_EXPORT_C(void,Fl_Slider_damage_with_text)(fl_Slider slider,uchar c){
(static_cast<Fl_Slider*>(slider))->damage(c);
}
FL_EXPORT_C(void,Fl_Slider_damage_inside_widget)(fl_Slider slider,uchar c,int x,int y,int w,int h){
(static_cast<Fl_Slider*>(slider))->damage(c,x,y,w,h);
}
FL_EXPORT_C(void,Fl_Slider_draw_label_with_xywh_alignment)(fl_Slider slider,int x,int y,int w,int h,Fl_Align alignment){
(static_cast<Fl_Slider*>(slider))->draw_label(x,y,w,h,alignment);
}
FL_EXPORT_C(void,Fl_Slider_measure_label)(fl_Slider slider,int* ww,int* hh){
(static_cast<Fl_Slider*>(slider))->measure_label(*ww,*hh);
}
FL_EXPORT_C(fl_Window, Fl_Slider_window)(fl_Slider slider){
return (fl_Window) (static_cast<Fl_Slider*>(slider))->window();
}
FL_EXPORT_C(fl_Window, Fl_Slider_top_window)(fl_Slider slider){
return (fl_Window) (static_cast<Fl_Slider*>(slider))->top_window();
}
FL_EXPORT_C(fl_Window , Fl_Slider_top_window_offset)(fl_Slider slider, int* xoff, int* yoff){
return (fl_Window) (static_cast<Fl_Slider*>(slider))->top_window_offset(*xoff,*yoff);
}
FL_EXPORT_C(fl_Group,Fl_Slider_as_group)(fl_Slider slider){
return (fl_Group) (static_cast<Fl_Slider*>(slider))->as_group();
}
FL_EXPORT_C(void,Fl_Slider_bounds)(fl_Slider slider,double a,double b){
(static_cast<Fl_Slider*>(slider))->bounds(a,b);
}
FL_EXPORT_C(double,Fl_Slider_minimum)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->minimum();
}
FL_EXPORT_C(void,Fl_Slider_set_minimum)(fl_Slider slider,double a){
(static_cast<Fl_Slider*>(slider))->minimum(a);
}
FL_EXPORT_C(double,Fl_Slider_maximum)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->maximum();
}
FL_EXPORT_C(void,Fl_Slider_set_maximum)(fl_Slider slider,double a){
(static_cast<Fl_Slider*>(slider))->maximum(a);
}
FL_EXPORT_C(void,Fl_Slider_precision)(fl_Slider slider,int precision){
(static_cast<Fl_Slider*>(slider))->precision(precision);
}
FL_EXPORT_C(void,Fl_Slider_range)(fl_Slider slider,double a,double b){
(static_cast<Fl_Slider*>(slider))->range(a,b);
}
FL_EXPORT_C(void,Fl_Slider_set_step)(fl_Slider slider,int a){
(static_cast<Fl_Slider*>(slider))->step(a);
}
FL_EXPORT_C(void,Fl_Slider_set_step_with_a_b)(fl_Slider slider,double a,int b){
(static_cast<Fl_Slider*>(slider))->step(a,b);
}
FL_EXPORT_C(void,Fl_Slider_step_with_s)(fl_Slider slider,double s){
(static_cast<Fl_Slider*>(slider))->step(s);
}
FL_EXPORT_C(double,Fl_Slider_step)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->step();
}
FL_EXPORT_C(double,Fl_Slider_value)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->value();
}
FL_EXPORT_C(int,Fl_Slider_set_value)(fl_Slider slider,double v){
return (static_cast<Fl_Slider*>(slider))->value(v);
}
FL_EXPORT_C(int,Fl_Slider_format)(fl_Slider slider,char* format){
return (static_cast<Fl_Slider*>(slider))->format(format);
}
FL_EXPORT_C(double,Fl_Slider_round)(fl_Slider slider,double v){
return (static_cast<Fl_Slider*>(slider))->round(v);
}
FL_EXPORT_C(double,Fl_Slider_clamp)(fl_Slider slider,double v){
return (static_cast<Fl_Slider*>(slider))->clamp(v);
}
FL_EXPORT_C(double,Fl_Slider_increment)(fl_Slider slider,double v,int n){
return (static_cast<Fl_Slider*>(slider))->increment(v,n);
}
FL_EXPORT_C(fl_Slider, Fl_Slider_New_WithT)(uchar t, int x, int y, int w, int h, const char* label){
Fl_Slider* slider = new Fl_Slider(t,x,y,w,h,label);
return (fl_Slider)slider;
}
FL_EXPORT_C(fl_Fill_Slider, Fl_Fill_Slider_New_WithLabel)(int x, int y, int w, int h, const char* label) {
Fl_Fill_Slider* slider = new Fl_Fill_Slider(x,y,w,h,label);
return (static_cast<fl_Fill_Slider>(slider));
}
FL_EXPORT_C(fl_Fill_Slider, Fl_Fill_Slider_New)(int x, int y, int w, int h) {
Fl_Fill_Slider* slider = new Fl_Fill_Slider(x,y,w,h,0);
return (fl_Fill_Slider)slider;
}
FL_EXPORT_C(fl_Hor_Slider, Fl_Hor_Slider_New_WithLabel)(int x, int y, int w, int h, const char* label) {
Fl_Hor_Slider* slider = new Fl_Hor_Slider(x,y,w,h,label);
return (static_cast<fl_Hor_Slider>(slider));
}
FL_EXPORT_C(fl_Hor_Slider, Fl_Hor_Slider_New)(int x, int y, int w, int h) {
Fl_Hor_Slider* slider = new Fl_Hor_Slider(x,y,w,h,0);
return (fl_Hor_Slider)slider;
}
FL_EXPORT_C(fl_Hor_Nice_Slider, Fl_Hor_Nice_Slider_New_WithLabel)(int x, int y, int w, int h, const char* label) {
Fl_Hor_Nice_Slider* slider = new Fl_Hor_Nice_Slider(x,y,w,h,label);
return (static_cast<fl_Hor_Nice_Slider>(slider));
}
FL_EXPORT_C(fl_Hor_Nice_Slider, Fl_Hor_Nice_Slider_New)(int x, int y, int w, int h) {
Fl_Hor_Nice_Slider* slider = new Fl_Hor_Nice_Slider(x,y,w,h,0);
return (fl_Hor_Nice_Slider)slider;
}
FL_EXPORT_C(fl_Hor_Fill_Slider, Fl_Hor_Fill_Slider_New_WithLabel)(int x, int y, int w, int h, const char* label) {
Fl_Hor_Fill_Slider* slider = new Fl_Hor_Fill_Slider(x,y,w,h,label);
return (static_cast<fl_Hor_Fill_Slider>(slider));
}
FL_EXPORT_C(fl_Hor_Fill_Slider, Fl_Hor_Fill_Slider_New)(int x, int y, int w, int h) {
Fl_Hor_Fill_Slider* slider = new Fl_Hor_Fill_Slider(x,y,w,h,0);
return (fl_Hor_Fill_Slider)slider;
}
FL_EXPORT_C(fl_Nice_Slider, Fl_Nice_Slider_New_WithLabel)(int x, int y, int w, int h, const char* label) {
Fl_Nice_Slider* slider = new Fl_Nice_Slider(x,y,w,h,label);
return (static_cast<fl_Nice_Slider>(slider));
}
FL_EXPORT_C(fl_Nice_Slider, Fl_Nice_Slider_New)(int x, int y, int w, int h) {
Fl_Nice_Slider* slider = new Fl_Nice_Slider(x,y,w,h,0);
return (fl_Nice_Slider)slider;
}
FL_EXPORT_C(void, Fl_Slider_Destroy)(fl_Slider slider){
delete (static_cast<Fl_Slider*>(slider));
}
FL_EXPORT_C(int,Fl_Slider_scrollvalue)(fl_Slider slider,int pos,int size,int first,int total){
return (static_cast<Fl_Slider*>(slider))->scrollvalue(pos,size,first,total);
}
FL_EXPORT_C(float,Fl_Slider_set_slider_size)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->slider_size();
}
FL_EXPORT_C(void,Fl_Slider_slider_size)(fl_Slider slider,double v){
(static_cast<Fl_Slider*>(slider))->slider_size(v);
}
FL_EXPORT_C(Fl_Boxtype,Fl_Slider_slider)(fl_Slider slider){
return (static_cast<Fl_Slider*>(slider))->slider();
}
FL_EXPORT_C(void,Fl_Slider_set_slider)(fl_Slider slider,Fl_Boxtype c){
(static_cast<Fl_Slider*>(slider))->slider(c);
}
FL_EXPORT_C(fl_Slider, Fl_Slider_New)(int X, int Y, int W, int H){
fl_Widget_Virtual_Funcs* fs = Fl_Widget_default_virtual_funcs();
Fl_DerivedSlider* w = new Fl_DerivedSlider(X,Y,W,H,fs);
return (fl_Slider)w;
}
FL_EXPORT_C(fl_Slider, Fl_Slider_New_WithLabel)(int X, int Y, int W, int H, const char* label){
fl_Widget_Virtual_Funcs* fs = Fl_Widget_default_virtual_funcs();
Fl_DerivedSlider* w = new Fl_DerivedSlider(X,Y,W,H,label,fs);
return (fl_Slider)w;
}
FL_EXPORT_C(fl_Slider, Fl_OverriddenSlider_New)(int X, int Y, int W, int H,fl_Widget_Virtual_Funcs* fs){
Fl_DerivedSlider* w = new Fl_DerivedSlider(X,Y,W,H,fs);
return (fl_Slider)w;
}
FL_EXPORT_C(fl_Slider, Fl_OverriddenSlider_New_WithLabel)(int X, int Y, int W, int H, const char* label, fl_Widget_Virtual_Funcs* fs){
Fl_DerivedSlider* w = new Fl_DerivedSlider(X,Y,W,H,label,fs);
return (fl_Slider)w;
}
FL_EXPORT_C(void, Fl_DerivedSlider_draw)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->draw();
}
FL_EXPORT_C(void, Fl_Slider_draw)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->draw_super();
}
FL_EXPORT_C(void, Fl_Slider_draw_super)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->draw_super();
}
FL_EXPORT_C(int, Fl_DerivedSlider_handle)(fl_Slider o, int event){
return (static_cast<Fl_DerivedSlider*>(o))->handle(event);
}
FL_EXPORT_C(int, Fl_Slider_handle)(fl_Slider o, int event){
return (static_cast<Fl_DerivedSlider*>(o))->Fl_Slider::handle(event);
}
FL_EXPORT_C(int, Fl_Slider_handle_super)(fl_Slider o, int event){
return (static_cast<Fl_DerivedSlider*>(o))->handle_super(event);
}
FL_EXPORT_C(void, Fl_DerivedSlider_resize)(fl_Slider o, int x, int y, int w, int h){
(static_cast<Fl_DerivedSlider*>(o))->resize(x,y,w,h);
}
FL_EXPORT_C(void, Fl_Slider_resize)(fl_Slider o, int x, int y, int w, int h){
(static_cast<Fl_DerivedSlider*>(o))->Fl_Slider::resize(x,y,w,h);
}
FL_EXPORT_C(void, Fl_Slider_resize_super)(fl_Slider o, int x, int y, int w, int h){
(static_cast<Fl_DerivedSlider*>(o))->resize_super(x,y,w,h);
}
FL_EXPORT_C(void, Fl_DerivedSlider_show)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->show();
}
FL_EXPORT_C(void, Fl_Slider_show)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->Fl_Slider::show();
}
FL_EXPORT_C(void, Fl_Slider_show_super)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->show_super();
}
FL_EXPORT_C(void, Fl_DerivedSlider_hide)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->hide();
}
FL_EXPORT_C(void, Fl_Slider_hide)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->Fl_Slider::hide();
}
FL_EXPORT_C(void, Fl_Slider_hide_super)(fl_Slider o){
(static_cast<Fl_DerivedSlider*>(o))->hide_super();
}
#ifdef __cplusplus
}
#endif
| mit |
githubmoros/myclinicsoft | application/views/include/sidebar.php | 5795 | <!-- Note: This width of the aside area can be adjusted through LESS/SASS variables -->
<aside id="left-panel">
<!-- User info -->
<div class="login-info">
<span> <!-- User image size is adjusted inside CSS, it should stay as is -->
<a href="javascript:void(0);" id="show-shortcut" data-action="toggleShortcut">
<?php
if($user_info->avatar){
echo '<img src="'.base_url().'uploads/'.$this->client_id.'/profile-picture/'.$user_info->avatar.'" alt="me" class="online" />';
}else{
echo '<img src="'.base_url().'img/avatars/blank.png" alt="me" class="online" />';
}?>
<span>
<?php echo $user_info->username;?>
</span>
<i class="fa fa-angle-down"></i>
</a>
</span>
</div>
<!-- end user info -->
<!-- NAVIGATION : This navigation is also responsive
To make this navigation dynamic please make sure to link the node
(the reference to the nav > ul) after page load. Or the navigation
will not initialize.
-->
<nav>
<!--
NOTE: Notice the gaps after each icon usage <i></i>..
Please note that these links work a bit different than
traditional href="" links. See documentation for details.
-->
<ul>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('dashboard', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__dashboard');?>" href="<?php echo site_url('dashboard'); ?>"><i class="fa fa-lg fa-fw fa-home"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__dashboard');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('patient', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__patients');?>" href="<?php echo site_url('patients'); ?>"><i class="fa fa-lg fa-fw fa-users"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__patients');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('users', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__users');?>" href="<?php echo site_url('user'); ?>"><i class="fa fa-lg fa-fw fa-users"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__users');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('role', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__roles');?>" href="<?php echo site_url('roles'); ?>"><i class="fa fa-lg fa-fw fa-key"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__roles');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('templates', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__templates');?>" href="<?php echo site_url('templates'); ?>"><i class="fa fa-lg fa-fw fa-list"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__templates');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('records', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__records');?>" href="<?php echo site_url('records'); ?>"><i class="fa fa-lg fa-fw fa-address-book"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__records');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('reports', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__reports');?>" href="<?php echo site_url('reports'); ?>"><i class="fa fa-lg fa-fw fa-bar-chart-o"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__reports');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('appointments', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__appointments');?>" href="<?php echo site_url('appointments'); ?>"><i class="fa fa-lg fa-fw fa-calendar"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__appointments');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('countries', $this->role_id, 'view', $this->client_id) : true) { ?>
<li class="hidden">
<a title="<?php echo $this->lang->line('__countries');?>" href="<?php echo site_url('countries'); ?>"><i class="fa fa-lg fa-fw fa-map"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__countries');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('utilities', $this->role_id, 'view', $this->client_id) : true) { ?>
<li class="hidden">
<a title="<?php echo $this->lang->line('__utilities');?>" href="<?php echo site_url('utilities'); ?>"><i class="fa fa-lg fa-fw fa-wrench"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__utilities');?></span></a>
</li>
<?php } ?>
<?php if(($this->role_id != 1) ? $this->Module->has_permission('settings', $this->role_id, 'view', $this->client_id) : true) { ?>
<li>
<a title="<?php echo $this->lang->line('__settings');?>" href="<?php echo site_url('settings'); ?>"><i class="fa fa-lg fa-fw fa-cogs"></i> <span class="menu-item-parent"><?php echo $this->lang->line('__settings');?></span></a>
</li>
<?php } ?>
</ul>
</nav>
<span class="minifyme" data-action="minifyMenu"> <i class="fa fa-arrow-circle-left hit"></i> </span>
</aside> | mit |
innogames/gitlabhq | lib/gitlab/background_migration/copy_merge_request_target_project_to_merge_request_metrics.rb | 848 | # frozen_string_literal: true
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class CopyMergeRequestTargetProjectToMergeRequestMetrics
extend ::Gitlab::Utils::Override
def perform(start_id, stop_id)
ActiveRecord::Base.connection.execute <<~SQL
WITH merge_requests_batch AS #{Gitlab::Database::AsWithMaterialized.materialized_if_supported} (
SELECT id, target_project_id
FROM merge_requests WHERE id BETWEEN #{Integer(start_id)} AND #{Integer(stop_id)}
)
UPDATE
merge_request_metrics
SET
target_project_id = merge_requests_batch.target_project_id
FROM merge_requests_batch
WHERE merge_request_metrics.merge_request_id=merge_requests_batch.id
SQL
end
end
end
end
| mit |
nelango/ViralityAnalysis | src/main/python/RFwithPCA.py | 1969 |
import pandas as pd
import numpy as np
import os
import math
from sklearn import datasets
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn import metrics
# from sklearn.tree import DecisionTreeRegressor #RandomForestClassifier #Classifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import train_test_split
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
from sklearn import preprocessing
# load the iris datasets
# dataset = datasets.load_iris()
def test_run():
data1 = os.path.join("data", "data3.csv")
dataset1 = pd.read_csv(data1)
number = preprocessing.LabelEncoder()
dataset1.apply(number.fit_transform)
# print dataset1.ix[1:5]
dataset = dataset1.as_matrix()
x = dataset[:,1:60]
y = dataset[:,60]
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=.33)
# # y = dataset[:,60]
# x_ =x[0:10000,:]
# # y = dataset[0:10000,60]
# y_ = y[0:10000]
# x_test = x[11001:12001,:]
# # y_test = dataset[1001:1201, -1].astype(int)
# y_test = y[11001:12001]
# print y_test
# create a base classifier used to evaluate a subset of attributes
print "starting"
pca = PCA()#n_components = 2)#DecisionTreeRegressor() #RandomForestClassifier() #ExtraTreesClassifier()
X_reduced = pca.fit_transform(scale(X_train))
model = RandomForestRegressor() #ExtraTreesClassifier()
model.fit(scale(X_reduced), y_train)
print (model.score(scale(X_test),y_test))
y_predict = model.predict(scale(X_test))
df = pd.DataFrame(y_predict)
path = 'data/results_RF_PCA.csv'
# print (model.explained_variance_ratio_)
print "done"
# scores = cross_val_score(model, x, y)
# print (scores.mean())
df.to_csv(path)
if __name__ == "__main__":
test_run()
| mit |
MixedRealityLab/UoNPaperScraper | example.php | 3450 | <?php
/**
* Example usage file.
*
* @author Martin Porcheron <[email protected]>
* @license MIT
*/
require 'vendor/autoload.php';
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Timezone (PHP requirement)
\date_default_timezone_set('Europe/London');
// Research Group eStaffProfile directory
\define('URL_ESP', 'http://www.nottingham.ac.uk/research/groups/mixedrealitylab/people/index.aspx');
// Sleep time between publication scraping requests; if 0, you may crash the
// publications list appliance for the University website
\define('CRAWL_SLEEP', 5);
// Page title
\define('STR_TITLE', 'Publications');
// String for when no DOI is available
\define('STR_NO_DOI', 'No DOI number is available');
// First year to group publications from
\define('GRP_ST', 1990);
// Last year to group publications to
\define('GRP_END', 2020);
// How many years appear in each group
\define('GRP_INC', 5);
// Path for where to save publications by year (%s = year)
\define('PATH_YR', 'build/year/%s.html');
// Path for where to save publications by group (%s = last year, %s = first year)
\define('PATH_GRP', 'build/group/%s-%s.html');
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Logging level
\Porcheron\UonPaperScraper\Log::setLevel(\Porcheron\UonPaperScraper\Log::LOG_VERBOSE);
// Fetch all publications for all staff
$authors = new \Porcheron\UonPaperScraper\Authors(URL_ESP);
$pubs = $authors->publications(true, CRAWL_SLEEP);
if (empty($pubs)) {
die('No publications');
}
// Collate publications by year
$pubsByYear = [];
foreach ($pubs as &$pub) {
$year = $pub->year();
if (empty($year)) {
continue;
}
$doi = $pub->doi();
if (\is_null($doi)) {
$doi = STR_NO_DOI;
}
if (!isset($pubsByYear[$year])) {
$pubsByYear[$year] = [];
}
$cssClass = (count($pubsByYear[$year]) % 2) === 0 ? 'sys_alt' : '';
$html = \sprintf('<li title="%s" class="%s">', $doi, $cssClass);
$html .= $pub->html();
$html .= '</li>';
$pubsByYear[$year][] = $html;
}
unset($pub);
// Create seperate files for each year
foreach ($pubsByYear as $year => $pubs) {
$file = \sprintf(PATH_YR, $year);
$html = '<div id="lookup-publications" class="sys_profilePad ui-tabs-panel ui-widget-content ui-corner-bottom">';
$html .= '<ul class="sys_publicationsListing">';
$html .= \implode('', $pubsByYear[$year]);
$html .= '</ul></div>';
@\mkdir(\dirname($file), 0777, true);
\file_put_contents($file, $html);
}
// Create pages for groups for the website to reduce the total number of pages
$years = \range(GRP_ST, GRP_END, GRP_INC);
$numYears = \count($years) - 1;
for ($i = 0; $i < $numYears; $i++) {
$firstYear = $years[$i];
$lastYear = $years[$i+1]-1;
$html = '';
for ($year = $lastYear; $year >= $firstYear; $year--) {
$file = \sprintf(PATH_YR, $year);
if (\is_file($file)) {
$html .= '<h2 class="headingBackground">'. $year .'</h2>';
$html .= \file_get_contents($file);
}
}
if (empty($html)) {
continue;
}
$html = \sprintf('<h1>%s</h1>%s', STR_TITLE, $html);
$file = \sprintf(PATH_GRP, $lastYear, $firstYear);
@\mkdir(\dirname($file), 0777, true);
\file_put_contents($file, $html);
}
| mit |
vaidehimurarka/dsalgo | src/com/geeksforgeeks/arrays/Combinations.java | 1310 | package com.geeksforgeeks.arrays;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Created by Vaidehi Murarka on 2/5/2017.
*/
public class Combinations {
public void printCombinations(int[] input){
if(input == null || input.length == 0){
return;
}
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
printUtils(input, result, 0, new ArrayList<>());
for(int i = 0; i < result.size(); i++){
for(int j = 0; j < result.get(i).size(); j++){
System.out.print(result.get(i).get(j) + " ");
}
System.out.println();
}
}
private void printUtils(int[] input, ArrayList<ArrayList<Integer>> result, int index, ArrayList<Integer> temp){
if( index == input.length){
return;
}
for(int i = index; i < input.length; i++){
temp.add(input[i]);
result.add((ArrayList<Integer>) temp.clone());
printUtils(input, result, i+1, temp);
temp.remove(temp.indexOf(input[i]));
}
}
public static void main(String[] args){
Combinations combinations = new Combinations();
combinations.printCombinations(new int[]{1,2,3});
}
}
| mit |
judgie79/iGolfTournament | Golf.js/db/courseHoleValidator.js | 808 |
var Promise = require('promise');
var JaySchema = require('jayschema');
var js = new JaySchema();
var holeSchema = require('../schemas/hole.js');
var courseHoleSchema = require('../schemas/courseHole.js');
var Validator = function (hole) {
this.hole = hole;
};
Validator.prototype.validateSchema = function () {
var me = this;
return new Promise(function (resolve, reject) {
js.register(holeSchema);
js.register(courseHoleSchema);
var isValid = js.validate(me.hole, courseHoleSchema);
if (isValid.length == 0) {
resolve();
} else {
reject({ reason: "CourseHole is not compatible to schema", message: "CourseHole is not compatible to schema", validationResult: isValid });
}
});
};
module.exports = Validator; | mit |
wi2/calendar-example | components/front/layout.js | 394 | "use strict";
import React, {Component, cloneElement} from 'react'
import Nav from './nav'
export default class extends Component {
render() {
if(!this.initState)
this.initState = global.__ReactInitState__
return (
<div>
<Nav {...this.initState} />
{this.props.children && cloneElement(this.props.children, {...this.initState})}
</div>
)
}
}
| mit |
ISO-tech/sw-d8 | web/2002-2/418/418_12_AntiNazis.php | 3751 | <html>
<head>
<title>
Keep Nazis out of D.C.!
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<P><font face="Times New Roman, Times, serif" size="4">Activists will confront racist rally at Capitol</font><BR>
<font face="Times New Roman, Times, serif" size="5"><b>Keep Nazis out of D.C.!</b></font></P>
<P><font face="Times New Roman, Times, serif" size="2"><b>By Michael Link and Brian Conway</b></font><font face="Arial, Helvetica, sans-serif" size="2"> | August 23, 2002 | Page 12</font> </P>
<font face="Times New Roman, Times, serif" size="3"><P>ANTIRACISTS are building for an August 24 counter-demonstration against a rally of neo-Nazis and racist skinheads on the steps of the U.S. Capitol building in Washington, D.C.</P>
<P>The Nazi rally was called by the National Alliance (NA), the best-organized white supremacist group in the U.S. NA leaders claim the event will be the "largest gathering of white nationalists at the U.S. Capitol since World War II." </P>
<P>This is the sixth time in just over a year that the NA has sponsored an event in D.C. Its last appearance was an anti-Jewish protest at the Israeli Embassy in May that drew some 250 Nazis and racist skinheads, who masqueraded as the friends of Palestinians. </P>
<P>Taking its cue from the rise of anti-Semitism in Europe, the NA has exploited the September 11 attacks to spread their message of hate. Once again, the Nazi rally will feature fake sympathy for the Palestinian cause.</P>
<P>But the NA and their ilk don't object to racist oppression of Palestinians. In fact, that's their agenda as they seek to create an "all-white America" without Jews, Blacks, gays or non-European immigrants. </P>
<P>Many people think that the best way to respond to these Nazis is to ignore them. This is dead wrong. Even if these groups can't achieve their full aims now, they use rallies like this to organize, grow and gain confidence to commit racist violence.</P>
<P>The D.C. area has seen an increase of hard-core racist activity on our streets, including swastikas and Nazi graffiti on homes and community buildings in Maryland and Virginia. Several hundred thugs standing on the Capitol steps with their arms raised in Nazi salutes will only give them more credibility.</P>
<P>That's why people are mobilizing from D.C. and around the East Coast to oppose the Nazis. We have to organize to confront and combat these racists now--before they can grow and spread their message of hate and violence. </P>
<P>Black and white, native-born and immigrant, Palestinians and Jews need to join together to send a clear message to the NA and to racists everywhere--we'll fight to keep D.C. Nazi free!</P>
<I><P>For information about the counterdemonstration, call 202-667-0049.</P>
</I>
<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| mit |
jods4/router | src/route-filters.js | 1617 | import {Container} from 'aurelia-dependency-injection';
export class RouteFilterContainer {
static inject() {return [Container];}
constructor(container : Container) {
this.container = container;
this.filters = { };
this.filterCache = { };
}
addStep(name : string, step : any, index : number = -1) : void {
let filter = this.filters[name];
if (!filter) {
filter = this.filters[name] = [];
}
if (index === -1) {
index = filter.length;
}
filter.splice(index, 0, step);
this.filterCache = {};
}
getFilterSteps(name : string) {
if (this.filterCache[name]) {
return this.filterCache[name];
}
let steps = [];
let filter = this.filters[name];
if (!filter) {
return steps;
}
for (let i = 0, l = filter.length; i < l; i++) {
if (typeof filter[i] === 'string') {
steps.push(...this.getFilterSteps(filter[i]));
} else {
steps.push(this.container.get(filter[i]));
}
}
return this.filterCache[name] = steps;
}
}
export function createRouteFilterStep(name : string) : Function {
function create(routeFilterContainer) {
return new RouteFilterStep(name, routeFilterContainer);
};
create.inject = function() {
return [RouteFilterContainer];
};
return create;
}
class RouteFilterStep {
isMultiStep: boolean = true;
constructor(name : string, routeFilterContainer : RouteFilterContainer) {
this.name = name;
this.routeFilterContainer = routeFilterContainer;
}
getSteps() {
return this.routeFilterContainer.getFilterSteps(this.name);
}
}
| mit |
vanda/vam-fractal | src/components/groups/image-overlay/image-overlay.config.js | 318 | module.exports = {
title: 'Image Overlay',
label: 'Image Overlay',
variants: [
{
name: 'default',
label: 'Default',
context: {}
},
{
name: 'Cultural Sensitive Image',
label: 'Cultural Sensitive Image',
context: {
offensive_image: true
}
}
]
};
| mit |
daqcri/rayyan-mobile | www/js/services/rayyan.remote.service.js | 11165 | angular.module('rayyan.remote.service', ['rayyan.remote-config.service'])
.factory('rayyanRemoteService', function($http, $localStorage, $ionicPlatform, $q,
RAYYAN_API_CONFIG) {
var config = $localStorage.config,
accessToken = $localStorage.accessToken
$http.defaults.headers.common['Content-Type'] = 'application/json';
var objectToQueryString = function(object, keyPrefix) {
if (!object) return "";
console.log("payload object", object)
var arr = []
// fix _ bug where an existing length property will confuse the each
var length = null
if (_.has(object, "length")) {
length = object.length
delete object.length
}
_.each(object, function(value, key){
var argument
if (_.isFunction(value))
;// not supported
else if (_.isObject(value))
argument = objectToQueryString(value, keyPrefix ? keyPrefix + key : key)
else {
if (keyPrefix)
argument = encodeURIComponent(keyPrefix + "[" + key + "]")
else
argument = encodeURIComponent(key)
argument += '=' + encodeURIComponent(value);
}
arr.push(argument)
})
if (!_.isNull(length)) {
arr.push('length=' + length)
object.length = length
}
console.log("payload arr", arr)
return arr.join("&")
}
var reportError = function(method, endpoint, data, response) {
// TODO central handling for errors
console.log("ERROR IN REQUEST", method, endpoint, data, response)
}
var request = function(method, endpoint, data, noRefreshToken, useAuthBaseURI) {
var deferred = $q.defer();
var req = {
method: method,
url: (useAuthBaseURI ? config.authBaseURI : config.baseURI) + endpoint,
headers: {
"Authorization": "Bearer " + accessToken
}
}
if (data) {
switch (method.toUpperCase()) {
case 'GET':
req.url += "?" + objectToQueryString(data);
break;
default:
req.data = data
}
}
$http(req).then(function(response) {
deferred.resolve(response.data)
// TODO: count received bytes here (take care of gzipping, read Content-Length)
}, function(response) {
console.log("error in http with status", response.status)
if (!noRefreshToken && response.status == 401) {
console.log("Got 401, accessToken [1] must have been expired, trying to refresh using [2], full response [3]",
accessToken, $localStorage.refreshToken, JSON.stringify(response))
continueAuth($localStorage.refreshToken, true)
.then(function(){
console.log("Succeeded in refreshing token and got new token [1] with refresh token [2]",
accessToken, $localStorage.refreshToken)
request(method, endpoint, data)
.then(function(responseData){
deferred.resolve(responseData)
}, function(response){
// main request failed even after refreshing token, report error
deferred.reject(response)
reportError(method, endpoint, data, response)
})
}, function(response){
// failed to refresh accessToken, may be user revoked client, must re-login
// TODO: sometimes if 2 requests are done in parallel, both will give 401, one will refresh and succeed
// the other will refresh (the now outdated token) and fail, cause login screen to appear
console.log("Got 401 again, could not refresh token, user may have revoked access, must re-login, here is response",
JSON.stringify(response))
deferred.reject(response)
reportError(method, endpoint, data, response)
startAuth(); // relogin
})
}
else {
// main request failed (not 401)
deferred.reject(response)
reportError(method, endpoint, data, response)
}
})
return deferred.promise;
}
var requestReviewEndpoint = function(method, endpoint, reviewId, data) {
return request(method, endpoint.replace(":id", reviewId), data)
}
var setAccessToken = function(_accessToken, refreshToken) {
accessToken = _accessToken
$localStorage.accessToken = _accessToken
$localStorage.refreshToken = refreshToken
}
var setBaseURI = function() {
config = RAYYAN_API_CONFIG
$localStorage.config = RAYYAN_API_CONFIG
}
var login = function() {
setBaseURI();
return startAuth();
}
var startAuth = function() {
var deferred = $q.defer()
// https://blog.nraboy.com/2014/07/using-oauth-2-0-service-ionicframework/
$ionicPlatform.ready(function() {
var authorizeURI = config.authBaseURI + "/oauth/authorize?client_id="+config.clientId+"&redirect_uri="+config.redirectURI+"&response_type=code"
var ref = (window.cordova ? cordova.InAppBrowser : window).open(authorizeURI, '_blank', 'location=yes,clearsessioncache=yes,clearcache=yes');
ref.addEventListener('loadstart', function(event) {
if((event.url).indexOf(config.redirectURI) == 0) {
ref.close();
var code = (event.url).split("code=")[1];
continueAuth(code).then(function(){
getUserInfo()
.finally(function(){
deferred.resolve()
})
}, function(){
deferred.reject()
})
}
});
})
return deferred.promise;
}
var continueAuth = function(code, refresh) {
var data = {
client_id: config.clientId,
client_secret: config.clientSecret,
redirect_uri: config.redirectURI,
grant_type: 'authorization_code',
code: code
}
if (refresh) {
data.grant_type = "refresh_token";
data.refresh_token = code;
}
return request('POST', '/oauth/token', data, true, true)
.then(function(data) {
// data = {"access_token":"...","token_type":"bearer","expires_in":7200,"refresh_token":"...","created_at":1440919170}
setAccessToken(data.access_token, data.refresh_token)
})
}
var revoke = function() {
return request('POST', '/oauth/revoke', {token: accessToken}, false, true)
}
var getUserInfo = function() {
return request('GET', '/api/v1/user_info')
.then(function(data){
console.log("got data from getUserInfo", data)
$localStorage.displayName = data.displayName
$localStorage.userId = data.userId
}, function(data) {
$localStorage.displayName = "Unknown"
$localStorage.userId = 0
})
}
var getReviews = function() {
return request('GET', '/api/v1/reviews')
.then(function(data){
console.log("got data from getReviews", data)
var reviews = _.map(data.owned_reviews, function(review){
return _.extend(review, {owner: true})
}).concat(_.map(data.collab_reviews, function(review) {
return _.extend(review, {owner: false})
}))
console.log("refreshed reviews: ", reviews.length)
return reviews
})
}
var transformRemoteFacets = function(facet, facetType) {
// override irrelevant rayyan_ids with searchable values (display)
var overrideValues = function(collection, overrider) {
return _.map(collection, function(facetRow){
var copy = _.clone(facetRow)
copy[1] = _.isFunction(overrider) ? overrider(copy) : copy[0]
return copy
})
}
var hash = {}
var inclusionsMap = {included: 1, excluded: -1, undecided: null, maybe: 0}
switch(facetType) {
case 'inclusions':
hash.inclusions = _.map(facet, function(count, key){
return [
M.capitalize(key),
inclusionsMap[key],
count
]
})
break;
case 'all_labels':
var partitions = _.partition(facet.collection, function(facetRow){
return M.labelPredicate(facetRow[1])
})
hash.labels = partitions[0]
hash.reasons = partitions[1]
_.each(hash.reasons, function(facetRow){
facetRow[0] = M.cleanExclusionReason(facetRow[[0]])
})
break;
case 'keyphrases':
hash.topics = overrideValues(facet.collection)
break;
case 'highlights':
_.each(facet, function(collection, key){
hash['highlights_' + key] = overrideValues(collection)
})
break;
default:
hash[facetType] = facet.collection
}
return hash
}
var getFacets = function(reviewId, facetTypes) {
var promises = {}
var paramsMap = {
labels: 'user_labels',
reasons: 'exclusion_labels',
topics: 'keyphrases',
highlights_1: 'highlights',
highlights_2: 'highlights'
}
// send inclusion counts request if found in facetTypes
if (_.contains(facetTypes, 'inclusions')) {
facetTypes = _.without(facetTypes, 'inclusions')
promises.inclusions = requestReviewEndpoint(
'GET', '/api/v1/reviews/:id/inclusion_counts', reviewId, {force_blind: 1})
}
// send all other facetTypes in a single facets request
if (facetTypes.length > 0) {
var params = _.reduce(facetTypes, function(hash, facetType){
hash[paramsMap[facetType]] = 1
return hash
}, {})
promises.remote = requestReviewEndpoint('GET', '/api/v1/reviews/:id/facets', reviewId, {facets: params})
}
return $q.all(promises)
.then(function(promises){
// transform returned facets from server compressed objects to client releaxed ones
return _.reduce(promises.remote, function(hash, facet, facetType){
return _.extend(hash, transformRemoteFacets(facet, facetType))
}, promises.inclusions
? _.extend({}, transformRemoteFacets(promises.inclusions, 'inclusions'))
: {})
})
}
var getLabels = function(reviewId) {
return requestReviewEndpoint('GET', '/api/v1/reviews/:id/labels', reviewId);
}
var getArticles = function(reviewId, offset, limit) {
return requestReviewEndpoint('GET', '/api/v1/reviews/:id/articles', reviewId, {
start: offset,
length: limit
});
}
var toggleBlind = function(reviewId) {
return requestReviewEndpoint('POST', '/api/v1/reviews/:id/blind', reviewId)
.then(function(data){
return data.is_blind
})
}
var applyCustomization = function(reviewId, articleId, plan, inclusions_etag, labels_etag) {
// plan is an object: {review_id: r, article_id: a, plan: [{key: k1, value: v1}, ...]}
return requestReviewEndpoint('POST', '/api/v1/reviews/:id/customize', reviewId,
{
article_id: articleId,
plan: plan,
inclusions_etag: inclusions_etag,
labels_etag: labels_etag
}
)
}
return {
setAccessToken: setAccessToken,
setBaseURI: setBaseURI,
login: login,
logout: revoke,
getUserInfo: getUserInfo,
getReviews: getReviews,
getFacets: getFacets,
getLabels: getLabels,
getArticles: getArticles,
toggleBlind: toggleBlind,
applyCustomization: applyCustomization
}
})
| mit |
github/codeql | javascript/ql/test/query-tests/Security/CWE-770/tst2.ts | 187 | import express from 'express';
import rateLimiter from './rateLimit';
const app = express();
app.use(rateLimiter);
app.get('/', (req, res) => {
res.sendFile('index.html'); // OK
});
| mit |
uqlibrary/uqlapp-frontend | frontend/app/scripts/modules/uql.authors/controllers/helpController.js | 980 | /**
* Help Controller functionality
*
* Displays a modal window with the help in it
*/
'use strict';
angular.module('uql.authors')
.controller('UqlAuthorsHelpCtrl', ['$uibModal', '$scope', 'UQL_CONFIG_AUTHORS', function ($modal, $scope, UQL_CONFIG_AUTHORS) {
$scope.openHelp = function () {
$modal.open({
templateUrl: UQL_CONFIG_AUTHORS.viewsBaseUrl + '/partials/help.html',
controller: 'UqlAuthorsModalInstanceCtrl',
windowClass: 'uql-authors-modal',
animation: false,
resolve: {
sections: function () {
return UQL_CONFIG_AUTHORS.help;
}
}
});
};
}]).controller('UqlAuthorsModalInstanceCtrl', ['$scope', '$uibModalInstance', 'sections', function ($scope, $modalInstance, sections) {
$scope.sections = sections;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
| mit |
phpchap/symfony-Kanban | lib/model/doctrine/Task.class.php | 279 | <?php
/**
* Task
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package sf_sandbox
* @subpackage model
* @author Your name here
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Task extends BaseTask
{
}
| mit |
yelite/RoomMonitor | db.py | 297 | #coding=utf-8
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
MAIN_DIC = os.path.split(os.path.realpath(__file__))[0]
DB_FILE = os.path.join(MAIN_DIC, 'data.db')
engine = create_engine('sqlite:///{}'.format(DB_FILE))
Session = sessionmaker(bind=engine)
| mit |
pandora2000/elos | lib/elos/index/unindexable.rb | 153 | module Elos::Index::Unindexable
extend ActiveSupport::Concern
class_methods do
def unindex
initialize_for_reindex(true)
end
end
end
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_78/safe/CWE_78__backticks__func_floatval__find_size-interpretation_simple_quote.php | 1212 | <?php
/*
Safe sample
input : backticks interpretation, reading the file /tmp/tainted.txt
sanitize : use of floatval
construction : interpretation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = `cat /tmp/tainted.txt`;
$tainted = floatval($tainted);
$query = "find / size ' $tainted '";
$ret = system($query);
?> | mit |
vbence86/fivenations | src/js/gui/AudioToggle.js | 2107 | /* global window, Phaser */
import Button from './Button';
const ns = window.fivenations;
let muteAudioButton;
let unmuteAudioButton;
/**
* Imitates a Toogle button to switch between Full-Screen and normal mode.
* It incorporates two separate buttons laying on top of one another.
*/
class AudioToggle extends Phaser.Group {
/**
* Instantiate the toogle with the given configuration
* @param {object} config - {x, y}
*/
constructor(config) {
const { game } = ns.game;
super(game);
this.initMuteAudioButton();
this.initUnmuteButton();
this.setCoordinates(config);
}
/**
* Creates the button to toggle the game to Full-Screen mode
*/
initMuteAudioButton() {
const { game } = ns.game;
muteAudioButton = new Button({
customOverFrame: 'roundbtn_mute_onclick.png',
customDownFrame: 'roundbtn_mute_onclick.png',
customOutFrame: 'roundbtn_mute_base.png',
spritesheet: 'gui.buttons',
onClick: () => {
game.sound.setMute();
muteAudioButton.visible = false;
unmuteAudioButton.visible = true;
},
});
this.add(muteAudioButton);
}
/**
* Creates the button to toggle the game back to normal mode
*/
initUnmuteButton() {
const { game } = ns.game;
unmuteAudioButton = new Button({
customOverFrame: 'roundbtn_mutebtb_invers_onclick.png',
customDownFrame: 'roundbtn_mutebtb_invers_onclick.png',
customOutFrame: 'roundbtn_mutebtb_invers_base.png',
spritesheet: 'gui.buttons',
onClick: () => {
game.sound.muteOnPause = false;
game.sound.unsetMute();
muteAudioButton.visible = true;
unmuteAudioButton.visible = false;
},
});
unmuteAudioButton.visible = false;
this.add(unmuteAudioButton);
}
/**
* Sets the coordinates based on the passed object that must contain
* at least x and y attributes
* @param {object} - x, y
*/
setCoordinates({ x, y }) {
this.x = x;
this.y = y;
this.fixedToCamera = true;
this.cameraOffset.setTo(x, y);
}
}
export default AudioToggle;
| mit |
kev280/Frogger | Frogger/Game.cpp | 3374 | #include "Game.h"
Game::Game()
{
// Créer nos objets
Sprite* background = new Sprite("Images/Frogger Background.bmp");
background->SetPosition(0, 0);
for (int i = 0; i < 5; i++)
{
int offset = 115;
Car1* car1 = new Car1();
car1->SetPosition(570 - i * offset, 430);
cars.push_back(car1);
}
for (int i = 0; i < 5; i++)
{
int offset = 115;
Car2* car2 = new Car2();
car2->SetPosition(570 - i * offset, 400);
cars.push_back(car2);
}
for (int i = 0; i < 5; i++)
{
int offset = 115;
Car3* car3 = new Car3();
car3->SetPosition(570 - i * offset, 365);
cars.push_back(car3);
}
for (int i = 0; i < 5; i++)
{
int offset = 115;
Car4* car4 = new Car4();
car4->SetPosition(-10 + i * offset, 330);
cars.push_back(car4);
}
for (int i = 0; i < 5; i++)
{
int offset = 115;
Car5* car5 = new Car5();
car5->SetPosition(570 - i * offset, 295);
cars.push_back(car5);
}
const int offset = 115;
int minOffset = 25;
// Genarate bundle of 3 turtles with a space between each bundle
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
Turtle* turtlepack1 = new Turtle();
turtlepack1->SetPosition(570 - (j * minOffset + i * offset), 220);
turtles.push_back(turtlepack1);
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
{
Turtle* turtlepack2 = new Turtle();
turtlepack2->SetPosition(570 - (j * minOffset + i * offset), 115);
turtles.push_back(turtlepack2);
}
}
for (int i = 0; i < 5; i++)
{
int offset = 115;
Log1* log1 = new Log1();
log1->SetPosition(570 - i * offset, 185);
logs.push_back(log1);
}
for (int i = 0; i < 3; i++)
{
int offset = 230;
Log2* log2 = new Log2();
log2->SetPosition(570 - i * offset, 148);
logs.push_back(log2);
}
for (int i = 0; i < 5; i++)
{
int offset = 115;
Log3* log3 = new Log3();
log3->SetPosition(570 - i * offset, 80);
logs.push_back(log3);
}
frog = new Frog();
frog->SetPosition(258, 475);
}
Game::~Game()
{
}
void Game::Update()
{
Rectangle* frogRect = new Rectangle(frog->GetX() ,frog->GetY() , 21, 15);
// Check if frog collides with cars
for (int i = 0; i < cars.size(); i++)
{
Rectangle* carRect = new Rectangle(cars[i]->GetX(), cars[i]->GetY(), 21, 15);
if (frogRect->CollidesWith(carRect))
{
// Respawn frog to start position and lose 1 life
frog->Die();
}
}
// Check if frog collides with logs
for (int i = 0; i < logs.size(); i++)
{
Rectangle* logRect = new Rectangle(logs[i]->GetX(), logs[i]->GetY(), 96, 17);
if (frogRect->CollidesWith(logRect))
{
frog->MatchSpeed(logs[i]->GetSpeed());
// Make frog stay on the log while moving
//frog->SetPosition(logs[i]->GetX(), logs[i]->GetY());
}
}
// Check if frog collides with turtles
for (int i = 0; i < turtles.size(); i++)
{
Rectangle* turtleRect = new Rectangle(turtles[i]->GetX(), turtles[i]->GetY(), 21, 15);
if (frogRect->CollidesWith(turtleRect))
{
// Make frog stay on turtles while moving
frog->SetPosition(turtles[i]->GetX(), turtles[i]->GetY());
}
}
// Prevent the player to get out of bounds
if (frog->GetX() <= 0 || frog->GetX() >= 516 || frog->GetY() <= 0 || frog->GetY() >= 560)
{
frog->Die();
}
}
| mit |
PieterD/glimmer | win/window.go | 2421 | package win
import (
"runtime"
"github.com/go-gl/gl/v2.1/gl"
"github.com/go-gl/glfw/v3.2/glfw"
)
// Represents a single window.
type Window struct {
id uint64
gw *glfw.Window
closing chan struct{}
closed chan struct{}
pev chan interface{}
ev chan interface{}
}
func (w *Window) run(f func(*Window)) {
runtime.LockOSThread()
w.gw.MakeContextCurrent()
glfw.SwapInterval(1)
gl.Init()
f(w)
}
// Swap the front and back buffers.
func (w *Window) Swap() {
w.gw.SwapBuffers()
}
// Return this window's event channel.
func (w *Window) Events() <-chan interface{} {
return w.ev
}
// Try to read a single event off the event channel, or return nil if none are buffered.
func (w *Window) Poll() interface{} {
for {
select {
case ie := <-w.Events():
return ie
default:
return nil
}
}
}
// Close this window.
func (w *Window) Destroy() {
close(w.closing)
<-w.closed
}
func (w *Window) initialize() {
w.closing = make(chan struct{})
w.closed = make(chan struct{})
w.pev = make(chan interface{}, 10)
w.ev = make(chan interface{}, 1000)
go func() {
in := w.pev
out := w.ev
out = nil
// TODO: Buffer this so we never block?
var stored interface{}
defer close(w.closed)
defer close(w.ev)
for {
select {
case e := <-in:
stored = e
in = nil
out = w.ev
case out <- stored:
stored = nil
in = w.pev
out = nil
case <-w.closing:
go func() {
for range w.pev {
}
}()
return
}
}
}()
w.gw.SetSizeCallback(func(gw *glfw.Window, width, height int) {
w.pev <- EventResize{
Width: width,
Height: height,
}
})
w.gw.SetCloseCallback(func(gw *glfw.Window) {
w.pev <- EventClose{}
})
w.gw.SetKeyCallback(func(gw *glfw.Window, key glfw.Key, scanCode int, action glfw.Action, mod glfw.ModifierKey) {
w.pev <- EventKey{
Key: Key(key),
ScanCode: scanCode,
Action: Action(action),
Mod: Mod(mod),
}
})
w.gw.SetCharCallback(func(gw *glfw.Window, key rune) {
w.pev <- EventChar{
Char: key,
}
})
w.gw.SetCursorPosCallback(func(gw *glfw.Window, x, y float64) {
w.pev <- EventMousePos{
X: int(x),
Y: int(y),
}
})
w.gw.SetMouseButtonCallback(func(gw *glfw.Window, button glfw.MouseButton, action glfw.Action, mod glfw.ModifierKey) {
w.pev <- EventMouseButton{
Button: Button(button),
Action: Action(action),
Mod: Mod(mod),
}
})
}
| mit |
mathiasbynens/unicode-data | 5.0.0/blocks/Glagolitic-code-points.js | 933 | // All code points in the Glagolitic block as per Unicode v5.0.0:
[
0x2C00,
0x2C01,
0x2C02,
0x2C03,
0x2C04,
0x2C05,
0x2C06,
0x2C07,
0x2C08,
0x2C09,
0x2C0A,
0x2C0B,
0x2C0C,
0x2C0D,
0x2C0E,
0x2C0F,
0x2C10,
0x2C11,
0x2C12,
0x2C13,
0x2C14,
0x2C15,
0x2C16,
0x2C17,
0x2C18,
0x2C19,
0x2C1A,
0x2C1B,
0x2C1C,
0x2C1D,
0x2C1E,
0x2C1F,
0x2C20,
0x2C21,
0x2C22,
0x2C23,
0x2C24,
0x2C25,
0x2C26,
0x2C27,
0x2C28,
0x2C29,
0x2C2A,
0x2C2B,
0x2C2C,
0x2C2D,
0x2C2E,
0x2C2F,
0x2C30,
0x2C31,
0x2C32,
0x2C33,
0x2C34,
0x2C35,
0x2C36,
0x2C37,
0x2C38,
0x2C39,
0x2C3A,
0x2C3B,
0x2C3C,
0x2C3D,
0x2C3E,
0x2C3F,
0x2C40,
0x2C41,
0x2C42,
0x2C43,
0x2C44,
0x2C45,
0x2C46,
0x2C47,
0x2C48,
0x2C49,
0x2C4A,
0x2C4B,
0x2C4C,
0x2C4D,
0x2C4E,
0x2C4F,
0x2C50,
0x2C51,
0x2C52,
0x2C53,
0x2C54,
0x2C55,
0x2C56,
0x2C57,
0x2C58,
0x2C59,
0x2C5A,
0x2C5B,
0x2C5C,
0x2C5D,
0x2C5E,
0x2C5F
]; | mit |
linkdd/sdl-game-engine | src/engine.cpp | 4415 | #include <sge/engine.hpp>
using namespace std;
namespace sge
{
Engine::Engine(Configuration &configuration)
: _configuration(configuration),
_sdl_init(make_shared<SDLInitializer>()),
_sdl_img_init(make_shared<SDLImageInitializer>()),
_sdl_mixer_init(make_shared<SDLMixerInitializer>(
configuration.geti("audio/frequency", 44100),
configuration.geti("audio/channels", 2),
configuration.geti("audio/chunksize", 1024)
)),
_sdl_fonts_init(make_shared<SDLFontsInitializer>()),
_sdl_window_init(make_shared<SDLWindowInitializer>(
configuration.geti("display/width", 640),
configuration.geti("display/height", 480),
configuration.getb("display/fullscreen", false),
configuration.getb("display/resizable", false),
configuration.gets("display/scale", "none")
)),
_mloop(configuration.geti("fps", 60)),
_audiomgr(*this),
_scmgr(*this),
_nodemgr(*this),
_pmgr(*this),
_asset_file_locator(make_shared<FileLocator>(configuration.gets("assets/file/location", ""))),
_asset_image_loader(make_shared<ImageLoader>()),
_asset_audio_loader(make_shared<AudioLoader>()),
_asset_font_loader(make_shared<FontLoader>()),
_asset_json_loader(make_shared<JSONLoader>())
{
_startup.add_initializer(_sdl_init);
_startup.add_initializer(_sdl_img_init);
_startup.add_initializer(_sdl_mixer_init);
_startup.add_initializer(_sdl_fonts_init);
_startup.add_initializer(_sdl_window_init);
_assets.register_locator(_asset_file_locator);
_assets.register_loader(_asset_font_loader, {"ttf"});
_assets.register_loader(_asset_json_loader, {"json"});
_assets.register_loader(
_asset_image_loader,
{
"png",
"bmp",
"jpg", "jpeg",
"tga",
"pnm", "pbm", "pgm", "ppm",
"xpm",
"xcf",
"pcx",
"gif",
"tif", "tiff",
"lbm", "iff"
}
);
_assets.register_loader(
_asset_audio_loader,
{
"wav",
"voc",
"midi",
"mod",
"s3m",
"it",
"xm",
"ogg",
"mp3"
}
);
_mloop.queue_event_handler(SDL_QUIT, [&](SDL_Event *) { _mloop.quit(); return true; });
_mloop.add_event_watcher([&](SDL_Event *evt) { return _amgr.event_handler(evt); });
_mloop.add_event_watcher([&](SDL_Event *evt) { return _scmgr.event_handler(evt); });
_mloop.queue_process_handler([&](Uint32 delta) { _scmgr.process_handler(delta); });
_mloop.queue_process_handler([&](Uint32 delta) { _pmgr.process_handler(delta); });
_mloop.queue_draw_handler([&]() { renderer().clear(); });
_mloop.queue_draw_handler([&]() { _scmgr.draw_handler(); });
_mloop.queue_draw_handler([&]() { renderer().present(); });
}
Engine::~Engine()
{
_startup.shutdown();
}
void Engine::init()
{
try
{
_startup.initialize();
}
catch(const InitError &e)
{
_startup.shutdown();
throw e;
}
_renderer.set_renderer(_sdl_window_init->renderer());
}
Configuration &Engine::configuration()
{
return _configuration;
}
Startup &Engine::startup()
{
return _startup;
}
MainLoop &Engine::mainloop()
{
return _mloop;
}
ActionManager &Engine::actions()
{
return _amgr;
}
AudioManager &Engine::audio()
{
return _audiomgr;
}
AssetManager &Engine::assets()
{
return _assets;
}
SceneManager &Engine::scenes()
{
return _scmgr;
}
NodeManager &Engine::nodes()
{
return _nodemgr;
}
PhysicManager &Engine::physics()
{
return _pmgr;
}
SDL_Window *Engine::window() const
{
return _sdl_window_init->window();
}
Renderer &Engine::renderer()
{
return _renderer;
}
}
| mit |
malcolmevans/Reel-Hoopers | client/templates/push/push.js | 584 | Template.pushForm.events({
'submit': function(e){
e.preventDefault();
var template = Template.instance();
var title = template.$('input[name=title]').val();
var description = template.$('input[name=description]').val();
Push.send({
from: 'Reel Hoopers',
title: title,
text: description,
query: {}
});
//if (Meteor.users.findOne("EYoTyqRwaqxiG5asdsa84y")){
//sAlert.warning('Your message', configOverwrite);
// }
e.target.notificationTitle.value = '';
e.target.notificationDescription.value = '';
}
}); | mit |
dechoD/Telerik-Homeworks | Module I Homeworks/Pre Course Homework/JavaScript Part 1/Strings/Problem8.js | 1010 | console.log('Problem 8');
console.log('test');
var resultString,
sampleString;
sampleString = '<p>Please visit <a href="http://academy.telerik. com">our site</a> to choose a training course. Also visit <a href="www.devbg.org">our forum</a> to discuss the courses.</p>';
function replaceAnchorTags(htmlString) {
var result;
console.log('in replaceAnchor');
function replaceAll(string, toReplace, replaceWith) {
var indexOfOccurrence;
console.log('in replaceAll');
while (true) {
indexOfOccurrence = string.indexOf(toReplace);
if (indexOfOccurrence < 0) {
break;
}
string = string.replace(toReplace, replaceWith);
}
return string;
}
result = replaceAll(htmlString, '<a href="', '[URL=')
result = replaceAll(result, '">', ']');
result = replaceAll(result, '</a>', '[/URL]');
return result;
}
resultString = replaceAnchorTags(sampleString);
console.log(resultString); | mit |
baviereteam/mapwriter-admin-client | src/main/java/net/baviereteam/minecraft/mapwriteradmin/interfaces/ServerInterface.java | 6820 | package net.baviereteam.minecraft.mapwriteradmin.interfaces;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import net.baviereteam.minecraft.mapwriteradmin.ToolBag;
import net.baviereteam.minecraft.mapwriteradmin.domain.Server;
import net.baviereteam.minecraft.mapwriteradmin.json.OperationResult;
public class ServerInterface {
private boolean deleteForReal = false;
private Gson gson = new Gson();
// Returns a list of all the servers
public String list() {
// Reset deletion security
deleteForReal = false;
// Only parameter required is the master key
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("userKey", ToolBag.getInstance().getUsedKey());
try {
// Execute the server command
OperationResult result = ToolBag.getInstance().getWebConnector().execute(
"server/list", parameters);
StringBuilder sb = new StringBuilder();
// Operation success
if(result.getResult()) {
sb.append("Execution success.\n");
List servers = (List) result.getResultingObject(Server.class);
if(servers == null) {
sb.append("No results.");
}
else {
sb.append(servers.size() + " results:\n");
for(Object item : servers) {
// Converting the inner object
Server server = (Server) item;
sb.append(server.toString());
sb.append("\n");
}
}
}
// Operation failed on server
else {
sb.append("Execution failed.\n");
sb.append("Server answered: ");
sb.append(result.getErrorMessage());
}
return sb.toString();
}
catch(Exception e) {
return e.getMessage();
}
}
// Create a minecraft server
public String create(String name) {
// Reset deletion security
deleteForReal = false;
// Parameters are the name of the server and the master key.
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("userKey", ToolBag.getInstance().getUsedKey());
parameters.put("name", name);
try {
// Execute the server command
OperationResult result = ToolBag.getInstance().getWebConnector().execute(
"server/create", parameters);
StringBuilder sb = new StringBuilder();
// Operation success
if(result.getResult()) {
sb.append("Execution success.\n");
// Converting the inner object
Server server = (Server) result.getResultingObject(Server.class);
if(server == null) {
sb.append("No results.");
}
else {
sb.append("Result:\n");
sb.append(server.toString());
}
}
// Operation failed on server
else {
sb.append("Execution failed.\n");
sb.append("Server answered: ");
sb.append(result.getErrorMessage());
}
return sb.toString();
}
catch(Exception e) {
return e.getMessage();
}
}
// Select (locally) a Server ID to work on.
public String select(int serverId) {
// Reset deletion security
deleteForReal = false;
ToolBag.getInstance().setSelectedServerId(serverId);
return "Selected server with ID " + serverId;
}
// Rename the selected server
public String rename(String name) {
// Reset deletion security
deleteForReal = false;
if(ToolBag.getInstance().getSelectedServerId() == 0) {
return "No server selected !";
}
// Parameters are the master key and the new name
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("userKey", ToolBag.getInstance().getUsedKey());
parameters.put("name", name);
try {
// Execute the server command
OperationResult result = ToolBag.getInstance().getWebConnector().execute(
"server/rename/" + ToolBag.getInstance().getSelectedServerId() , parameters);
StringBuilder sb = new StringBuilder();
// Operation success
if(result.getResult()) {
sb.append("Execution success.\n");
// Converting the inner object
Server server = (Server) result.getResultingObject(Server.class);
if(server == null) {
sb.append("No results.");
}
else {
sb.append("Result:\n");
sb.append(server.toString());
}
}
// Operation failed on server
else {
sb.append("Execution failed.\n");
sb.append("Server answered: ");
sb.append(result.getErrorMessage());
}
return sb.toString();
}
catch(Exception e) {
return e.getMessage();
}
}
// Change the key of the selected server
public String changekey() {
// Reset deletion security
deleteForReal = false;
if(ToolBag.getInstance().getSelectedServerId() == 0) {
return "No server selected !";
}
// Only parameter required is the master key
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("userKey", ToolBag.getInstance().getUsedKey());
try {
// Execute the server command
OperationResult result = ToolBag.getInstance().getWebConnector().execute(
"server/changekey/" + ToolBag.getInstance().getSelectedServerId() , parameters);
StringBuilder sb = new StringBuilder();
// Operation success
if(result.getResult()) {
sb.append("Execution success.\n");
// Converting the inner object
Server server = (Server) result.getResultingObject(Server.class);
if(server == null) {
sb.append("No results.");
}
else {
sb.append("Result:\n");
sb.append(server.toString());
}
}
// Operation failed on server
else {
sb.append("Execution failed.\n");
sb.append("Server answered: ");
sb.append(result.getErrorMessage());
}
return sb.toString();
}
catch(Exception e) {
return e.getMessage();
}
}
// Delete the selected server
public String delete() {
if(!deleteForReal) {
deleteForReal = true;
return "Please type the command again to confirm deletion of this server. There is no coming back !";
}
if(ToolBag.getInstance().getSelectedServerId() == 0) {
return "No server selected !";
}
// Only parameter required is the master key
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("userKey", ToolBag.getInstance().getUsedKey());
try {
// Execute the server command
OperationResult result = ToolBag.getInstance().getWebConnector().execute(
"server/delete/" + ToolBag.getInstance().getSelectedServerId() , parameters);
StringBuilder sb = new StringBuilder();
// Operation success
if(result.getResult()) {
sb.append("Execution success.\n");
}
// Operation failed on server
else {
sb.append("Execution failed.\n");
sb.append("Server answered: ");
sb.append(result.getErrorMessage());
}
return sb.toString();
}
catch(Exception e) {
return e.getMessage();
}
}
}
| mit |
siddharthbhagwan/devmate | test/dummy/config/application.rb | 2571 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require "devmate"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
| mit |
surfingRen/oceancode-web | src/main/java/cn/com/oceancode/service/TTReturnObj.java | 557 | package cn.com.oceancode.service;
public class TTReturnObj {
String msg = null;
Throwable e = null;
public TTReturnObj(String msg) {
super();
this.msg = msg;
}
public TTReturnObj(String msg, Throwable e) {
super();
this.msg = msg;
this.e = e;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Throwable getE() {
return e;
}
public void setE(Throwable e) {
this.e = e;
}
public boolean hasException() {
if (getE() != null) {
return true;
}
return false;
}
}
| mit |
SvitlanaShepitsena/remax16 | app/scripts/sections/home/homeRoutes.js | 225 | (function () {
'use strict'
angular.module('sections.home', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
/*=home*/
//#state'
});
})();
| mit |
alsatian-test/alsatian | packages/alsatian/core/utils/remove-item-by-index.ts | 117 | export function removeItemByIndex(array: Array<any>, index: number) {
return array.filter((v, i) => i !== index);
}
| mit |
porscheinformatik/selenium-components | src/main/java/at/porscheinformatik/seleniumcomponents/SeleniumComponentListFactory.java | 4564 | package at.porscheinformatik.seleniumcomponents;
import static at.porscheinformatik.seleniumcomponents.SeleniumUtils.*;
import java.util.Collections;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Creates {@link SeleniumComponentList}s
*
* @author ham
* @param <CHILD_TYPE> the type of the child components
*/
public class SeleniumComponentListFactory<CHILD_TYPE extends SeleniumComponent>
{
/**
* Creates a {@link SeleniumComponentListFactory}, that uses the specified component as template.
*
* @param <CHILD_TYPE> the type of the child
* @param template the template
* @return a list factory
*/
public static <CHILD_TYPE extends SeleniumComponent & SeleniumComponentTemplate<CHILD_TYPE>> SeleniumComponentListFactory<CHILD_TYPE> of(
CHILD_TYPE template)
{
return of(template.parent(), template.selector(), template::create);
}
/**
* Creates a {@link SeleniumComponentListFactory}, that uses the specified component as template.
*
* @param <CHILD_TYPE> the type of the child
* @param parent the parent
* @param template the template
* @return a list factory
*/
public static <CHILD_TYPE extends SeleniumComponent> SeleniumComponentListFactory<CHILD_TYPE> of(
SeleniumComponent parent, SeleniumComponentTemplate<CHILD_TYPE> template)
{
return of(parent, template.selector(), template::create);
}
/**
* Creates a {@link SeleniumComponentListFactory}, that uses the specified selector and factory to create the child
* instances.
*
* @param <CHILD_TYPE> the type of the child components
* @param parent the parent
* @param childSelector the selector for the children
* @param childFactory the factory for the children
* @return the factory
*/
public static <CHILD_TYPE extends SeleniumComponent> SeleniumComponentListFactory<CHILD_TYPE> of(
SeleniumComponent parent, WebElementSelector childSelector, SeleniumComponentFactory<CHILD_TYPE> childFactory)
{
return new SeleniumComponentListFactory<>(parent, childSelector, childFactory);
}
private final SeleniumComponent parent;
private final WebElementSelector childSelector;
private final SeleniumComponentFactory<CHILD_TYPE> childFactory;
/**
* Creates a new factory
*
* @param parent the parent component
* @param childSelector the selector for the child components
* @param childFactory the factory for the child components
*/
public SeleniumComponentListFactory(SeleniumComponent parent, WebElementSelector childSelector,
SeleniumComponentFactory<CHILD_TYPE> childFactory)
{
super();
this.parent = parent;
this.childSelector = childSelector;
this.childFactory = childFactory;
}
/**
* Selects a child by the specified selector. Use this, if you already know how to selected a specified entry (this
* is much faster search {@link #find(Predicate)}ing it). But there is no guarantee, that the child exists. It's
* like directly selecting it e.g. by it's Selenium key.
*
* @param selector the selector
* @return the child
*/
public CHILD_TYPE select(WebElementSelector selector)
{
return childFactory.create(parent, selector);
}
/**
* Returns the first child, that matches the predicate. This method is just a wrapper that uses the
* {@link #findAll()} and {@link SeleniumComponentList#find(Predicate)} method. Please prefer to cache the result of
* {@link #findAll()} instead of calling {{@link #find(Predicate)} multiple times.
*
* @param predicate the predicate
* @return the child, null if not found
*/
public CHILD_TYPE find(Predicate<CHILD_TYPE> predicate)
{
return retryOnStale(() -> findAll().find(predicate));
}
/**
* Returns a list of all components that match the selector.
*
* @return the list, never null
*/
public SeleniumComponentList<CHILD_TYPE> findAll()
{
if (!parent.isReady())
{
return new SeleniumComponentList<>(Collections.emptyList());
}
return new SeleniumComponentList<>(childSelector
.findAll(parent.element())
.stream()
.map(element -> childFactory
.create(parent, WebElementSelector.selectElement(childSelector.toString(), element)))
.collect(Collectors.toList()));
}
}
| mit |
romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/Qualcomm/ASF5LumaFilter07.php | 866 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Qualcomm;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class ASF5LumaFilter07 extends AbstractTag
{
protected $Id = 'asf5_luma_filter[7]';
protected $Name = 'ASF5LumaFilter07';
protected $FullName = 'Qualcomm::Main';
protected $GroupName = 'Qualcomm';
protected $g0 = 'MakerNotes';
protected $g1 = 'Qualcomm';
protected $g2 = 'Camera';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'ASF5 Luma Filter 07';
protected $flag_Permanent = true;
}
| mit |
mplaine/xformsdb | src/fi/tkk/tml/xformsdb/handler/XFormsDBWidgetQueryAllHandler.java | 7461 | package fi.tkk.tml.xformsdb.handler;
import javax.servlet.http.HttpSession;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Node;
import nu.xom.Nodes;
import nu.xom.XPathContext;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import fi.tkk.tml.xformsdb.core.Constants;
import fi.tkk.tml.xformsdb.dao.DAOFactory;
import fi.tkk.tml.xformsdb.dao.XFormsDBDAO;
import fi.tkk.tml.xformsdb.dao.exist.ExistDAOFactory;
import fi.tkk.tml.xformsdb.dao.xmldocument.XMLDocumentDAOFactory;
import fi.tkk.tml.xformsdb.error.DAOException;
import fi.tkk.tml.xformsdb.error.ErrorConstants;
import fi.tkk.tml.xformsdb.error.HandlerException;
import fi.tkk.tml.xformsdb.error.ManagerException;
import fi.tkk.tml.xformsdb.manager.xformsdb.XFormsDBWidgetDataSourcesManager;
import fi.tkk.tml.xformsdb.servlet.XFormsDBServlet;
import fi.tkk.tml.xformsdb.util.IOUtils;
import fi.tkk.tml.xformsdb.xml.to.xformsdb.XFormsDBConfigTO;
/**
* Handle the <xformsdb:widgetquery> ALL queries.
*
*
* @author Markku Laine
* @version 1.0 Created on October 23, 2009
*/
public class XFormsDBWidgetQueryAllHandler extends ResponseHandler {
// PRIVATE STATIC FINAL VARIABLES
private static final Logger logger = Logger.getLogger( XFormsDBWidgetQueryAllHandler.class );
// PUBLIC CONSTURCTORS
public XFormsDBWidgetQueryAllHandler() {
logger.log( Level.DEBUG, "Constructor has been called." );
}
// PRIVATE METHODS
private XFormsDBDAO getXFormsDBDAO( XFormsDBServlet xformsdbServlet, HttpSession session, Document document, String encoding ) throws HandlerException {
logger.log( Level.DEBUG, "Method has been called." );
XFormsDBDAO xformsdbDAO = null;
try {
// Retrieve the name of the widget data source to be used
String dataSrc = document.getRootElement().getAttributeValue( "datasrc" );
// Retrieve XFormsDB widget data sources from the session
String xformsdbWidgetDataSources = XFormsDBWidgetDataSourcesManager.getXFormsDBWidgetDataSources( session );
// Build a XOM document
Builder builder = new Builder();
Document xformsdbWidgetDataSourcesDocument = builder.build( IOUtils.convert( xformsdbWidgetDataSources, encoding ) );
// Retrieve the correct widget data source
Nodes xformsdbWidgetDataSourceNodes = xformsdbWidgetDataSourcesDocument.query( "xformsdb:widget-data-sources/xformsdb:widget-data-source[ @id = '" + dataSrc + "' ]", new XPathContext( Constants.NAMESPACE_PREFIX_XFORMSDB, Constants.NAMESPACE_URI_XFORMSDB ) );
if ( xformsdbWidgetDataSourceNodes == null || ( xformsdbWidgetDataSourceNodes != null && xformsdbWidgetDataSourceNodes.size() == 0 ) ) {
throw new DAOException( ErrorConstants.ERROR_CODE_DAO_130, ErrorConstants.ERROR_MESSAGE_DAO_130 );
}
// Retrieve the correct widget data source
Node xformsdbWidgetDataSourceNode = xformsdbWidgetDataSourceNodes.get( 0 );
// Retrieve values for the DAO data source
Nodes typeNodes = xformsdbWidgetDataSourceNode.query( "xformsdb:type/text()", new XPathContext( "xformsdb", "http://www.tml.tkk.fi/2007/xformsdb" ) );
String type = "";
if ( typeNodes.size() > 0 ) {
type = typeNodes.get( 0 ).toXML();
}
Nodes uriNodes = xformsdbWidgetDataSourceNode.query( "xformsdb:uri/text()", new XPathContext( "xformsdb", "http://www.tml.tkk.fi/2007/xformsdb" ) );
String uri = "";
if ( uriNodes.size() > 0 ) {
uri = uriNodes.get( 0 ).toXML();
}
Nodes usernameNodes = xformsdbWidgetDataSourceNode.query( "xformsdb:username/text()", new XPathContext( "xformsdb", "http://www.tml.tkk.fi/2007/xformsdb" ) );
String username = "";
if ( usernameNodes.size() > 0 ) {
username = usernameNodes.get( 0 ).toXML();
}
Nodes passwordNodes = xformsdbWidgetDataSourceNode.query( "xformsdb:password/text()", new XPathContext( "xformsdb", "http://www.tml.tkk.fi/2007/xformsdb" ) );
String password = "";
if ( passwordNodes.size() > 0 ) {
password = passwordNodes.get( 0 ).toXML();
}
Nodes collectionNodes = xformsdbWidgetDataSourceNode.query( "xformsdb:collection/text()", new XPathContext( "xformsdb", "http://www.tml.tkk.fi/2007/xformsdb" ) );
String collection = "";
if ( collectionNodes.size() > 0 ) {
collection = collectionNodes.get( 0 ).toXML();
}
// Retrieve the XFormsDB DAO of the appropriate DAO Factory implementation
DAOFactory daoFactory = null;
// Set the DAO Factory
int dataSourceType = Integer.parseInt( type );
switch ( dataSourceType ) {
case DAOFactory.XML_DOCUMENT:
daoFactory = ( XMLDocumentDAOFactory ) DAOFactory.getDAOFactory( DAOFactory.XML_DOCUMENT );
break;
case DAOFactory.EXIST:
daoFactory = ( ExistDAOFactory ) DAOFactory.getDAOFactory( DAOFactory.EXIST );
break;
default:
throw new DAOException( "Illegal widget data source type value '" + dataSourceType + "' in the <xformsdb:widget-data-source" + ( ( dataSrc != null ) ? " id=\"" + dataSrc + "\">" : ">" ) + " element." );
}
// Set DAO data Source
daoFactory.getDAODataSource().setId( dataSrc );
// Type has already been set
daoFactory.getDAODataSource().setUri( ( ( "".equals( uri ) == false ) ? uri : xformsdbServlet.getServletContext().getRealPath( "/" ) ) );
daoFactory.getDAODataSource().setUsername( username );
daoFactory.getDAODataSource().setPassword( password );
daoFactory.getDAODataSource().setCollection( collection );
xformsdbDAO = daoFactory.getXFormsDBDAO();
logger.log( Level.DEBUG, "The XFormsDB DAO of the appropriate DAO factory implementation has been successfully retrieved." );
} catch ( ManagerException mex ) {
throw new HandlerException( mex.getCode(), mex.getMessage(), mex );
} catch ( DAOException daoex ) {
throw new HandlerException( daoex.getCode(), daoex.getMessage(), daoex );
} catch ( Exception ex ) {
throw new HandlerException( ErrorConstants.ERROR_CODE_XFORMSDBWIDGETQUERYALLHANDLER_1, ErrorConstants.ERROR_MESSAGE_XFORMSDBWIDGETQUERYALLHANDLER_1, ex );
}
return xformsdbDAO;
}
// PUBLIC METHODS
public String handle( XFormsDBServlet xformsdbServlet, HttpSession session, Document document ) throws HandlerException {
logger.log( Level.DEBUG, "Method has been called." );
XFormsDBConfigTO xformsDBConfigTO = null;
String xmlString = null;
XFormsDBDAO xformsdbDAO = null;
try {
// Retrieve the XFormsDB configuration file
xformsDBConfigTO = xformsdbServlet.getXFormsDBConfigTO();
// Retrieve the XFormsDB DAO of the appropriate DAO Factory implementation
xformsdbDAO = this.getXFormsDBDAO( xformsdbServlet, session, document, xformsDBConfigTO.getEncoding() );
// Retrieve the XML document
xmlString = xformsdbDAO.all( document, xformsDBConfigTO.getEncoding() );
logger.log( Level.DEBUG, "The ALL action of the XFormsDB widget query request has been successfully handled." );
} catch ( DAOException daoex ) {
throw new HandlerException( daoex.getCode(), daoex.getMessage(), daoex );
} catch ( HandlerException hex ) {
throw hex;
} catch ( Exception ex ) {
throw new HandlerException( ErrorConstants.ERROR_CODE_XFORMSDBWIDGETQUERYALLHANDLER_2, ErrorConstants.ERROR_MESSAGE_XFORMSDBWIDGETQUERYALLHANDLER_2, ex );
}
return xmlString;
}
} | mit |
googlestadia/renderdoc | util/test/demos/win32/win32_window.cpp | 3559 | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2018-2019 Baldur Karlsson
*
* 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.
******************************************************************************/
#include "win32_window.h"
#include <windows.h>
static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if(msg == WM_CLOSE)
{
DestroyWindow(hwnd);
return 0;
}
if(msg == WM_DESTROY)
return 0;
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
const wchar_t *classname = L"renderdoc_d3d11_test";
void regClass()
{
static bool init = false;
if(init)
return;
init = true;
WNDCLASSEXW wc;
wc.cbSize = sizeof(WNDCLASSEXW);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetModuleHandle(NULL);
wc.hIcon = NULL;
wc.hCursor = NULL;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = classname;
wc.hIconSm = NULL;
if(!RegisterClassExW(&wc))
{
TEST_ERROR("Couldn't register window class");
return;
}
}
Win32Window::Win32Window(int width, int height, const char *title)
{
regClass();
RECT rect = {0, 0, width, height};
AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_CLIENTEDGE);
WCHAR *wstr = L"";
if(title)
{
int len = (int)strlen(title);
int wsize = MultiByteToWideChar(CP_UTF8, 0, title, len, NULL, 0);
wstr = (WCHAR *)_alloca(wsize * sizeof(wchar_t) + 2);
wstr[wsize] = 0;
MultiByteToWideChar(CP_UTF8, 0, title, len, wstr, wsize);
}
wnd = CreateWindowExW(WS_EX_CLIENTEDGE, classname, wstr, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL,
NULL, NULL);
if(title)
ShowWindow(wnd, SW_SHOW);
}
Win32Window::~Win32Window()
{
DestroyWindow(wnd);
}
void Win32Window::Resize(int width, int height)
{
SetWindowPos(wnd, HWND_TOP, 0, 0, width, height, SWP_NOMOVE);
}
bool Win32Window::Update()
{
UpdateWindow(wnd);
MSG msg = {};
// Check to see if any messages are waiting in the queue
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Translate the message and dispatch it to WindowProc()
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if(!IsWindowVisible(wnd))
return false;
if(msg.message == WM_CHAR && msg.wParam == VK_ESCAPE)
return false;
Sleep(20);
return true;
}
| mit |
madcore-ai/containers | xlswriter/logger.py | 422 | import logging
class Logger(object):
def __init__(self, name):
self.logger = logging.getLogger(name)
if not len(self.logger.handlers):
handler = logging.StreamHandler()
formatter = logging.Formatter('[%(levelname)s]:%(name)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
# self.logger.setLevel(logging.INFO) | mit |
CheDream-Android/CheDream | app/src/main/java/org/chedream/android/database/RealmDream.java | 6293 | package org.chedream.android.database;
import com.google.gson.annotations.SerializedName;
import org.chedream.android.model.Dream;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
/**
* Created by Dante Allteran on 3/28/2015.
* Class were created only for correct work of Realm Database
*/
@RealmClass
public class RealmDream extends RealmObject {
@PrimaryKey
private int id;
private String title;
private String description;
private String phone;
private String slug;
@SerializedName("created_at")
private String createdAt;
@SerializedName("updated_at")
private String updatedAt;
@SerializedName("deleted_at")
private String deletedAt;
@SerializedName("users_who_favorites")
private RealmList<RealmUser> usersWhoFavorites;
private RealmUser author;
@SerializedName("current_status")
private String currentStatus;
@SerializedName("media_pictures")
private RealmList<RealmPicture> mediaPictures;
@SerializedName("media_completed_pictures")
private RealmList<RealmPicture> mediaCompletedPictures;
@SerializedName("media_poster")
private RealmPicture mediaPoster;
private int finResQuantity;
private int finContribQuantity;
private int equipResQuantity;
private int equipContribQuantity;
private int workResQuantity;
private int workContribQuantity;
private boolean isDreamFromDatabase;
public boolean isDreamFromDatabase() {
return isDreamFromDatabase;
}
public void setDreamFromDatabase(boolean isDreamFromDatabase) {
this.isDreamFromDatabase = isDreamFromDatabase;
}
public int getFinResQuantity() {
return finResQuantity;
}
public void setFinResQuantity(int finResQuantity) {
this.finResQuantity = finResQuantity;
}
public int getFinContribQuantity() {
return finContribQuantity;
}
public void setFinContribQuantity(int finContribQuantity) {
this.finContribQuantity = finContribQuantity;
}
public int getEquipResQuantity() {
return equipResQuantity;
}
public void setEquipResQuantity(int equipResQuantity) {
this.equipResQuantity = equipResQuantity;
}
public int getEquipContribQuantity() {
return equipContribQuantity;
}
public void setEquipContribQuantity(int equipContribQuantity) {
this.equipContribQuantity = equipContribQuantity;
}
public int getWorkResQuantity() {
return workResQuantity;
}
public void setWorkResQuantity(int workResQuantity) {
this.workResQuantity = workResQuantity;
}
public int getWorkContribQuantity() {
return workContribQuantity;
}
public void setWorkContribQuantity(int workContribQuantity) {
this.workContribQuantity = workContribQuantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public String getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(String deletedAt) {
this.deletedAt = deletedAt;
}
public RealmList<RealmUser> getUsersWhoFavorites() {
return usersWhoFavorites;
}
public void setUsersWhoFavorites(RealmList<RealmUser> usersWhoFavorites) {
this.usersWhoFavorites = usersWhoFavorites;
}
public RealmUser getAuthor() {
return author;
}
public void setAuthor(RealmUser author) {
this.author = author;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
public RealmList<RealmPicture> getMediaPictures() {
return mediaPictures;
}
public void setMediaPictures(RealmList<RealmPicture> mediaPictures) {
this.mediaPictures = mediaPictures;
}
public RealmList<RealmPicture> getMediaCompletedPictures() {
return mediaCompletedPictures;
}
public void setMediaCompletedPictures(RealmList<RealmPicture> mediaCompletedPictures) {
this.mediaCompletedPictures = mediaCompletedPictures;
}
public RealmPicture getMediaPoster() {
return mediaPoster;
}
public void setMediaPoster(RealmPicture mediaPoster) {
this.mediaPoster = mediaPoster;
}
public RealmDream() {
}
public RealmDream(Dream dream, RealmUser authorRealm, RealmList<RealmUser> usersWhoFavoritesRealm,
RealmPicture mediaPoster, RealmList<RealmPicture> mediaPictures,
RealmList<RealmPicture> mediaCompletedPictures) {
this.id = dream.getId();
this.title = dream.getTitle();
this.description = dream.getDescription();
this.phone = dream.getPhone();
this.slug = dream.getSlug();
this.createdAt = dream.getCreatedAt();
this.updatedAt = dream.getUpdatedAt();
this.deletedAt = dream.getDeletedAt();
this.currentStatus = dream.getCurrentStatus();
this.author = authorRealm;
this.usersWhoFavorites = usersWhoFavoritesRealm;
this.mediaPoster = mediaPoster;
this.mediaPictures = mediaPictures;
this.mediaCompletedPictures = mediaCompletedPictures;
}
}
| mit |
team-diana/nucleo-dynamixel | docs/html/struct_t_i_m___i_c___init_type_def.js | 464 | var struct_t_i_m___i_c___init_type_def =
[
[ "ICFilter", "struct_t_i_m___i_c___init_type_def.html#ae8432aa11b5495b252ac7ae299eabb32", null ],
[ "ICPolarity", "struct_t_i_m___i_c___init_type_def.html#ab122383ebc0926c49a814546471da9b3", null ],
[ "ICPrescaler", "struct_t_i_m___i_c___init_type_def.html#a452a4a459b6f7b7c478db032de9b0d72", null ],
[ "ICSelection", "struct_t_i_m___i_c___init_type_def.html#aad80556490de79727ba1269c851e9724", null ]
]; | mit |
dechoD/Telerik-Homeworks | Practice Exams/C# Part II/2013.09.14M/Test/Properties/AssemblyInfo.cs | 1402 | 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("Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Test")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[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("1c99078d-97d4-4a73-9a7a-9f046914e226")]
// 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")]
| mit |
hendrikdelarey/appcampus | AppCampus.Website/app/controllers/mainController.ts | 2279 | app.controller("mainController", function ($scope, $rootScope, $http, $cookies, $injector, userService, usersService, errorHandler) {
var devicesService = <any>{};
$scope.newDevices = false;
$scope.superAdmin = false;
//userLogin();
function init() {
userLogin();
checkDevices();
setInterval(function () { checkDevices(); }, 30000);
};
function checkDevices() {
if (!userService.checkCompanyInfo()) {
return false;
} else {
devicesService = $injector.get("devicesService");
devicesService.query({}).$promise.then(
function success(devices) {
$scope.newDevices = false;
angular.forEach(devices,(value, key) => {
if (value.state === "Pending") {
$scope.newDevices = true;
}
});
},
(error) => {
errorHandler.handleError(error);
});
}
};
function userLogin() {
applyRoutes();
};
function applyRoutes() {
};
$scope.$on("userInfoUpdate", function (event, args) {
$scope.superAdmin = JSON.parse($cookies.token).isSuper;
userService.$resource().get({
userId: JSON.parse($cookies.token).userId
},
function success(user) {
init();
$scope.name = user.firstName + " " + user.lastName;
},
(error) => {
if (!userService.isSuperUser()) {
errorHandler.handleError(error);
}
});
var companyService = $injector.get("companyService");
companyService.get({},
(company) => {
$scope.companyName = company.name;
$scope.companyId = company.companyId;
},
(error) => {
errorHandler.handleError(error);
});
});
$scope.$on("rolesUpdated", function (event, args) {
$(".cover-window").hide();
});
$scope.$on("loadingRoles", function (event, args) {
$scope.loaderNumber = "(1/1)";
$scope.loaderText = "Loading Roles";
});
}); | mit |
liuhuisheng/dhtmlx_web | assets/lib/dhtmlx/v403_pro/sources/dhtmlxGrid/codebase/ext/dhtmlxgrid_data.js | 4906 | /*
Product Name: dhtmlxSuite
Version: 4.0.3
Edition: Professional
License: content of this file is covered by DHTMLX Commercial or Enterprise license. Usage without proper license is prohibited. To obtain it contact [email protected]
Copyright UAB Dinamenta http://www.dhtmlx.com
*/
dhtmlXGridObject.prototype._process_xmlA=function(xml){
if (!xml.doXPath){
var t = new dtmlXMLLoaderObject(function(){});
if (typeof xml == "string")
t.loadXMLString(xml);
else {
if (xml.responseXML)
t.xmlDoc=xml;
else
t.xmlDoc={};
t.xmlDoc.responseXML=xml;
}
xml=t;
}
this._parsing=true;
var top=xml.getXMLTopNode(this.xml.top)
//#config_from_xml:20092006{
this._parseHead(top);
//#}
var rows=xml.doXPath(this.xml.row,top)
var cr=parseInt(xml.doXPath("//"+this.xml.top)[0].getAttribute("pos")||0);
var total=parseInt(xml.doXPath("//"+this.xml.top)[0].getAttribute("total_count")||0);
if (total && !this.rowsBuffer[total-1]) this.rowsBuffer[total-1]=null;
if (this.isTreeGrid()){
this._get_xml_data = this._get_xml_dataA;
this._process_xml_row = this._process_xml_rowA;
return this._process_tree_xml(xml);
}
for (var i=0; i < rows.length; i++) {
if (this.rowsBuffer[i+cr]) continue;
var id=rows[i].getAttribute("id")||this.uid();
this.rowsBuffer[i+cr]={ idd:id, data:rows[i], _parser: this._process_xml_rowA, _locator:this._get_xml_dataA };
this.rowsAr[id]=rows[i];
//this.callEvent("onRowCreated",[r.idd]);
}
this.render_dataset();
this._parsing=false;
return xml.xmlDoc.responseXML?xml.xmlDoc.responseXML:xml.xmlDoc;
}
dhtmlXGridObject.prototype._process_xmlB=function(xml){
if (!xml.doXPath){
var t = new dtmlXMLLoaderObject(function(){});
if (typeof xml == "string")
t.loadXMLString(xml);
else {
if (xml.responseXML)
t.xmlDoc=xml;
else
t.xmlDoc={};
t.xmlDoc.responseXML=xml;
}
xml=t;
}
this._parsing=true;
var top=xml.getXMLTopNode(this.xml.top)
//#config_from_xml:20092006{
this._parseHead(top);
//#}
var rows=xml.doXPath(this.xml.row,top)
var cr=parseInt(xml.doXPath("//"+this.xml.top)[0].getAttribute("pos")||0);
var total=parseInt(xml.doXPath("//"+this.xml.top)[0].getAttribute("total_count")||0);
if (total && !this.rowsBuffer[total-1]) this.rowsBuffer[total-1]=null;
if (this.isTreeGrid()){
this._get_xml_data = this._get_xml_dataB;
this._process_xml_row = this._process_xml_rowB;
return this._process_tree_xml(xml);
}
for (var i=0; i < rows.length; i++) {
if (this.rowsBuffer[i+cr]) continue;
var id=rows[i].getAttribute("id")||this.uid();
this.rowsBuffer[i+cr]={ idd:id, data:rows[i], _parser: this._process_xml_rowB, _locator:this._get_xml_dataB };
this.rowsAr[id]=rows[i];
//this.callEvent("onRowCreated",[r.idd]);
}
this.render_dataset();
this._parsing=false;
return xml.xmlDoc.responseXML?xml.xmlDoc.responseXML:xml.xmlDoc;
}
dhtmlXGridObject.prototype._process_xml_rowA=function(r,xml){
var strAr = [];
r._attrs=this._xml_attrs(xml);
//load cell data
for(var j=0;j<this.columnIds.length;j++){
var cid=this.columnIds[j];
var cellVal=r._attrs[cid]||"";
if (r.childNodes[j])
r.childNodes[j]._attrs={};
strAr.push(cellVal);
}
//back to common code
this._fillRow(r,(this._c_order?this._swapColumns(strAr):strAr));
return r;
}
dhtmlXGridObject.prototype._get_xml_dataA=function(data,ind){
return data.getAttribute(this.getColumnId(ind));
}
dhtmlXGridObject.prototype._process_xml_rowB=function(r,xml){
var strAr = [];
r._attrs=this._xml_attrs(xml);
//load userdata
if (this._ud_enabled){
var udCol = this.xmlLoader.doXPath("./userdata",xml);
for (var i = udCol.length - 1; i >= 0; i--)
this.setUserData(udCol[i].getAttribute("name"),udCol[i].firstChild?udCol[i].firstChild.data:"");
}
//load cell data
for (var jx=0; jx < xml.childNodes.length; jx++) {
var cellVal=xml.childNodes[jx];
if (!cellVal.tagName) continue;
var j=this.getColIndexById(cellVal.tagName);
if (isNaN(j)) continue;
var exc=cellVal.getAttribute("type");
if (exc)
r.childNodes[j]._cellType=exc;
r.childNodes[j]._attrs=this._xml_attrs(cellVal);
if (cellVal.getAttribute("xmlcontent"))
{}
else if (cellVal.firstChild)
cellVal=cellVal.firstChild.data;
else cellVal="";
strAr[j]=cellVal;
}
for (var i=0; i < r.childNodes.length; i++) {
if (!r.childNodes[i]._attrs) r.childNodes[i]._attrs={};
};
//back to common code
this._fillRow(r,(this._c_order?this._swapColumns(strAr):strAr));
return r;
}
dhtmlXGridObject.prototype._get_xml_dataB=function(data,ind){
var id=this.getColumnId(ind);
data=data.firstChild;
while (true){
if (!data) return "";
if (data.tagName==id) return (data.firstChild?data.firstChild.data:"")
data=data.nextSibling;
}
return "";
} | mit |
ITAAcademy/crmChat | src/main/java/com/intita/wschat/config/UserPermissionEvaluator.java | 1542 | package com.intita.wschat.config;
import java.io.Serializable;
import java.security.Permission;
import java.util.Collection;
import com.intita.wschat.domain.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import com.intita.wschat.models.User;
import com.intita.wschat.services.UsersService;
/**
*
* @author Nicolas Haiduchok
*/
@Configuration
public class UserPermissionEvaluator implements PermissionEvaluator {
@Autowired UsersService userService;
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permissions) {
String []permitionsOrList = ((String) permissions).split(",");
boolean has = false;
for(String permitionsOr : permitionsOrList)
{
String [] permitionsAnd = permitionsOr.split("&");
boolean _has = true;
for(String permition : permitionsAnd)
{
_has = _has && userService.checkRoleByAuthentication(authentication, UserRole.valueOf(permition.trim()));
}
has = has || _has;
if(has)
break;
}
//return userService.checkRoleByPrincipal(authentication, UserRole.valueOf());
return has;
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
Object permission) {
return false;
}
} | mit |
yaoxf/waterCup | xhxtbgxt_A5/xinhu_utf8_1.5.7/webmain/flow/input/inputjs/mode_daily.js | 584 | function initbodys(){
$(form('dt')).blur(function(){
//changetypes();
});
$(form('type')).change(function(){
changetypes();
});
$(form('enddt')).blur(function(){
//changetypes();
});
}
function changetypes(){
var lx= form('type').value;
if(lx==''||lx=='0'){
form('enddt').value='';
return;
}
var dt = form('dt').value;
if(dt=='')return;
js.ajax(geturlact('getdtstr'),{dt:dt,type:lx},function(a){
form('dt').value= a[0];
form('enddt').value=a[1];
},'get,json');
}
function changesubmit(d){
if(d.type!='0' && d.enddt=='')return '截止日期不能为空';
} | mit |
hmatuschek/linalg | test/gemvtest.hh | 715 | /*
* This file is part of the Linalg project, a C++ interface to BLAS and LAPACK.
*
* The source-code is licensed under the terms of the MIT license, read LICENSE for more details.
*
* (c) 2011, 2012 Hannes Matuschek <hmatuschek at gmail dot com>
*/
#ifndef GEMVTEST_HH
#define GEMVTEST_HH
#include "unittest.hh"
class GEMVTest : public UnitTest::TestCase
{
public:
void testSquareRowMajor();
void testSquareColMajor();
void testSquareTransposedRowMajor();
void testSquareTransposedColMajor();
void testRectRowMajor();
void testRectTransposedRowMajor();
void testRectColMajor();
void testRectTransposedColMajor();
public:
static UnitTest::TestSuite *suite();
};
#endif // GEMVTEST_HH
| mit |
blackcatcoin/blackcatcoin | src/version.cpp | 2587 | // Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("BCATcoin");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID ""
# define GIT_COMMIT_DATE ""
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
| mit |
AntiSC2/TidyEngine | libTidyEngine/rect2d.hpp | 1672 | /*
* TidyEngine
* Copyright (c) 2018 Jakob Sinclair <[email protected]>
*
* 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.
*/
#pragma once
#include "renderable.hpp"
class Rect2D : public Renderable {
public:
Rect2D();
Rect2D(float x, float y, float w, float h);
Rect2D(glm::vec2 position, glm::vec2 dimensions);
Rect2D(glm::vec4 rect);
virtual ~Rect2D();
virtual void SetRect(float x, float y, float w, float h);
virtual void SetPos(float x, float y);
virtual void SetColor(glm::vec4 color);
virtual void SetColor(float r, float g, float b, float a);
protected:
glm::vec4 m_Color = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
};
| mit |
chris-peterson/Kekiri | src/Kekiri/Impl/Reporting/FeatureFileReportTarget.cs | 2846 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Kekiri.Impl.Reporting
{
class FeatureFileReportTarget : IReportTarget
{
static readonly Lazy<FeatureFileReportTarget> _target = new Lazy<FeatureFileReportTarget>(() => new FeatureFileReportTarget());
readonly Dictionary<string, dynamic> _featureState = new Dictionary<string, dynamic>();
readonly object _syncObject = new object();
FeatureFileReportTarget()
{
}
public static IReportTarget GetInstance()
{
return _target.Value;
}
public void Report(ScenarioReportingContext scenario)
{
lock (_syncObject)
{
var featureName = scenario.FeatureName;
if (_featureState.ContainsKey(featureName))
{
using (var fs = File.Open(_featureState[featureName].Path, FileMode.Append, FileAccess.Write))
{
Write(scenario, fs);
}
}
else
{
_featureState.Add(featureName, new
{
Path = Path.Combine(
AppContext.BaseDirectory,
$"{CoerceValidFileName(featureName)}.feature")
});
using (var fs = File.Create(_featureState[featureName].Path))
{
Write(scenario, fs);
}
}
}
}
static void Write(ScenarioReportingContext context, Stream stream)
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(context.CreateReport());
}
}
// http://stackoverflow.com/questions/309485/c-sharp-sanitize-file-name
static string CoerceValidFileName(string filename)
{
var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
var invalidReStr = $@"[{invalidChars}]+";
var reservedWords = new[]
{
"CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
"COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
"LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
};
var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
return reservedWords.Select(reservedWord => $"^{reservedWord}\\.").Aggregate(sanitisedNamePart, (current, reservedWordPattern) => Regex.Replace(current, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase));
}
}
} | mit |
HSOAutonomy/base | src/hso/autonomy/agent/decision/behavior/IBehavior.java | 2145 | /* Copyright 2008 - 2017 Hochschule Offenburg
* For a list of authors see README.md
* This software of HSOAutonomy is released under MIT License (see LICENSE).
*/
package hso.autonomy.agent.decision.behavior;
/**
* Interface to access all behaviors of the agent
*/
public interface IBehavior {
/** Name for the none behavior */
String NONE = "None";
/**
* Reinitializes the Behavior-StateMachine (if present)
*/
void init();
/**
* Called to perform the behavior
*/
void perform();
/**
* Retrieve the behavior name
*
* @return Behavior name
*/
String getName();
/**
* Check if this behavior is finished performing
*
* @return True if finished, false if not
*/
boolean isFinished();
/**
* Called when to stop this behavior without caring for stopping it softly
*/
void abort();
/**
* Decide if it is possible to switch to this behavior from the current
* behavior.
*
* @param actualBehavior the currently/actually performed behavior
* @return This behavior if it is possible to switch to this behavior,
* otherwise the current behavior
*/
IBehavior switchFrom(IBehavior actualBehavior);
/**
* Called to notify this behavior that is no longer performed and replaced by
* the new behavior.
*
* @param newBehavior the new behavior which will be performed after this
* behavior
*/
void onLeavingBehavior(IBehavior newBehavior);
/**
* Called if we decided again for that behavior
*/
void stayIn();
/**
* Retrieve the number of times this behavior has been performed/initialized
*
* @return Number of performs
*/
int getPerforms();
/**
* @return the number of cycles this behavior has been performed in total
*/
int getPerformedCycles();
/**
* @return the number of consecutive performs without interruption
*/
int getConsecutivePerforms();
/**
* A call does <b><u>not</u></b> have side effects. But a call before
* decideNextBasicBehavior will result in the old current behavior in case of
* Complex behaviors.
* @return the underlying basic behavior that will be performed.
*/
IBehavior getRootBehavior();
}
| mit |
dstuecken/Amazon-WD-Alerts | src/WdAlerts/Crawler/Crawler.php | 11078 | <?php
namespace dstuecken\WdAlerts\Crawler;
use dstuecken\Notify\NotificationCenter;
use dstuecken\WdAlerts\Config;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\RequestOptions;
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerAwareInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\DomCrawler\Crawler as DomCrawler;
/**
* Class Crawler
*
* @copyright Dennis Stücken <[email protected]>
* @licence MIT
*
* @package dstuecken\WdAlerts\Crawler
*/
class Crawler
{
/**
* @var EngineContract
*/
private $engine;
/**
* @var NotificationCenter
*/
private $notification;
/**
* @var Config
*/
private $config;
/**
* @var ConsoleOutput
*/
private $output;
/**
* @var LoggerAwareInterface
*/
private $logger;
/**
* @var float
*/
protected $maximumPrice = .0;
/**
* Write console text if enabled
*
* @param $text
* @return $this
*/
private function consoleOutput($text)
{
if ($this->config->getOption('enableConsoleTextOutput')) {
$this->output->writeln($text);
}
$this->logger->info($text);
return $this;
}
/**
* Speech output on mac, text output on other systems
*
* @param string $text
*/
private function macOsSpeechOutput($text)
{
if ($this->config->getOption('enableMacOsSpeechOutput')) {
shell_exec('say -v Alex "'. $text .'"');
} else {
$this->consoleOutput($text);
}
}
/**
* @param $link
*
* @return $this
*/
private function openBrowser($link)
{
if ($this->config->getOption('startBrowserIfDealFound')) {
if (strstr(php_uname('s'), 'Darwin')) {
shell_exec('open ' . $link);
} elseif (strstr(php_uname('s'), 'Windows')) {
shell_exec('explorer ' . $link);
}
}
return $this;
}
/**
* Check for maximum price
*
* @param string|mixed $itemPrice
*
* @return bool
*/
private function validateMaximumPrice($itemPrice) {
// Just return true if maximum price is set to .0 (which is the default)
if ($this->maximumPrice === .0) {
return true;
}
// Extract price value (without currency signs)
if ($itemPrice = preg_match('/^.*?([0-9,\.]+).*?$/', $itemPrice, $matches)) {
$itemPrice = $matches[1];
}
// Check for locale
if (!setlocale(LC_NUMERIC, $this->engine->getLocale())) {
$this->consoleOutput('You need to have the following locale installed in order to use price matchings properly: ' . $this->engine->getLocale());
}
return ($this->maximumPrice > .0 && floatval($itemPrice) < $this->maximumPrice);
}
/**
* Start crawling process
*/
public function crawl()
{
$shellStart = $this->config->get('hooks', 'shellStart');
if ($shellStart) {
shell_exec($shellStart);
}
$this->macOsSpeechOutput('I\'m happy to start scanning for your deals!');
// Amazon offer listing page, e.g. https://www.amazon.de/gp/offer-listing/B00ULWWFIC
$crawlUrl = $this->engine->getCrawlUrl();
// Instances
$notificationCenter = $this->notification;
try {
$client = new Client();
$jar = new CookieJar();
$listingUrl = rtrim($crawlUrl, '/') . "/" . $this->engine->getArticleId();
if (!$this->config->has('options', 'useRefLink') || $this->config->getOption('useRefLink')) {
$listingUrl .= $this->engine->getLinkAddition();
}
while (1) {
try {
$res = $client->request('GET', $listingUrl, [
RequestOptions::ALLOW_REDIRECTS => [
'max' => 10,
],
RequestOptions::COOKIES => $jar,
RequestOptions::CONNECT_TIMEOUT => 10,
// RequestOptions::DEBUG => true,
RequestOptions::HEADERS => [
'Accept-Encoding' => 'gzip, deflate, sdch, br',
'Cache-Control' => 'max-age=0',
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent' => $this->config->get('options', 'userAgent'),
'Accept-language' => $this->config->get('options', 'acceptLanguage'),
'Connection' => 'keep-alive'
],
RequestOptions::PROXY => $this->config->getOption('proxy'),
RequestOptions::VERIFY => true,
]);
if ($data = $res->getBody()->getContents()) {
$crawler = new DomCrawler($data);
$result = $this->engine->parse($crawler);
if ($result->isFound() && $this->validateMaximumPrice($result->getPrice())) {
// Warehouse deal found, prepare message:
$body = sprintf(
"Item \"%s\" is available for %s!\nCondition is: %s\nDescription: %s\n\n%s",
$result->getTitle(),
$result->getPrice(),
$result->getCondition(),
$result->getDescription(),
$listingUrl
);
// Mac OS notification
$notificationCenter->info($body);
// Show console message
$this->consoleOutput($body);
// Open web browser
$this->openBrowser($listingUrl);
$shellDeal = $this->config->get('hooks', 'shellDeal');
if ($shellDeal) {
shell_exec(str_replace([$result->getTitle(), $result->getCondition(), $result->getPrice()], ['%TITLE%', '%CONDITION%', '%PRICE%'], $shellDeal));
}
// Say it out loud
$this->macOsSpeechOutput('Yay, your deal ' . $result->getTitle() . ' is available for ' . $result->getPrice() . '');
if ($this->config->get('mail', 'enabled')) {
$transport = \Swift_SmtpTransport::newInstance(
$this->config->get('mail', 'smtp'),
$this->config->get('mail', 'port'),
$this->config->get('mail', 'security')
)
->setUsername($this->config->get('mail', 'username'))
->setPassword($this->config->get('mail', 'password'));
$mailer = \Swift_Mailer::newInstance($transport);
$message = \Swift_Message::newInstance()
->setSubject($this->config->get('mail', 'subjectPrefix') . ': ' . $result->getTitle())
->setFrom($this->config->get('mail', 'from'))
->setTo($this->config->get('mail', 'to'));
$message->setBody($body);
$mailer->send($message);
}
} else {
// no warehouse deal
$priceInfo = $this->maximumPrice === .0 ? '' : ' <comment>at '.$this->maximumPrice.'</comment>';
$this->consoleOutput("No deal available".$priceInfo.". Current best price is <info>" . $result->getPrice() . "</info>.");
$shellNoDeal = $this->config->get('hooks', 'shellNoDeal');
if ($shellNoDeal) {
shell_exec($shellNoDeal);
}
}
} else {
$this->consoleOutput("Error retrieving page (". $res->getStatusCode() ."): <error>" . error_get_last()['message'] . '</error>');
}
$this->consoleOutput(sprintf("Sleeping <comment>%s</comment> seconds..\n", $this->config->getOption('updateInterval')));
sleep($this->config->getOption('updateInterval'));
} catch (\Exception $e) {
// Amazon thinks we are a bot..
if (isset($data) && (strstr($data, 'To discuss automated access to Amazon data please contact'))) {
$this->consoleOutput('Damn, Amazon rejected our request. Retrying in five seconds.');
}
else {
$this->consoleOutput($e->getMessage());
$notificationCenter->error($e->getMessage());
}
// Sleep one second if an error occurred
sleep(5);
}
}
} catch (\Exception $e) {
$this->consoleOutput($e->getMessage());
$notificationCenter->error($e->getMessage());
}
}
/**
* @param float $maximumPrice
*
* @return $this
*/
public function setMaximumPrice($maximumPrice)
{
// Disallow negative or invalid maximum prices
if ($maximumPrice < .0 || !$maximumPrice) {
throw new \InvalidArgumentException('Invalid price: Price should be positive and in the following format "1999.99".');
}
$this->maximumPrice = floatval($maximumPrice);
return $this;
}
/**
* Crawler constructor.
*
* @param EngineContract $engine
* @param NotificationCenter $notificationCenter
* @param Config $config
*/
public function __construct(EngineContract $engine, NotificationCenter $notificationCenter, Config $config)
{
$this->engine = $engine;
$this->notification = $notificationCenter;
$this->config = $config;
// Console output handler
$this->output = new ConsoleOutput();
$this->logger = new Logger('name');
if ($this->config->get('log', 'enabled')) {
$this->logger->pushHandler(new StreamHandler($this->config->get('log', 'file'), Logger::INFO));
} else {
$this->logger->pushHandler(new NullHandler());
}
}
} | mit |
HighlandersFRC/fpga | beagleBoneBlack/netTablesTest/networktables2/WriteManager.cpp | 3417 | /*
* WriteManager.cpp
*
* Created on: Sep 25, 2012
* Author: Mitchell Wills
*/
#include "networktables2/WriteManager.h"
#include "networktables2/util/System.h"
#include <iostream>
WriteManager::WriteManager(FlushableOutgoingEntryReceiver& _receiver, NTThreadManager& _threadManager, AbstractNetworkTableEntryStore& _entryStore, unsigned long _keepAliveDelay)
: receiver(_receiver), threadManager(_threadManager), entryStore(_entryStore), keepAliveDelay(_keepAliveDelay){
thread = NULL;
lastWrite = 0;
incomingAssignmentQueue = new std::queue<NetworkTableEntry*>();
incomingUpdateQueue = new std::queue<NetworkTableEntry*>();
outgoingAssignmentQueue = new std::queue<NetworkTableEntry*>();
outgoingUpdateQueue = new std::queue<NetworkTableEntry*>();
}
WriteManager::~WriteManager(){
transactionsLock.take();
stop();
delete incomingAssignmentQueue;
delete incomingUpdateQueue;
delete outgoingAssignmentQueue;
delete outgoingUpdateQueue;
}
void WriteManager::start(){
if(thread!=NULL)
stop();
lastWrite = currentTimeMillis();
thread = threadManager.newBlockingPeriodicThread(this, "Write Manager Thread");
}
void WriteManager::stop(){
if(thread!=NULL){
thread->stop();
//delete thread;
thread = NULL;
}
}
void WriteManager::offerOutgoingAssignment(NetworkTableEntry* entry) {
{
Synchronized sync(transactionsLock);
((std::queue<NetworkTableEntry*>*)incomingAssignmentQueue)->push(entry);
if(((std::queue<NetworkTableEntry*>*)incomingAssignmentQueue)->size()>=queueSize){
run();
writeWarning("assignment queue overflowed. decrease the rate at which you create new entries or increase the write buffer size");
}
}
}
void WriteManager::offerOutgoingUpdate(NetworkTableEntry* entry) {
{
Synchronized sync(transactionsLock);
((std::queue<NetworkTableEntry*>*)incomingUpdateQueue)->push(entry);
if(((std::queue<NetworkTableEntry*>*)incomingUpdateQueue)->size()>=queueSize){
run();
writeWarning("update queue overflowed. decrease the rate at which you update entries or increase the write buffer size");
}
}
}
void WriteManager::run() {
{
Synchronized sync(transactionsLock);
//swap the assignment and update queue
volatile std::queue<NetworkTableEntry*>* tmp = incomingAssignmentQueue;
incomingAssignmentQueue = outgoingAssignmentQueue;
outgoingAssignmentQueue = tmp;
tmp = incomingUpdateQueue;
incomingUpdateQueue = outgoingUpdateQueue;
outgoingUpdateQueue = tmp;
}
bool wrote = false;
NetworkTableEntry* entry;
while(!((std::queue<NetworkTableEntry*>*)outgoingAssignmentQueue)->empty()){
entry = ((std::queue<NetworkTableEntry*>*)outgoingAssignmentQueue)->front();
((std::queue<NetworkTableEntry*>*)outgoingAssignmentQueue)->pop();
{
Synchronized sync(entryStore.LOCK);
entry->MakeClean();
wrote = true;
receiver.offerOutgoingAssignment(entry);
}
}
while(!((std::queue<NetworkTableEntry*>*)outgoingUpdateQueue)->empty()){
entry = ((std::queue<NetworkTableEntry*>*)outgoingUpdateQueue)->front();
((std::queue<NetworkTableEntry*>*)outgoingUpdateQueue)->pop();
{
Synchronized sync(entryStore.LOCK);
entry->MakeClean();
wrote = true;
receiver.offerOutgoingUpdate(entry);
}
}
if(wrote){
receiver.flush();
lastWrite = currentTimeMillis();
}
else if(currentTimeMillis()-lastWrite>keepAliveDelay)
receiver.ensureAlive();
sleep_ms(20);
}
| mit |
policygenius/athenaeum | src/molecules/formfields/GoogleAutoCompleteField/util/loadJS.js | 462 | function buildSrc({ link, key }) {
if (link) return link;
return `https://maps.googleapis.com/maps/api/js?key=${key}&libraries=places&callback=initMap`;
}
export default function loadJS({ link, key }) {
const src = buildSrc({ link, key });
const ref = window.document.getElementsByTagName('script')[0];
const script = window.document.createElement('script');
script.src = src;
script.async = true;
ref.parentNode.insertBefore(script, ref);
}
| mit |
stopyoukid/DojoToTypescriptConverter | out/separate/dojox.widget.gauge.Range.d.ts | 413 | /// <reference path="Object.d.ts" />
/// <reference path="dijit._Widget.d.ts" />
/// <reference path="dijit._Contained.d.ts" />
module dojox.widget.gauge{
export class Range extends dijit._Widget {
getParent () : any;
_getSibling (which:String) : any;
getPreviousSibling () : any;
getNextSibling () : any;
getIndexInParent () : number;
low : number;
high : any;
hover : String;
color : Object;
size : number;
}
}
| mit |
princeHyDentro/wetalk | assets/new-js/adding_staff.js | 10388 |
var save_method; //for save method string
var table;
$(document).ready(function() {
table = $('#staff-table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [],
// Load data for the table's content from an Ajax source
"ajax": {
"url": "ajax_list_data",
"type": "POST",
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
dom: '<"toolbar">Bfrtip',
buttons: [
{
text: '<i class="fa fa-plus-circle"></i> Add Staff',
action: function ( e, dt, node, config ) {
add_person();
}
},
{
text: '<i class="fa fa-refresh"></i> Reload List',
action: function ( e, dt, node, config ) {
reload_table();
}
},
]
});
// $("div.toolbar").html('<b>Custom tool bar! Text/images etc.</b>');
$('#admin_search_privilege').on('change' , function(){
table.search( this.value ).draw();
});
$('#search_register_account_by_name').on('keyup' , function(){
table.search( this.value ).draw();
});
$('#admin_search_status').on('change' , function(){
table.search( this.value ).draw();
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_person()
{
save_method = 'add';
var form = document.getElementById("form");
clearForm(form);
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('open'); // show bootstrap modal
$('.modal-title').text('Add Staff'); // Set Title to Bootstrap modal title
}
function clearForm(frm_elements){
for (i = 0; i < frm_elements.length; i++)
{
field_type = frm_elements[i].type.toLowerCase();
switch (field_type)
{
case "text":
case "password":
case "textarea":
// case "hidden":
case "email":
frm_elements[i].value = "";
break;
case "radio":
case "checkbox":
if (frm_elements[i].checked)
{
frm_elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
frm_elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
var unselected;
url = "ajax_add";
if($('#permission').val() == "office-admin"){
$.ajax({
url : "ajax_add_all",
type: "POST",
data: {
//'form' : $('#form').serialize() ,
'id' : $('#user_id').val(),
'user_fname' : $('#user_fname').val(),
'user_lname' : $('#user_lname').val(),
'user_mname' : $('#user_mname').val(),
'user_username' : $('#user_username').val(),
'user_password' : $('#user_password').val(),
'user_email' : $('#user_email').val(),
'permission' : $('#permission').val(),
},
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('close');
reload_table();
if(save_method == 'add') {
swal({ title: "Succesfully Added!",
text: "I will close in 2 seconds.",
timer: 2000,
icon: "success",
type: "success",
showConfirmButton: false
}).then(function() {
});
} else {
swal({ title: "Succesfully Updated!",
text: "I will close in 2 seconds.",
timer: 2000,
icon: "success",
type: "success",
showConfirmButton: false
}).then(function() {
});
}
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}else{
var checkValues = $('#services option:selected').map(function(){
data = {
'service_id' : $(this).val(),
'primary_id' : $(this).attr('data-id')
}
return data;
}).get();
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: {
//'form' : $('#form').serialize() ,
'id' : $('#user_id').val(),
'user_fname' : $('#user_fname').val(),
'user_lname' : $('#user_lname').val(),
'user_mname' : $('#user_mname').val(),
'user_username' : $('#user_username').val(),
'user_password' : $('#user_password').val(),
'user_email' : $('#user_email').val(),
'permission' : $('#permission').val(),
'services' : checkValues,
},
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('close');
reload_table();
if(save_method == 'add') {
swal({ title: "Succesfully Added!",
text: "I will close in 2 seconds.",
timer: 2000,
icon: "success",
type: "success",
showConfirmButton: false
}).then(function() {
});
} else {
swal({ title: "Succesfully Updated!",
text: "I will close in 2 seconds.",
timer: 2000,
icon: "success",
type: "success",
showConfirmButton: false
}).then(function() {
});
}
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
}
function delete_person(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "ajax_delete/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('close');
reload_table();
Materialize.toast('<i class="material-icons">notifications</i> Succesfully Deleted!', 3000, 'rounded')
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
} | mit |
wilson0xb4/strava-friend-breaker | friend_breaker/fb_app/views.py | 3539 | from __future__ import unicode_literals
from __future__ import print_function
import os
from django.conf import settings
from django.shortcuts import render, redirect
from stravalib import Client
from models import Athlete, ChallengedSegment
from tasks import massive_test
def index(request):
access_token = request.session.get('access_token', None)
if access_token is None:
# if access_token is NOT in session, kickoff the oauth exchange
client = Client()
url = client.authorization_url(
client_id=os.environ.get('STRAVA_CLIENT_ID', None),
redirect_uri='http://' + settings.ALLOWED_HOSTS[0] + '/authorization'
# redirect_uri='http://127.0.0.1:8000/authorization'
)
context = {'auth_url': url}
return render(request, 'index.html', context)
# otherwise, load authorized user
client = Client(access_token=access_token)
athlete_id = request.session.get('athlete_id', None)
if athlete_id is None:
# if athlete is NOT already in session, get athlete
# (attempting to reduce calls to the API)
athlete = client.get_athlete()
request.session['athlete_id'] = athlete.id
request.session['firstname'] = athlete.firstname
try:
Athlete.objects.get(strava_id=athlete.id)
except Athlete.DoesNotExist:
new_athlete = Athlete()
new_athlete.strava_id = athlete.id
new_athlete.first_name = athlete.firstname
new_athlete.last_name = athlete.lastname
new_athlete.city = athlete.city
new_athlete.state = athlete.state
new_athlete.country = athlete.country
new_athlete.save()
return render(request, 'welcome_landing.html')
def update(request):
'''
Kickoff the update process! (using celery)
'''
# check that I have both an `access_token` and an `athlete_id`
# essentially, "is the user logged in"
if not request.session.get('access_token', False) and request.session.get('athlete_id', False):
# could redirect 401 or 403 instead...but just put them at the home page
return redirect(index)
# client = Client(access_token=request.session.get('access_token', None))
access_token = request.session.get('access_token', None)
athlete_id = request.session.get('athlete_id', None)
# context = _build_context(client, athlete_id)
massive_test.delay(access_token, athlete_id)
return redirect(challenged_segments, athlete=athlete_id)
def challenged_segments(request, athlete):
segments = ChallengedSegment.objects.filter(my_id=athlete)
context = {}
context['segments'] = segments
return render(request, 'index_loggedin.html', context)
def authorization(request):
'''
Trades in the `code` sent from Strava for an `access_token`.
Ties that `access_token` to a users session.
'''
code = request.GET.get('code', None)
client = Client()
access_token = client.exchange_code_for_token(
client_id=os.environ.get('STRAVA_CLIENT_ID', None),
client_secret=os.environ.get('STRAVA_CLIENT_SECRET', None),
code=code
)
request.session['access_token'] = access_token
return redirect(index)
def logout(request):
request.session.flush()
return redirect(index)
def about(request):
# TODO: handle logged in and not logged in users
return render(request, 'about.html')
def profile(request):
return render(request, 'profile.html')
| mit |
fgrid/iso20022 | sese/TransferOutCancellationRequestV05.go | 3247 | package sese
import (
"encoding/xml"
"github.com/fgrid/iso20022"
)
type Document00200105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.002.001.05 Document"`
Message *TransferOutCancellationRequestV05 `xml:"TrfOutCxlReq"`
}
func (d *Document00200105) AddMessage() *TransferOutCancellationRequestV05 {
d.Message = new(TransferOutCancellationRequestV05)
return d.Message
}
// Scope
// An instructing party, for example, an investment manager or its authorised representative, sends the TransferOutCancellationRequest message to the executing party, for example, a transfer agent, to request the cancellation of a previously sent TransferOutInstruction.
// Usage
// The TransferOutCancellationRequest message is used to request cancellation of a previously sent TransferOutInstruction. There are two ways to specify the transfer cancellation request. Either:
// - the transfer reference of the original transfer is quoted, or,
// - all the details of the original transfer (this includes TransferReference) are quoted but this is not recommended.
// The message identification of the TransferOutInstruction message in which the original transfer was conveyed may also be quoted in PreviousReference. It is also possible to request the cancellation of a TransferOutInstruction message by quoting its message identification in PreviousReference.
type TransferOutCancellationRequestV05 struct {
// Reference that uniquely identifies a message from a business application standpoint.
MessageIdentification *iso20022.MessageIdentification1 `xml:"MsgId"`
// Reference to the transaction identifier issued by the counterparty. Building block may also be used to reference a previous transaction, or tie a set of messages together.
References []*iso20022.References15 `xml:"Refs,omitempty"`
// Choice between cancellation by reference or by transfer details.
Cancellation []*iso20022.Cancellation4Choice `xml:"Cxl"`
// Identifies the market practice to which the message conforms.
MarketPracticeVersion *iso20022.MarketPracticeVersion1 `xml:"MktPrctcVrsn,omitempty"`
// Information provided when the message is a copy of a previous message.
CopyDetails *iso20022.CopyInformation2 `xml:"CpyDtls,omitempty"`
}
func (t *TransferOutCancellationRequestV05) AddMessageIdentification() *iso20022.MessageIdentification1 {
t.MessageIdentification = new(iso20022.MessageIdentification1)
return t.MessageIdentification
}
func (t *TransferOutCancellationRequestV05) AddReferences() *iso20022.References15 {
newValue := new(iso20022.References15)
t.References = append(t.References, newValue)
return newValue
}
func (t *TransferOutCancellationRequestV05) AddCancellation() *iso20022.Cancellation4Choice {
newValue := new(iso20022.Cancellation4Choice)
t.Cancellation = append(t.Cancellation, newValue)
return newValue
}
func (t *TransferOutCancellationRequestV05) AddMarketPracticeVersion() *iso20022.MarketPracticeVersion1 {
t.MarketPracticeVersion = new(iso20022.MarketPracticeVersion1)
return t.MarketPracticeVersion
}
func (t *TransferOutCancellationRequestV05) AddCopyDetails() *iso20022.CopyInformation2 {
t.CopyDetails = new(iso20022.CopyInformation2)
return t.CopyDetails
}
| mit |
RamV13/Infection | src/com/ram/kainterview/InfectionViewImpl.java | 5058 | /**
* Package for the infection implementations for the Khan Academy interview
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ram Vellanki
*
* 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.
*/
package com.ram.kainterview;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.implementations.SingleGraph;
import org.graphstream.ui.swingViewer.DefaultView;
import org.graphstream.ui.view.Viewer;
/**
* View for the infection model
*/
public class InfectionViewImpl extends JFrame implements InfectionView {
private static final long serialVersionUID = 1L;
/**
* Fraction of the screen width to use
*/
private static final double WIDTH_FRACTION = 0.8;
/**
* Fraction of the screen height to use
*/
private static final double HEIGHT_FRACTION = 0.8;
/**
* Window width
*/
private int width;
/**
* Window height
*/
private int height;
/**
* Graph instance for containing visualizable nodes
*/
private Graph graph;
/**
* Viewer associated with this graph
*/
private Viewer viewer;
/**
* Infection number text field
*/
private JTextField infectTextField;
/**
* Infection type button
*/
private JButton infect;
/**
* Execute button
*/
private JButton execute;
/**
* Help button
*/
private JButton help;
public InfectionViewImpl(String title) {
setTitle(title);
Dimension screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
width = (int) (screen.width*WIDTH_FRACTION);
height = (int) (screen.height*HEIGHT_FRACTION);
setSize(width,height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initControls();
initGraph(title);
this.setVisible(true);
}
/**
* Initializes the controls
*/
private void initControls() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
infectTextField = new JTextField();
infectTextField.setPreferredSize(new Dimension(150,50));
infectTextField.setVisible(false);
panel.add(infectTextField);
infect = new JButton();
infect.setText("Total Infection");
infect.setPreferredSize(new Dimension(200,50));
panel.add(infect);
execute = new JButton();
execute.setText("Execute");
execute.setPreferredSize(new Dimension(100,50));
execute.setVisible(false);
panel.add(execute);
help = new JButton();
help.setText("Help");
help.setPreferredSize(new Dimension(100,50));
panel.add(help);
this.add(panel,BorderLayout.PAGE_START);
}
/**
* Initializes the graph with the given title
* @param title the title
*/
private void initGraph(String title) {
System.setProperty("org.graphstream.ui.renderer",
"org.graphstream.ui.j2dviewer.J2DGraphRenderer");
graph = new SingleGraph(title);
graph.setStrict(true);
graph.addAttribute("ui.antialias");
graph.addAttribute("ui.stylesheet", "graph {fill-color: black;}"
+ "node {size: 20px;fill-color: white;text-alignment: center; "
+ "stroke-mode: plain; stroke-width: 1px;}"
+ "node.selected {stroke-color: cyan;}"
+ "edge { fill-color: gray; }");
viewer = new Viewer(graph,
Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
viewer.enableAutoLayout();
DefaultView view = (DefaultView) viewer.addDefaultView(false);
view.getCamera().setAutoFitView(true);
view.getCamera().resetView();
this.add(view,BorderLayout.CENTER);
}
@Override
public void initController(InfectionController controller) {
controller.init(this, graph, viewer);
controller.registerInfectField(infectTextField);
controller.registerInfectButton(infect);
controller.registerExecuteButton(execute);
controller.registerHelpButton(help);
}
@Override
public void addNode(String id, int label, List<String> toIds,
List<String> fromIds) {
Node node = graph.addNode(id);
node.setAttribute("ui.label", label);
for (String s : toIds)
if (graph.getNode(s) != null)
graph.addEdge(s+id, s, id, true);
for (String s : fromIds)
if (graph.getNode(s) != null)
graph.addEdge(id+s, id, s, true);
}
@Override
public void updateNode(String id, int label) {
graph.getNode(id).setAttribute("ui.label", label);
}
}
| mit |
ammobinDOTca/ammobin-api | src/vendors.ts | 3193 | import { IVendor, Province } from './graphql-types'
declare type Vendor = Omit<Omit<IVendor, '__typename'>, 'background'>
// todo move other vendors here
export const BACK_COUNTRY_SPORTS: Vendor = {
name: 'Back Country Sports',
link: 'backcountrysports.ca',
location: 'Penticton',
provinces: [Province.BC],
logo: 'backcountrysports-logo.png',
hasReloadingItems: false,
}
export const SYLVESTRE_SPORTING_GOODS: Vendor = {
name: 'Sylvestre Sporting Goods',
link: 'shop.sylvestresportinggoods.com',
location: 'Bonnyville',
provinces: [Province.AB],
logo: 'sylvestresportinggoods-logo.png',
hasReloadingItems: false,
}
export const LONDEROS_SPORTS: Vendor = {
name: 'Londeros Sports',
link: 'londerosports.com',
location: 'Saint-Jean-sur-Richelieu',
provinces: [Province.QC],
logo: 'londerosports-logo.png',
hasReloadingItems: true,
}
export const NORDIC_MARKSMAN: Vendor = {
name: 'Nordic Marksman',
link: 'nordicmarksman.com',
location: 'Truro',
provinces: [Province.NS],
logo: 'nordicmarksman-logo.png',
hasReloadingItems: false,
}
export const PROPHET_RIVER: Vendor = {
name: 'Prophet River',
link: 'store.prophetriver.com',
location: 'Lloydminster',
provinces: [Province.AB],
logo: 'prophetriver-logo.png',
hasReloadingItems: false,
}
export const PRECISION_OPTICS: Vendor = {
name: 'Precision Optics',
link: 'precisionoptics.net',
location: 'Quesnel',
provinces: [Province.BC],
logo: 'precisionoptics-logo.png',
hasReloadingItems: false,
}
export const MARSTAR: Vendor = {
name: 'Marstar',
link: 'marstar.ca',
location: 'Vankleek Hill',
provinces: [Province.ON],
logo: 'marstar-logo.png',
hasReloadingItems: false,
}
export const NAS: Vendor = {
name: 'N.A.S. Guns and Ammo',
link: 'nasguns.com',
logo: 'nas-logo.jpg',
provinces: [Province.ON],
location: 'Niagara and Sault Ste. Marie',
hasReloadingItems: true,
}
export const BULLS_EYE: Vendor = {
name: 'Bulls Eye North',
link: 'bullseyenorth.com',
logo: 'bulls-logo.png',
provinces: [Province.ON],
location: 'London',
hasReloadingItems: true,
}
export const NICKS_SPORTS: Vendor = {
name: 'Nicks Sports',
link: 'nickssportshop.ca',
logo: 'nicks-sports-logo.png',
provinces: [Province.ON],
location: 'Toronto',
hasReloadingItems: false,
}
export const CANADA_FIRST_AMMO: Vendor = {
name: 'Canada First Ammo',
link: 'canadafirstammo.ca',
logo: 'canada-first-ammo.png',
provinces: [Province.AB],
location: 'Calagary',
hasReloadingItems: false,
}
export const TENDA: Vendor = {
name: 'Tenda',
link: 'gotenda.com',
logo: 'tenda-logo.png',
provinces: [Province.ON],
location: 'Richmond Hill',
hasReloadingItems: true,
}
export const GREAT_NORTH_PRECISION: Vendor = {
name: 'Great North Precision',
link: 'greatnorthprecision.com',
logo: 'greatnorthprecision-logo.png',
provinces: [Province.BC],
location: 'Kelowna',
hasReloadingItems: true,
}
export const VICTORY_RIDGE_SPORTS: Vendor = {
name: 'Victory Ridge Sports',
link: 'victoryridgesports.ca',
logo: 'victoryridgepsorts-logo.png',
provinces: [Province.ON],
location: 'Barrie',
hasReloadingItems: false,
}
| mit |
Mishurin/itemslide.github.io | src/requestAnimationFrame.js | 860 | var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
}; | mit |
sushihangover/Xamarin.Forms.Renderer.Tests | MessagingCenterAsync/Droid/MainActivity.cs | 771 | using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace MessagingCenterAsync.Droid
{
[Activity(Label = "MessagingCenterAsync.Droid", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| mit |
ozkuran/associationrulelearner | AssociationRuleLearner/Test/UnitTestItem.cs | 2860 | using System;
using System.Collections.Generic;
using Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test
{
[TestClass]
public class UnitTestItem
{
[TestMethod]
public void Item_Creation_Default_Constructor_Name()
{
var item = new Item();
const string expected = "Test Item";
var actual = item.Name;
// Assert
Assert.AreEqual(expected,actual,"Default constructor not set Item Name correctly");
}
[TestMethod]
public void Item_Creation_Default_Constructor_Guid()
{
var item = new Item();
var isValid = (item.Guid != Guid.Empty);
// Assert
Assert.AreEqual(true, isValid, "Default constructor not set Item Guid correctly");
}
[TestMethod]
public void Items_With_Same_Name_Equality_Check()
{
var item = new Item();
var item2 = new Item();
// Assert
Assert.AreEqual(item, item2, "Items with same name are not assumed equal");
}
[TestMethod]
public void Did_Items_With_Same_Name_Added_To_HashSet()
{
var item = new Item();
var item2 = new Item();
HashSet<Item> hashSet = new HashSet<Item>();
hashSet.Add(item);
hashSet.Add(item2);
// Assert
Assert.AreEqual(1, hashSet.Count, "Hashset added two Items with same name!");
}
[TestMethod]
public void Did_Item_ToString_Works_Correct()
{
var item = new Item("A");
// Assert
Assert.AreEqual("A", item.ToString(), "Item.ToString() did not work correct!");
}
[TestMethod]
public void Did_Item_NotEqual_Operator_Works_Correct()
{
var itemA = new Item("A");
var itemB = new Item("B");
// Assert
Assert.IsTrue((itemA != itemB), "Item_NotEqual_Operator did not work correct!");
}
[TestMethod]
public void Did_Item_Equals_Operator_Works_Correct()
{
var itemA = new Item("A");
var itemB = new Item("B");
// Assert
Assert.IsFalse(itemA.Equals(itemB), "Item_Equals_Operator did not work correct!");
}
[TestMethod]
public void Did_Item_CompareTo_Operator_Works_Correct()
{
var itemA = new Item("A");
var itemB = new Item("A");
var itemC = new Item("C");
// Assert
Assert.AreEqual(0,itemA.CompareTo(itemB), "Item_CompareTo_Operator did not work correct!");
Assert.AreNotEqual(0, itemA.CompareTo(itemC), "Item_CompareTo_Operator did not work correct!");
}
}
}
| mit |
abique/mimosa | mimosa/tpl/ast/text.cc | 280 | #include "text.hh"
namespace mimosa
{
namespace tpl
{
namespace ast
{
void
Text::execute(stream::Stream::Ptr stream,
const AbstractValue & /*value*/) const
{
stream->write(text_.data(), text_.size());
}
}
}
}
| mit |
laravolt/indonesia | resources/views/kabupaten/index.blade.php | 476 | @extends(
config('laravolt.indonesia.view.layout'),
[
'__page' => [
'title' => __('Kota/Kabupaten'),
'actions' => [
[
'label' => __('Tambah'),
'class' => 'primary',
'icon' => 'plus circle',
'url' => route('indonesia::kabupaten.create')
],
]
],
]
)
@section('content')
{!! $table !!}
@endsection
| mit |
anatm/administrator | src/Dscorp/WarriorsBundle/Form/mapaType.php | 914 | <?php
namespace Dscorp\WarriorsBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class mapaType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('urlimagenMapa')
->add('descripcionMapa')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Dscorp\WarriorsBundle\Entity\mapa'
));
}
/**
* @return string
*/
public function getName()
{
return 'dscorp_warriorsbundle_mapa';
}
}
| mit |
largem/Java101 | base101/src/main/java/net/largem/java101/class101/Interface101.java | 540 | package net.largem.java101.class101;
/**
* Created by jamestan on 2016-07-12.
*/
interface IFoo {
void fun();
}
class Foo implements IFoo {
final private String value;
public Foo(String v) {
value = v;
}
public void fun() {
//do something here
}
public String getValue()
{
return value;
}
@Override
public String toString() {
return value;
}
}
public class Interface101
{
public static void main( String[] args )
{
final IFoo foo = new Foo("abc");
foo.fun();
System.out.println(foo);
}
}
| mit |
IMEMS/gtbelib | Documentation/html/search/all_2.js | 10652 | var searchData=
[
['dac_5fcleardacs',['DAC_clearDACs',['../group___d_a_c__ad5754.html#ga2db4e1ba2471f68b497c3d6db1ab7726',1,'DAC_clearDACs(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga2db4e1ba2471f68b497c3d6db1ab7726',1,'DAC_clearDACs(void): dac_ad5754.c']]],
['dac_5fcleardacspin',['DAC_clearDACsPin',['../group___d_a_c__ad5754.html#ga22ab2e74e2db83f7af5d9888f641d8c5',1,'DAC_clearDACsPin(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga22ab2e74e2db83f7af5d9888f641d8c5',1,'DAC_clearDACsPin(void): dac_ad5754.c']]],
['dac_5fgetssinsettingscr1',['DAC_getSSInSettingsCR1',['../group___d_a_c__ad5754.html#gaa7ca584d832a5a8155f2715e0c583f95',1,'DAC_getSSInSettingsCR1(uint32_t ui32Base): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gaa7ca584d832a5a8155f2715e0c583f95',1,'DAC_getSSInSettingsCR1(uint32_t ui32Base): dac_ad5754.c']]],
['dac_5finitctlclr',['DAC_initCtlCLR',['../group___d_a_c__ad5754.html#ga33b8dcd9e7b399418db9f3f2f6d6cad7',1,'DAC_initCtlCLR(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga33b8dcd9e7b399418db9f3f2f6d6cad7',1,'DAC_initCtlCLR(void): dac_ad5754.c']]],
['dac_5finitctlldac',['DAC_initCtlLDAC',['../group___d_a_c__ad5754.html#gaa41f00f804f48c88f4aee18a02aa6a8e',1,'DAC_initCtlLDAC(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gaa41f00f804f48c88f4aee18a02aa6a8e',1,'DAC_initCtlLDAC(void): dac_ad5754.c']]],
['dac_5finitdac',['DAC_initDAC',['../group___d_a_c__ad5754.html#ga65670bedae308f00f19b4a95e444d0c6',1,'DAC_initDAC(uint32_t rangeValue, uint32_t pwrSettingsValue, uint32_t SysClkFreq): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga65670bedae308f00f19b4a95e444d0c6',1,'DAC_initDAC(uint32_t rangeValue, uint32_t pwrSettingsValue, uint32_t SysClkFreq): dac_ad5754.c']]],
['dac_5finitssi',['DAC_initSSI',['../group___d_a_c__ad5754.html#ga5c32da52b4ee8acf91ae4309ff8056aa',1,'DAC_initSSI(uint32_t SysClkFreq): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga5c32da52b4ee8acf91ae4309ff8056aa',1,'DAC_initSSI(uint32_t SysClkFreq): dac_ad5754.c']]],
['dac_5finitssiint',['DAC_initSSIint',['../group___d_a_c__ad5754.html#ga63a8682c2a50d7edc7a8cca6a84b0292',1,'DAC_initSSIint(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga63a8682c2a50d7edc7a8cca6a84b0292',1,'DAC_initSSIint(void): dac_ad5754.c']]],
['dac_5finittimersldac',['DAC_initTimersLDAC',['../group___d_a_c__ad5754.html#ga4204dbf05cb09398e186dcd71d37e0d7',1,'DAC_initTimersLDAC(bool enForcer, bool enQuad, uint32_t pulseWidth): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga4204dbf05cb09398e186dcd71d37e0d7',1,'DAC_initTimersLDAC(bool enForcer, bool enQuad, uint32_t pulseWidth): dac_ad5754.c']]],
['dac_5finthandlerssi',['DAC_intHandlerSSI',['../group___d_a_c__ad5754.html#gaabc6352feab3ad0f94de4b79bc0f5b72',1,'DAC_intHandlerSSI(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gaabc6352feab3ad0f94de4b79bc0f5b72',1,'DAC_intHandlerSSI(void): dac_ad5754.c']]],
['dac_5finthandlerssitimer',['DAC_intHandlerSSItimer',['../group___d_a_c__ad5754.html#ga37030529d834f166eef7114fd71190e5',1,'DAC_intHandlerSSItimer(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga37030529d834f166eef7114fd71190e5',1,'DAC_intHandlerSSItimer(void): dac_ad5754.c']]],
['dac_5floaddacs',['DAC_loadDACs',['../group___d_a_c__ad5754.html#ga1f7eda4d64087b938f5f62ec8e8cbe5e',1,'DAC_loadDACs(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga1f7eda4d64087b938f5f62ec8e8cbe5e',1,'DAC_loadDACs(void): dac_ad5754.c']]],
['dac_5floaddacspin',['DAC_loadDACsPin',['../group___d_a_c__ad5754.html#gaa375fe95555a421ca76283998e64ae41',1,'DAC_loadDACsPin(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gaa375fe95555a421ca76283998e64ae41',1,'DAC_loadDACsPin(void): dac_ad5754.c']]],
['dac_5floaddacspintimer',['DAC_loadDACsPinTimer',['../group___d_a_c__ad5754.html#ga65c9a05f616fd3cc94415869edf0c9c0',1,'DAC_loadDACsPinTimer(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga65c9a05f616fd3cc94415869edf0c9c0',1,'DAC_loadDACsPinTimer(void): dac_ad5754.c']]],
['dac_5fsetpowerctl',['DAC_setPowerCtl',['../group___d_a_c__ad5754.html#gae1622532a9332006dd5f19a22b98825b',1,'DAC_setPowerCtl(uint32_t pwrSettingsValue): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gae1622532a9332006dd5f19a22b98825b',1,'DAC_setPowerCtl(uint32_t pwrSettingsValue): dac_ad5754.c']]],
['dac_5fsetrange',['DAC_setRange',['../group___d_a_c__ad5754.html#ga04548e3a1e5b6a200c540b7a4227ec4d',1,'DAC_setRange(uint32_t dacAddress, uint32_t rangeValue): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga04548e3a1e5b6a200c540b7a4227ec4d',1,'DAC_setRange(uint32_t dacAddress, uint32_t rangeValue): dac_ad5754.c']]],
['dac_5fsetsettingsctl',['DAC_setSettingsCtl',['../group___d_a_c__ad5754.html#ga4c9d4568cf8efdb66e2ded3e2bde168d',1,'DAC_setSettingsCtl(uint32_t ctlSettingsValue): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga4c9d4568cf8efdb66e2ded3e2bde168d',1,'DAC_setSettingsCtl(uint32_t ctlSettingsValue): dac_ad5754.c']]],
['dac_5fssiintenableeot',['DAC_SSIIntEnableEOT',['../group___d_a_c__ad5754.html#ga95cf8880ebefcfa5a3c877f33a0de56f',1,'DAC_SSIIntEnableEOT(uint32_t ui32Base): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga95cf8880ebefcfa5a3c877f33a0de56f',1,'DAC_SSIIntEnableEOT(uint32_t ui32Base): dac_ad5754.c']]],
['dac_5fupdatedatadig',['DAC_updateDataDig',['../group___d_a_c__ad5754.html#ga6042bbafba1e30640f0dbdd9dbe4d6b1',1,'DAC_updateDataDig(uint32_t dacAddress, uint32_t data): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga6042bbafba1e30640f0dbdd9dbe4d6b1',1,'DAC_updateDataDig(uint32_t dacAddress, uint32_t data): dac_ad5754.c']]],
['dac_5fupdatedatavolt',['DAC_updateDataVolt',['../group___d_a_c__ad5754.html#gae6d7c8f3167d84f60a56a3c1bb6252b7',1,'DAC_updateDataVolt(uint32_t dacAddress, uint32_t rangeValue, _Bool bin, float voltage): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gae6d7c8f3167d84f60a56a3c1bb6252b7',1,'DAC_updateDataVolt(uint32_t dacAddress, uint32_t rangeValue, _Bool BIN, float voltage): dac_ad5754.c']]],
['dac_5fwritenop',['DAC_writeNop',['../group___d_a_c__ad5754.html#ga5c92c520051e198a9d24f5d14893f506',1,'DAC_writeNop(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga5c92c520051e198a9d24f5d14893f506',1,'DAC_writeNop(void): dac_ad5754.c']]],
['dacd_5fcleardacs_5fah',['DACd_clearDACs_AH',['../group___d_a_c__ad5754.html#ga45f4b52890f9373b7781925529b37f5a',1,'DACd_clearDACs_AH(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga45f4b52890f9373b7781925529b37f5a',1,'DACd_clearDACs_AH(void): dac_ad5754.c']]],
['dacd_5fcleardacs_5feh',['DACd_clearDACs_EH',['../group___d_a_c__ad5754.html#gafdc88b1e8452f3717199e9dfbc780992',1,'DACd_clearDACs_EH(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gafdc88b1e8452f3717199e9dfbc780992',1,'DACd_clearDACs_EH(void): dac_ad5754.c']]],
['dacd_5finitdac',['DACd_initDAC',['../group___d_a_c__ad5754.html#ga4d051b751ee930dca68513b6c7dec46e',1,'DACd_initDAC(uint32_t rangeValue, uint32_t pwrSettingsValue, uint32_t SysClkFreq): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga4d051b751ee930dca68513b6c7dec46e',1,'DACd_initDAC(uint32_t rangeValue, uint32_t pwrSettingsValue, uint32_t SysClkFreq): dac_ad5754.c']]],
['dacd_5floaddacs_5fah',['DACd_loadDACs_AH',['../group___d_a_c__ad5754.html#gaa88d6be5a9ccd5ff94b102c1f1a4b464',1,'DACd_loadDACs_AH(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gaa88d6be5a9ccd5ff94b102c1f1a4b464',1,'DACd_loadDACs_AH(void): dac_ad5754.c']]],
['dacd_5floaddacs_5feh',['DACd_loadDACs_EH',['../group___d_a_c__ad5754.html#ga5aa63b602b15c7328deb2e562501e8d2',1,'DACd_loadDACs_EH(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga5aa63b602b15c7328deb2e562501e8d2',1,'DACd_loadDACs_EH(void): dac_ad5754.c']]],
['dacd_5floaddacspin_5feh',['DACd_loadDACsPin_EH',['../group___d_a_c__ad5754.html#ga2b2a5da94a4c27b60e1577793bdb970e',1,'DACd_loadDACsPin_EH(void): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga2b2a5da94a4c27b60e1577793bdb970e',1,'DACd_loadDACsPin_EH(void): dac_ad5754.c']]],
['dacd_5fsetpowerctl',['DACd_setPowerCtl',['../group___d_a_c__ad5754.html#ga094f43f6aa44b22562d49efe5403c2ca',1,'DACd_setPowerCtl(uint32_t pwrSettingsValue): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga094f43f6aa44b22562d49efe5403c2ca',1,'DACd_setPowerCtl(uint32_t pwrSettingsValue): dac_ad5754.c']]],
['dacd_5fsetrange',['DACd_setRange',['../group___d_a_c__ad5754.html#ga20458db50830182bcf912a60e9df04cd',1,'DACd_setRange(uint32_t dacAddress, uint32_t rangeValue): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga20458db50830182bcf912a60e9df04cd',1,'DACd_setRange(uint32_t dacAddress, uint32_t rangeValue): dac_ad5754.c']]],
['dacd_5fsetsettingsctl',['DACd_setSettingsCtl',['../group___d_a_c__ad5754.html#gac3aeb454aade9dd1def535c072ea78fd',1,'DACd_setSettingsCtl(uint32_t ctlSettingsValue): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gac3aeb454aade9dd1def535c072ea78fd',1,'DACd_setSettingsCtl(uint32_t ctlSettingsValue): dac_ad5754.c']]],
['dacd_5fupdatedatadig',['DACd_updateDataDig',['../group___d_a_c__ad5754.html#ga14aa5f3fc7902cd96eefd32b56b728d4',1,'DACd_updateDataDig(uint32_t dacAddress, uint32_t data_AD, uint32_t data_EH): dac_ad5754.c'],['../group___d_a_c__ad5754.html#ga14aa5f3fc7902cd96eefd32b56b728d4',1,'DACd_updateDataDig(uint32_t dacAddress, uint32_t data_AD, uint32_t data_EH): dac_ad5754.c']]],
['dacd_5fupdatedatavolt',['DACd_updateDataVolt',['../group___d_a_c__ad5754.html#gaa6e1b8d821a10a4ca887a743f2123b3d',1,'DACd_updateDataVolt(uint32_t dacAddress, uint32_t rangeValue, _Bool bin_AD, _Bool bin_EH, float voltage_AD, float voltage_EH): dac_ad5754.c'],['../group___d_a_c__ad5754.html#gaa6e1b8d821a10a4ca887a743f2123b3d',1,'DACd_updateDataVolt(uint32_t dacAddress, uint32_t rangeValue, _Bool bin_AD, _Bool bin_EH, float voltage_AD, float voltage_EH): dac_ad5754.c']]],
['data',['data',['../structfloat_flash.html#a26e87220519c775d0f9d4ac76db58ef2',1,'floatFlash']]],
['databuffer',['dataBuffer',['../structfir_inst.html#ac14aaae21e04566f810b07f12356391d',1,'firInst']]],
['databufferend',['dataBufferEnd',['../structfir_inst.html#a37651cee0a39534fd328bea7a9544e64',1,'firInst']]],
['databufferstart',['dataBufferStart',['../structfir_inst.html#a091a490fe2e1bfccc41e380571b805b4',1,'firInst']]],
['datahead',['dataHead',['../structfir_inst.html#a36450131e3f9237482ea9759dc23117a',1,'firInst']]]
];
| mit |
kinkinweb/lhvb | vendor/sonata-project/ecommerce/src/Component/Customer/CustomerSelectorInterface.php | 220 | <?php
namespace Sonata\Component\Customer;
interface CustomerSelectorInterface
{
/**
* Get the customer.
*
* @return \Sonata\Component\Customer\CustomerInterface
*/
public function get();
}
| mit |
samael205/ExcelPHP | PhpSpreadsheet/Calculation/Functions.php | 19494 | <?php
namespace PhpOffice\PhpSpreadsheet\Calculation;
/* MAX_VALUE */
define('MAX_VALUE', 1.2e308);
/* 2 / PI */
define('M_2DIVPI', 0.63661977236758134307553505349006);
/* MAX_ITERATIONS */
define('MAX_ITERATIONS', 256);
/* PRECISION */
define('PRECISION', 8.88E-016);
/**
* Copyright (c) 2006 - 2016 PhpSpreadsheet
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PhpSpreadsheet
* @copyright Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class Functions
{
/** constants */
const COMPATIBILITY_EXCEL = 'Excel';
const COMPATIBILITY_GNUMERIC = 'Gnumeric';
const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc';
const RETURNDATE_PHP_NUMERIC = 'P';
const RETURNDATE_PHP_OBJECT = 'O';
const RETURNDATE_EXCEL = 'E';
/**
* Compatibility mode to use for error checking and responses
*
* @var string
*/
protected static $compatibilityMode = self::COMPATIBILITY_EXCEL;
/**
* Data Type to use when returning date values
*
* @var string
*/
protected static $returnDateType = self::RETURNDATE_EXCEL;
/**
* List of error codes
*
* @var array
*/
protected static $errorCodes = [
'null' => '#NULL!',
'divisionbyzero' => '#DIV/0!',
'value' => '#VALUE!',
'reference' => '#REF!',
'name' => '#NAME?',
'num' => '#NUM!',
'na' => '#N/A',
'gettingdata' => '#GETTING_DATA',
];
/**
* Set the Compatibility Mode
*
* @category Function Configuration
* @param string $compatibilityMode Compatibility Mode
* Permitted values are:
* Functions::COMPATIBILITY_EXCEL 'Excel'
* Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
* Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
* @return bool (Success or Failure)
*/
public static function setCompatibilityMode($compatibilityMode)
{
if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)
) {
self::$compatibilityMode = $compatibilityMode;
return true;
}
return false;
}
/**
* Return the current Compatibility Mode
*
* @category Function Configuration
* @return string Compatibility Mode
* Possible Return values are:
* Functions::COMPATIBILITY_EXCEL 'Excel'
* Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
* Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
*/
public static function getCompatibilityMode()
{
return self::$compatibilityMode;
}
/**
* Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
*
* @category Function Configuration
* @param string $returnDateType Return Date Format
* Permitted values are:
* Functions::RETURNDATE_PHP_NUMERIC 'P'
* Functions::RETURNDATE_PHP_OBJECT 'O'
* Functions::RETURNDATE_EXCEL 'E'
* @return bool Success or failure
*/
public static function setReturnDateType($returnDateType)
{
if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
($returnDateType == self::RETURNDATE_EXCEL)
) {
self::$returnDateType = $returnDateType;
return true;
}
return false;
}
/**
* Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
*
* @category Function Configuration
* @return string Return Date Format
* Possible Return values are:
* Functions::RETURNDATE_PHP_NUMERIC 'P'
* Functions::RETURNDATE_PHP_OBJECT 'O'
* Functions::RETURNDATE_EXCEL 'E'
*/
public static function getReturnDateType()
{
return self::$returnDateType;
}
/**
* DUMMY
*
* @category Error Returns
* @return string #Not Yet Implemented
*/
public static function DUMMY()
{
return '#Not Yet Implemented';
}
/**
* DIV0
*
* @category Error Returns
* @return string #Not Yet Implemented
*/
public static function DIV0()
{
return self::$errorCodes['divisionbyzero'];
}
/**
* NA
*
* Excel Function:
* =NA()
*
* Returns the error value #N/A
* #N/A is the error value that means "no value is available."
*
* @category Logical Functions
* @return string #N/A!
*/
public static function NA()
{
return self::$errorCodes['na'];
}
/**
* NaN
*
* Returns the error value #NUM!
*
* @category Error Returns
* @return string #NUM!
*/
public static function NAN()
{
return self::$errorCodes['num'];
}
/**
* NAME
*
* Returns the error value #NAME?
*
* @category Error Returns
* @return string #NAME?
*/
public static function NAME()
{
return self::$errorCodes['name'];
}
/**
* REF
*
* Returns the error value #REF!
*
* @category Error Returns
* @return string #REF!
*/
public static function REF()
{
return self::$errorCodes['reference'];
}
/**
* NULL
*
* Returns the error value #NULL!
*
* @category Error Returns
* @return string #NULL!
*/
public static function null()
{
return self::$errorCodes['null'];
}
/**
* VALUE
*
* Returns the error value #VALUE!
*
* @category Error Returns
* @return string #VALUE!
*/
public static function VALUE()
{
return self::$errorCodes['value'];
}
public static function isMatrixValue($idx)
{
return (substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0);
}
public static function isValue($idx)
{
return substr_count($idx, '.') == 0;
}
public static function isCellValue($idx)
{
return substr_count($idx, '.') > 1;
}
public static function ifCondition($condition)
{
$condition = self::flattenSingleValue($condition);
if (!isset($condition{0})) {
$condition = '=""';
}
if (!in_array($condition{0}, ['>', '<', '='])) {
if (!is_numeric($condition)) {
$condition = \PhpOffice\PhpSpreadsheet\Calculation::wrapResult(strtoupper($condition));
}
return '=' . $condition;
} else {
preg_match('/([<>=]+)(.*)/', $condition, $matches);
list(, $operator, $operand) = $matches;
if (!is_numeric($operand)) {
$operand = str_replace('"', '""', $operand);
$operand = \PhpOffice\PhpSpreadsheet\Calculation::wrapResult(strtoupper($operand));
}
return $operator . $operand;
}
}
/**
* ERROR_TYPE
*
* @param mixed $value Value to check
* @return bool
*/
public static function errorType($value = '')
{
$value = self::flattenSingleValue($value);
$i = 1;
foreach (self::$errorCodes as $errorCode) {
if ($value === $errorCode) {
return $i;
}
++$i;
}
return self::NA();
}
/**
* IS_BLANK
*
* @param mixed $value Value to check
* @return bool
*/
public static function isBlank($value = null)
{
if (!is_null($value)) {
$value = self::flattenSingleValue($value);
}
return is_null($value);
}
/**
* IS_ERR
*
* @param mixed $value Value to check
* @return bool
*/
public static function isErr($value = '')
{
$value = self::flattenSingleValue($value);
return self::isError($value) && (!self::isNa(($value)));
}
/**
* IS_ERROR
*
* @param mixed $value Value to check
* @return bool
*/
public static function isError($value = '')
{
$value = self::flattenSingleValue($value);
if (!is_string($value)) {
return false;
}
return in_array($value, array_values(self::$errorCodes));
}
/**
* IS_NA
*
* @param mixed $value Value to check
* @return bool
*/
public static function isNa($value = '')
{
$value = self::flattenSingleValue($value);
return $value === self::NA();
}
/**
* IS_EVEN
*
* @param mixed $value Value to check
* @return string|bool
*/
public static function isEven($value = null)
{
$value = self::flattenSingleValue($value);
if ($value === null) {
return self::NAME();
} elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
return self::VALUE();
}
return $value % 2 == 0;
}
/**
* IS_ODD
*
* @param mixed $value Value to check
* @return string|bool
*/
public static function isOdd($value = null)
{
$value = self::flattenSingleValue($value);
if ($value === null) {
return self::NAME();
} elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
return self::VALUE();
}
return abs($value) % 2 == 1;
}
/**
* IS_NUMBER
*
* @param mixed $value Value to check
* @return bool
*/
public static function isNumber($value = null)
{
$value = self::flattenSingleValue($value);
if (is_string($value)) {
return false;
}
return is_numeric($value);
}
/**
* IS_LOGICAL
*
* @param mixed $value Value to check
* @return bool
*/
public static function isLogical($value = null)
{
$value = self::flattenSingleValue($value);
return is_bool($value);
}
/**
* IS_TEXT
*
* @param mixed $value Value to check
* @return bool
*/
public static function isText($value = null)
{
$value = self::flattenSingleValue($value);
return is_string($value) && !self::isError($value);
}
/**
* IS_NONTEXT
*
* @param mixed $value Value to check
* @return bool
*/
public static function isNonText($value = null)
{
return !self::isText($value);
}
/**
* VERSION
*
* @return string Version information
*/
public static function VERSION()
{
return 'PhpSpreadsheet ##VERSION##, ##DATE##';
}
/**
* N
*
* Returns a value converted to a number
*
* @param value The value you want converted
* @return number N converts values listed in the following table
* If value is or refers to N returns
* A number That number
* A date The serial number of that date
* TRUE 1
* FALSE 0
* An error value The error value
* Anything else 0
*/
public static function n($value = null)
{
while (is_array($value)) {
$value = array_shift($value);
}
switch (gettype($value)) {
case 'double':
case 'float':
case 'integer':
return $value;
case 'boolean':
return (integer) $value;
case 'string':
// Errors
if ((strlen($value) > 0) && ($value{0} == '#')) {
return $value;
}
break;
}
return 0;
}
/**
* TYPE
*
* Returns a number that identifies the type of a value
*
* @param value The value you want tested
* @return number N converts values listed in the following table
* If value is or refers to N returns
* A number 1
* Text 2
* Logical Value 4
* An error value 16
* Array or Matrix 64
*/
public static function TYPE($value = null)
{
$value = self::flattenArrayIndexed($value);
if (is_array($value) && (count($value) > 1)) {
end($value);
$a = key($value);
// Range of cells is an error
if (self::isCellValue($a)) {
return 16;
// Test for Matrix
} elseif (self::isMatrixValue($a)) {
return 64;
}
} elseif (empty($value)) {
// Empty Cell
return 1;
}
$value = self::flattenSingleValue($value);
if (($value === null) || (is_float($value)) || (is_int($value))) {
return 1;
} elseif (is_bool($value)) {
return 4;
} elseif (is_array($value)) {
return 64;
} elseif (is_string($value)) {
// Errors
if ((strlen($value) > 0) && ($value{0} == '#')) {
return 16;
}
return 2;
}
return 0;
}
/**
* Convert a multi-dimensional array to a simple 1-dimensional array
*
* @param array $array Array to be flattened
* @return array Flattened array
*/
public static function flattenArray($array)
{
if (!is_array($array)) {
return (array) $array;
}
$arrayValues = [];
foreach ($array as $value) {
if (is_array($value)) {
foreach ($value as $val) {
if (is_array($val)) {
foreach ($val as $v) {
$arrayValues[] = $v;
}
} else {
$arrayValues[] = $val;
}
}
} else {
$arrayValues[] = $value;
}
}
return $arrayValues;
}
/**
* Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
*
* @param array $array Array to be flattened
* @return array Flattened array
*/
public static function flattenArrayIndexed($array)
{
if (!is_array($array)) {
return (array) $array;
}
$arrayValues = [];
foreach ($array as $k1 => $value) {
if (is_array($value)) {
foreach ($value as $k2 => $val) {
if (is_array($val)) {
foreach ($val as $k3 => $v) {
$arrayValues[$k1 . '.' . $k2 . '.' . $k3] = $v;
}
} else {
$arrayValues[$k1 . '.' . $k2] = $val;
}
}
} else {
$arrayValues[$k1] = $value;
}
}
return $arrayValues;
}
/**
* Convert an array to a single scalar value by extracting the first element
*
* @param mixed $value Array or scalar value
* @return mixed
*/
public static function flattenSingleValue($value = '')
{
while (is_array($value)) {
$value = array_pop($value);
}
return $value;
}
}
//
// There are a few mathematical functions that aren't available on all versions of PHP for all platforms
// These functions aren't available in Windows implementations of PHP prior to version 5.3.0
// So we test if they do exist for this version of PHP/operating platform; and if not we create them
//
if (!function_exists('acosh')) {
function acosh($x)
{
return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
} // function acosh()
}
if (!function_exists('asinh')) {
function asinh($x)
{
return log($x + sqrt(1 + $x * $x));
} // function asinh()
}
if (!function_exists('atanh')) {
function atanh($x)
{
return (log(1 + $x) - log(1 - $x)) / 2;
} // function atanh()
}
//
// Strangely, PHP doesn't have a mb_str_replace multibyte function
// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
//
if ((!function_exists('mb_str_replace')) &&
(function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))
) {
function mb_str_replace($search, $replace, $subject)
{
if (is_array($subject)) {
$ret = [];
foreach ($subject as $key => $val) {
$ret[$key] = mb_str_replace($search, $replace, $val);
}
return $ret;
}
foreach ((array) $search as $key => $s) {
if ($s == '' && $s !== 0) {
continue;
}
$r = !is_array($replace) ? $replace : (isset($replace[$key]) ? $replace[$key] : '');
$pos = mb_strpos($subject, $s, 0, 'UTF-8');
while ($pos !== false) {
$subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), null, 'UTF-8');
$pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
}
}
return $subject;
}
}
| mit |
jaredbeck/sexp2ruby | lib/sexp2ruby/node/ivar.rb | 124 | module Sexp2Ruby
module Node
class Ivar < Base
def to_s(exp)
exp.shift.to_s
end
end
end
end
| mit |
EdgarSun/Django-Demo | urls.py | 1431 | from django.conf.urls.defaults import *
from django.conf import settings
handler500 = 'djangotoolbox.errorviews.server_error'
urlpatterns = patterns('',
('^_ah/warmup$', 'djangoappengine.views.warmup'),
# ('^$', 'django.views.generic.simple.direct_to_template',
# {'template': 'home.html'}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), # static content
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}), # static content
(r'^$', 'general.views.render_generic_page'),
(r'^urlshortener/(?P<url>.*)$', 'utils.shortenerUrl.generate_shortener_url'),
(r'^micronote/', include('micronote.urls')),
(r'^comment/', include('micronote.urls')),
(r'^account/', include('account.urls')),
(r'^general/', include('general.urls')),
(r'^tag/', include('tagging.urls')),
(r'^event/', include('event.urls')),
(r'^showcase/', include('showcase.urls')),
(r'^upload/', include('google_dependency.urls')),
(r'^resource/', include('google_dependency.urls')),
(r'^samples/', include('samples.urls')),
#(r'^admin/', include(admin.site.urls)),
#favicon
(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/images/favicon.ico'}),
(r'^favicon\.png$', 'django.views.generic.simple.redirect_to', {'url': '/static/images/favicon.png'}),
)
| mit |
microTK/microTK | tests/append.js | 2017 | describe('append()', function() {
beforeEach(function() {
document.body.innerHTML = '<p id="idFixtrue">Some HTML</p><div class="classFixture"><span></span></div><div class="classFixture"></div><div class="classFixture"></div><span></span>';
});
afterEach(function() {
document.body.innerHTML = '';
});
it("microTK('span').append(element)", function () {
var control = document.querySelectorAll('span');
var sample = microTK('span');
var element = document.createElement("div");
element.classList.add("testDiv");
var results = sample.append(element);
expect(results.constructor.name).toEqual("MicroTK");
expect(sample.length).toEqual(control.length);
for (var i = 0; i < sample.length; i++) {
expect(control[i].lastChild).toEqual(element);
}
});
it("microTK('#idFixtrue').append(element)", function () {
var control = document.querySelectorAll('#idFixtrue');
var sample = microTK('#idFixtrue');
var element = document.createElement("div");
element.classList.add("testDiv");
var results = sample.append(element);
expect(results.constructor.name).toEqual("MicroTK");
expect(sample.length).toEqual(control.length);
for (var i = 0; i < sample.length; i++) {
expect(control[i].lastChild).toEqual(element);
}
});
it("microTK('.classFixture').append(element)", function () {
var control = document.querySelectorAll('.classFixture');
var sample = microTK('.classFixture');
var element = document.createElement("div");
element.classList.add("testDiv");
var results = sample.append(element);
expect(results.constructor.name).toEqual("MicroTK");
expect(sample.length).toEqual(control.length);
for (var i = 0; i < sample.length; i++) {
expect(control[i].lastChild).toEqual(element);
}
});
}); | mit |
sscaff1/eng_tasks | Test/Case/Model/RoleTest.php | 628 | <?php
App::uses('Role', 'Model');
/**
* Role Test Case
*
*/
class RoleTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array(
'app.role',
'app.user',
'app.work_time',
'app.task',
'app.mach_config',
'app.mach_model',
'app.task_type',
'app.status',
'app.issue',
'app.issue_type',
'app.tasks_user'
);
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Role = ClassRegistry::init('Role');
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->Role);
parent::tearDown();
}
}
| mit |
stephenfuqua/safnetDirectory | safnetDirectory/Properties/AssemblyInfo.cs | 1402 | 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("safnet-directory")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("safnet-directory")]
[assembly: AssemblyCopyright("Copyright © 2018, Stephen A. Fuqua")]
[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("0df7f4c7-5bc0-4e73-a363-61612ed26bee")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: InternalsVisibleTo("safnetDirectory.FullMvc.Tests")] | mit |
ossim/lately | python_tutorial/python_tutorial/settings.py | 2681 | """
Django settings for python_tutorial project.
Generated by 'django-admin startproject' using Django 1.8.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mnp*8d7ix)eivdvg@9j2__4j99tj4fz%chw8u70fazlf2yz73a'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tutorial',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'python_tutorial.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'python_tutorial.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| mit |
kpsuperplane/personal-website | versions/1.19.0/core/server/data/importer/importers/data/base.js | 8232 | 'use strict';
const debug = require('ghost-ignition').debug('importer:base'),
common = require('../../../../lib/common'),
models = require('../../../../models'),
_ = require('lodash'),
Promise = require('bluebird');
class Base {
constructor(options) {
let self = this;
this.modelName = options.modelName;
this.problems = [];
this.errorConfig = {
allowDuplicates: true,
returnDuplicates: true,
showNotFoundWarning: true
};
this.legacyKeys = {};
this.legacyMapper = function legacyMapper(item) {
return _.mapKeys(item, function matchLegacyKey(value, key) {
return self.legacyKeys[key] || key;
});
};
this.dataKeyToImport = options.dataKeyToImport;
this.dataToImport = _.cloneDeep(options[this.dataKeyToImport] || []);
this.importedData = [];
// NOTE: e.g. properties are removed or properties are added/changed before importing
_.each(options, function (obj, key) {
if (options.requiredData.indexOf(key) !== -1) {
self[key] = _.cloneDeep(obj);
}
});
if (!this.users) {
this.users = _.cloneDeep(options.users);
}
}
/**
* Never ever import these attributes!
*/
stripProperties(properties) {
_.each(this.dataToImport, function (obj) {
_.each(properties, function (property) {
delete obj[property];
});
});
}
/**
* Clean invalid values.
*/
sanitizeValues() {
let temporaryDate, self = this;
_.each(this.dataToImport, function (obj) {
_.each(_.pick(obj, ['updated_at', 'created_at', 'published_at']), function (value, key) {
temporaryDate = new Date(value);
if (isNaN(temporaryDate)) {
self.problems.push({
message: 'Date is in a wrong format and invalid. It was replaced with the current timestamp.',
help: self.modelName,
context: JSON.stringify(obj)
});
obj[key] = new Date().toISOString();
}
});
});
}
beforeImport() {
this.stripProperties(['id']);
this.sanitizeValues();
return Promise.resolve();
}
handleError(errs, obj) {
let self = this, errorsToReject = [], problems = [];
// CASE: validation errors, see models/base/events.js onValidate
if (!_.isArray(errs)) {
errs = [errs];
}
_.each(errs, function (err) {
if (err.code && err.message.toLowerCase().indexOf('unique') !== -1) {
if (self.errorConfig.allowDuplicates) {
if (self.errorConfig.returnDuplicates) {
problems.push({
message: 'Entry was not imported and ignored. Detected duplicated entry.',
help: self.modelName,
context: JSON.stringify(obj),
err: err
});
}
} else {
errorsToReject.push(new common.errors.DataImportError({
message: 'Detected duplicated entry.',
help: self.modelName,
context: JSON.stringify(obj),
err: err
}));
}
} else if (err instanceof common.errors.NotFoundError) {
if (self.showNotFoundWarning) {
problems.push({
message: 'Entry was not imported and ignored. Could not find entry.',
help: self.modelName,
context: JSON.stringify(obj),
err: err
});
}
} else {
if (!common.errors.utils.isIgnitionError(err)) {
err = new common.errors.DataImportError({
message: err.message,
context: JSON.stringify(obj),
help: self.modelName,
errorType: err.errorType,
err: err
});
} else {
err.context = JSON.stringify(obj);
}
errorsToReject.push(err);
}
});
if (!errorsToReject.length) {
this.problems = this.problems.concat(problems);
debug('detected problem/warning', problems);
return Promise.resolve();
}
debug('err', errorsToReject, obj);
return Promise.reject(errorsToReject);
}
doImport(options) {
debug('doImport', this.modelName, this.dataToImport.length);
let self = this, ops = [];
_.each(this.dataToImport, function (obj) {
ops.push(models[self.modelName].add(obj, options)
.then(function (importedModel) {
obj.model = importedModel.toJSON();
self.importedData.push(obj.model);
return importedModel;
})
.catch(function (err) {
return self.handleError(err, obj);
})
.reflect()
);
});
return Promise.all(ops);
}
/**
* Update all user reference fields e.g. published_by
*
* Background:
* - we never import the id field
* - almost each imported model has a reference to a user reference
* - we update all fields after the import (!)
*/
afterImport(options) {
let self = this, dataToEdit = {}, oldUser, context;
debug('afterImport', this.modelName);
return models.User.getOwnerUser(options)
.then(function (ownerUser) {
return Promise.each(self.dataToImport, function (obj) {
if (!obj.model) {
return;
}
return Promise.each(['author_id', 'published_by', 'created_by', 'updated_by'], function (key) {
// CASE: not all fields exist on each model, skip them if so
if (!obj[key]) {
return Promise.resolve();
}
oldUser = _.find(self.users, {id: obj[key]});
if (!oldUser) {
self.problems.push({
message: 'Entry was imported, but we were not able to update user reference field: ' + key,
help: self.modelName,
context: JSON.stringify(obj)
});
return;
}
return models.User.findOne({
email: oldUser.email,
status: 'all'
}, options).then(function (userModel) {
// CASE: user could not be imported e.g. multiple roles attached
if (!userModel) {
userModel = {
id: ownerUser.id
};
}
dataToEdit = {};
dataToEdit[key] = userModel.id;
// CASE: updated_by is taken from the context object
if (key === 'updated_by') {
context = {context: {user: userModel.id}};
} else {
context = {};
}
return models[self.modelName].edit(dataToEdit, _.merge({}, options, {id: obj.model.id}, context));
});
});
});
});
}
}
module.exports = Base;
| mit |
Frky/moon | webpack-prod.config.js | 784 | var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
var config = {
context: __dirname,
entry: {
'app': './website/static/website/js/index',
},
output: {
path: path.resolve('./website/static/dist/'),
filename: "[name].bundle.js"
},
plugins: [],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel-loader?presets[]=react&presets[]=es2015']
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
}
};
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true
}
})
)
}
module.exports = config; | mit |
zmira/abremir.AllMyBricks | abremir.AllMyBricks.Data/Interfaces/IThemeRepository.cs | 339 | using abremir.AllMyBricks.Data.Models;
using System.Collections.Generic;
namespace abremir.AllMyBricks.Data.Interfaces
{
public interface IThemeRepository
{
Theme AddOrUpdate(Theme theme);
Theme Get(string themeName);
IEnumerable<Theme> All();
IEnumerable<Theme> AllForYear(short year);
}
}
| mit |
fs-opensource/nodejs-account-boilerplate | test/user-tests.js | 4003 | /**
* Created by npeitek on 01/27/14.
*
* this file tests if the user handling works as expected
*/
// set up environment
//var http = require('http');
//var app = require('../server/app')();
var should = require('should');
// get customer api
var UserSchema = require('../server/schemas/users');
var userApi = require("../server/api/user-api");
var helper = require('../server/modules/helper');
describe("User Account Functionality", function(){
var dummyUser = new UserSchema.userModel({
email: "[email protected]",
phone: "123456789",
password: "password",
auth_token: helper.createRandomString(32),
auth_token_issued: new Date(),
register_date: new Date(),
subscriptions: [],
role: "Customer"
});
// save the dummy user before starting the tests
before(function(done){
dummyUser.save(function (err) {
if (err) {
throw(err)
}
else {
done();
}
});
});
// remove everything at the end
after(function(done){
UserSchema.userModel.remove(function() {
done();
});
});
/*
// try to register a new user
it("register new user - valid data", function(done){
var mockReq = {};
mockReq.body = {};
mockReq.body.email = "[email protected]";
mockReq.body.password = "testtest";
mockReq.body.phone = "123456789"
userApi.signupUser(mockReq, function(result){
if (!result.successful) {
throw(result.error);
}
currentUser = result.result;
done();
});
});
*/
it("register new user - password too short", function(done){
var mockReq = {};
mockReq.body = {};
mockReq.body.email = "[email protected]";
mockReq.body.password = "123";
mockReq.body.phone = "123456789"
userApi.signupUser(mockReq, function(err, result){
if (err) {
return done();
}
throw("registration should be declined");
});
});
it("register new user - no valid email", function(done){
var mockReq = {};
mockReq.body = {};
mockReq.body.email = "@futurestud.io";
mockReq.body.password = "123456789";
mockReq.body.phone = "123456789"
userApi.signupUser(mockReq, function(err, result){
if (err) {
return done();
}
throw("registration should be declined");
});
});
it("get user by auth_token", function(done){
var mockReq = {};
mockReq.headers = {};
mockReq.headers.auth_token = dummyUser.auth_token;
userApi.checkAuthToken(mockReq, function(err, user){
if (err) {
throw("check auth token failed");
}
if (user == undefined) {
throw("no user returned");
}
if (user.email !== dummyUser.email) {
throw("email is incorrect");
}
done();
});
});
it("get user by invalid auth_token", function(done){
var mockReq = {};
mockReq.headers = {};
mockReq.headers.auth_token = "some_random_non_existing_auth_token";
userApi.checkAuthToken(mockReq, function(err, user){
if (!err) {
throw("this should not return a user");
}
done();
});
});
// todo add login check
/*
it("dummy user - login", function(done){
var mockReq = {};
mockReq.body = {};
mockReq.body.email = "@futurestud.io";
mockReq.body.password = "123456789";
mockReq.body.phone = "123456789"
userApi.signupUser(mockReq, function(result){
if (!result.successful) {
done();
}
throw("registration should be declined");
});
});
*/
}); | mit |
HKMOpen/VendingMachine | vendSDK/demo/src/main/java/com/hkmvend/apiclitest/mosaic/Block.java | 1120 | package com.hkmvend.apiclitest.mosaic;
/**
* Created by zJJ on 1/23/2016.
*/
import java.util.ArrayList;
public class Block {
// Identifier to recognize the block
int id;
// The left edge of the block
public double x1;
// The top edge of the block
public double y1;
// The right edge of the block
public double x2;
// The bottom edge of the block
public double y2;
// The width of the block in pixels
public double width;
// The height of the block in pixels
public double height;
// The type of the block
public int type;
// The set of cell units that represent the block
public ArrayList<Cell> cells = new ArrayList<Cell>();
/**
* Get how much the block should be shifted below depending on the previous
* records.
*/
public double getHeightShift(double maxYs[]) {
double maxHeight = 0.0;
for (int i = 0; i < cells.size(); i++) {
if (maxYs[cells.get(i).coorX] > maxHeight) {
maxHeight = maxYs[cells.get(i).coorX];
}
}
return maxHeight;
}
} | mit |
indigotech/graphql-schema-decorator | examples/apollo-server/src/schema/index.ts | 462 | import { Query, Mutation, Schema, schemaFactory, Subscription } from 'graphql-schema-decorator';
import UserQuery from './user.query';
import UserMutation from './user.mutation';
import UserSubscription from './user.subscription';
@Schema()
class RootSchema {
@Query()
UserQuery: UserQuery;
@Mutation()
UserMutation: UserMutation;
@Subscription()
UserSubscription: UserSubscription;
}
const schema = schemaFactory(RootSchema);
export default schema;
| mit |
dockyard/ember-cart | addon/instance-initializers/cart.js | 675 | import Ember from 'ember';
const {
A
} = Ember;
export function initialize(appInstance) {
let CartService = appInstance._lookupFactory('service:cart');
let payload;
if (window.localStorage.getItem('cart')) {
payload = window.localStorage.getItem('cart');
payload = JSON.parse(payload);
}
let cart = CartService.create({
content: A()
});
if (payload && cart.localStorage) {
cart.pushPayload(payload);
}
appInstance.register('cart:main', cart, { instantiate: false });
appInstance.inject('controller', 'cart', 'cart:main');
appInstance.inject('component', 'cart', 'cart:main');
}
export default {
name: 'cart',
initialize
};
| mit |
DimitrisVlachos/INTEL-AYC-2013SUMMER--2ND-PLACE-SOLUTION | includes/types.hpp | 1347 | /*
Builtin & custom types
Author : Dimitris Vlachos ([email protected] @ github.com/DimitrisVlachos)
*/
#ifndef __types__hpp__
#define __types__hpp__
#undef __USE_MAPPED_IO__
#include <stdint.h>
#include <stddef.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <list>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#ifndef __MIC__BUILD__
#include <emmintrin.h>
#include <xmmintrin.h>
#else
#include <immintrin.h>
#include <zmmintrin.h>
#endif
typedef float f32_t;
typedef double f64_t;
typedef uint32_t boolean_t;
struct parameters_t {
uint32_t nb_threads,max_scale,max_rot;
std::string main_image_name;
std::list<std::string> template_names;
};
struct result_t {
uint32_t pattern;
uint32_t px;
uint32_t py;
uint32_t _align;
};
typedef struct __attribute__ ((__packed__)){
//BMP header
uint16_t magic_number;
uint32_t size;
uint32_t reserved;
uint32_t offset;
//DIB header
uint32_t dibSize;
uint32_t width;
uint32_t height;
uint16_t plane;
uint16_t bit_per_pixel;
uint32_t compression;
uint32_t data_size;
uint32_t hor_res;
uint32_t vert_res;
uint32_t color_number;
uint32_t important;
}bmp_header_t;
#endif
| mit |
voidpp/PCA9685-driver-http | pca9685_driver_http/http.py | 296 | import logging
import json
logger = logging.getLogger(__name__)
class HttpException(Exception):
def __init__(self, message, code):
super(HttpException, self).__init__(message)
self.code = code
def create_response(data, code = 200):
return json.dumps(data) + "\n", code
| mit |
jpanikulam/experiments | lanczos/newtonian_object.hh | 485 | #pragma once
#include "lanczos/rigid_body.hh"
namespace lanczos {
struct NewtonianObject {
RigidBody body;
double mass_kg = 1.0;
// pkg --> "per kilogram"
Eigen::Matrix3d inertia_pkg = Eigen::Matrix3d::Identity();
RigidBodySimulationConfig rigid_body_cfg = {};
};
NewtonianObject simulate(const NewtonianObject& object,
const Vec3& force,
const Vec3& torque,
double dt);
} // namespace lanczos
| mit |
jonaustin/craigslist-housing-mapper | cake/tests/cases/libs/view/helpers/rss.test.php | 9917 | <?php
/* SVN FILE: $Id: rss.test.php 7296 2008-06-27 09:09:03Z gwoo $ */
/**
* Short description for file.
*
* Long description for file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc.
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @package cake.tests
* @subpackage cake.tests.cases.libs.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @version $Revision: 7296 $
* @modifiedby $LastChangedBy: gwoo $
* @lastmodified $Date: 2008-06-27 02:09:03 -0700 (Fri, 27 Jun 2008) $
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Helper', array('Rss', 'Time'));
/**
* Short description for class.
*
* @package cake.tests
* @subpackage cake.tests.cases.libs.view.helpers
*/
class RssTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->Rss =& new RssHelper();
$this->Rss->Time =& new TimeHelper();
$this->Rss->beforeRender();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Rss);
}
/**
* testAddNamespace method
*
* @access public
* @return void
*/
function testAddNamespace() {
$this->Rss->addNs('custom', 'http://example.com/dtd.xml');
$manager =& XmlManager::getInstance();
$expected = array('custom' => 'http://example.com/dtd.xml');
$this->assertEqual($manager->namespaces, $expected);
$this->Rss->removeNs('custom');
$this->Rss->addNs('dummy', 'http://dummy.com/1.0/');
$res = $this->Rss->document();
$this->assertPattern('/^<rss xmlns:dummy="http:\/\/dummy\.com\/1.0\/" version="2.0" \/>$/', $res);
$this->Rss->removeNs('dummy');
}
/**
* testRemoveNamespace method
*
* @access public
* @return void
*/
function testRemoveNamespace() {
$this->Rss->addNs('custom', 'http://example.com/dtd.xml');
$this->Rss->addNs('custom2', 'http://example.com/dtd2.xml');
$manager =& XmlManager::getInstance();
$expected = array('custom' => 'http://example.com/dtd.xml', 'custom2' => 'http://example.com/dtd2.xml');
$this->assertEqual($manager->namespaces, $expected);
$this->Rss->removeNs('custom');
$expected = array('custom2' => 'http://example.com/dtd2.xml');
$this->assertEqual($manager->namespaces, $expected);
}
/**
* testDocument method
*
* @access public
* @return void
*/
function testDocument() {
$res = $this->Rss->document();
$this->assertPattern('/^<rss version="2.0" \/>$/', $res);
$res = $this->Rss->document(array('contrived' => 'parameter'));
$this->assertPattern('/^<rss version="2.0"><parameter \/><\/rss>$/', $res);
$res = $this->Rss->document(null, 'content');
$this->assertPattern('/^<rss version="2.0">content<\/rss>$/', $res);
$res = $this->Rss->document(array('contrived' => 'parameter'), 'content');
$this->assertPattern('/^<rss[^<>]+version="2.0"[^<>]*>/', $res);
$this->assertPattern('/<rss[^<>]+contrived="parameter"[^<>]*>/', $res);
$this->assertNoPattern('/<rss[^<>]+[^version|contrived]=[^<>]*>/', $res);
}
/**
* testChannel method
*
* @access public
* @return void
*/
function testChannel() {
$attrib = array('a' => '1', 'b' => '2');
$elements['title'] = 'title';
$content = 'content';
$res = $this->Rss->channel($attrib, $elements, $content);
$this->assertPattern('/^<channel[^<>]+a="1"[^<>]*>/', $res);
$this->assertPattern('/^<channel[^<>]+b="2"[^<>]*>/', $res);
$this->assertNoPattern('/^<channel[^<>]+[^a|b]=[^<>]*/', $res);
$this->assertPattern('/<title>title<\/title>/', $res);
$this->assertPattern('/<link>'.str_replace('/', '\/', RssHelper::url('/', true)).'<\/link>/', $res);
$this->assertPattern('/<description \/>/', $res);
$this->assertPattern('/content<\/channel>$/', $res);
}
/**
* testChannelElementLevelAttrib method
*
* @access public
* @return void
*/
function testChannelElementLevelAttrib() {
$attrib = array();
$elements['title'] = 'title';
$elements['image'] = array('myImage', 'attrib' => array('href' => 'http://localhost'));
$content = 'content';
$res = $this->Rss->channel($attrib, $elements, $content);
$this->assertPattern('/^<channel>/', $res);
$this->assertPattern('/<title>title<\/title>/', $res);
$this->assertPattern('/<image[^<>]+href="http:\/\/localhost"><myImage \/><\/image>/', $res);
$this->assertPattern('/<link>'.str_replace('/', '\/', RssHelper::url('/', true)).'<\/link>/', $res);
$this->assertPattern('/<description \/>/', $res);
$this->assertPattern('/content<\/channel>$/', $res);
}
/**
* testItems method
*
* @access public
* @return void
*/
function testItems() {
$items = array(
array('title' => 'title1', 'guid' => 'http://www.example.com/guid1', 'link' => 'http://www.example.com/link1', 'description' => 'description1'),
array('title' => 'title2', 'guid' => 'http://www.example.com/guid2', 'link' => 'http://www.example.com/link2', 'description' => 'description2'),
array('title' => 'title3', 'guid' => 'http://www.example.com/guid3', 'link' => 'http://www.example.com/link3', 'description' => 'description3')
);
$result = $this->Rss->items($items);
$this->assertPattern('/^<item>.*<\/item><item>.*<\/item><item>.*<\/item>$/', $result);
$this->assertPattern('/<item>.*<title>title1<\/title>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<guid>' . str_replace('/', '\/', 'http://www.example.com/guid1') . '<\/guid>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<link>' . str_replace('/', '\/', 'http://www.example.com/link1') . '<\/link>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<description>description1<\/description>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<title>title2<\/title>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<guid>' . str_replace('/', '\/', 'http://www.example.com/guid2') . '<\/guid>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<link>' . str_replace('/', '\/', 'http://www.example.com/link2') . '<\/link>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<description>description2<\/description>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<title>title3<\/title>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<guid>' . str_replace('/', '\/', 'http://www.example.com/guid3') . '<\/guid>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<link>' . str_replace('/', '\/', 'http://www.example.com/link3') . '<\/link>.*<\/item>/', $result);
$this->assertPattern('/<item>.*<description>description3<\/description>.*<\/item>/', $result);
$result = $this->Rss->items(array());
$this->assertEqual($result, '');
}
/**
* testItem method
*
* @access public
* @return void
*/
function testItem() {
$result = $this->Rss->item(null, array("title"=>"My title","description"=>"My description","link"=>"http://www.google.com/"));
$expecting = '<item><title>My title</title><description>My description</description><link>http://www.google.com/</link><guid>http://www.google.com/</guid></item>';
$this->assertEqual($result, $expecting);
$item = array(
'title' => array(
'value' => 'My Title',
'cdata' => true,
),
'link' => 'http://www.example.com/1',
'description' => array(
'value' => 'descriptive words',
'cdata' => true,
),
'pubDate' => '2008-05-31 12:00:00',
'guid' => 'http://www.example.com/1'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title]]',
'/title',
'<link',
'http://www.example.com/1',
'/link',
'<description',
'<![CDATA[descriptive words]]',
'/description',
'<pubDate',
'Sat, 31 May 2008 12:00:00 ' . date('O'),
'/pubDate',
'<guid',
'http://www.example.com/1',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title & more',
'cdata' => true
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title & more]]',
'/title',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title & more',
'convertEntities' => false
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'My Title & more',
'/title',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title & more',
'cdata' => true,
'convertEntities' => false,
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title & more]]',
'/title',
'/item'
);
$this->assertTags($result, $expected);
}
/**
* testTime method
*
* @access public
* @return void
*/
function testTime() {
}
/**
* testElementAttrNotInParent method
*
* @access public
* @return void
*/
function testElementAttrNotInParent() {
$attributes = array('title' => 'Some Title', 'link' => 'http://link.com', 'description' => 'description');
$elements = array('enclosure' => array('url' => 'http://test.com'));
$result = $this->Rss->item($attributes, $elements);
$expected = array(
'item' => array('title' => 'Some Title', 'link' => 'http://link.com', 'description' => 'description'),
'enclosure' => array('url' => 'http://test.com'),
'/item'
);
$this->assertTags($result, $expected);
}
}
?> | mit |
F5Networks/f5-icontrol-library-dotnet | iControl/Interfaces/System/SystemHAGroup.cs | 64419 | namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="System.HAGroupBinding", Namespace="urn:iControl")]
public partial class SystemHAGroup : iControlInterface {
public SystemHAGroup() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_cluster
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void add_cluster(
string [] ha_groups,
string [] [] clusters,
long [] [] weights
) {
this.Invoke("add_cluster", new object [] {
ha_groups,
clusters,
weights});
}
public System.IAsyncResult Beginadd_cluster(string [] ha_groups,string [] [] clusters,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_cluster", new object[] {
ha_groups,
clusters,
weights}, callback, asyncState);
}
public void Endadd_cluster(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void add_pool(
string [] ha_groups,
string [] [] pools,
long [] [] weights
) {
this.Invoke("add_pool", new object [] {
ha_groups,
pools,
weights});
}
public System.IAsyncResult Beginadd_pool(string [] ha_groups,string [] [] pools,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_pool", new object[] {
ha_groups,
pools,
weights}, callback, asyncState);
}
public void Endadd_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_trunk
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void add_trunk(
string [] ha_groups,
string [] [] trunks,
long [] [] weights
) {
this.Invoke("add_trunk", new object [] {
ha_groups,
trunks,
weights});
}
public System.IAsyncResult Beginadd_trunk(string [] ha_groups,string [] [] trunks,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_trunk", new object[] {
ha_groups,
trunks,
weights}, callback, asyncState);
}
public void Endadd_trunk(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void create(
string [] ha_groups
) {
this.Invoke("create", new object [] {
ha_groups});
}
public System.IAsyncResult Begincreate(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
ha_groups}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_high_availability_groups
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void delete_all_high_availability_groups(
) {
this.Invoke("delete_all_high_availability_groups", new object [0]);
}
public System.IAsyncResult Begindelete_all_high_availability_groups(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_high_availability_groups", new object[0], callback, asyncState);
}
public void Enddelete_all_high_availability_groups(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_high_availability_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void delete_high_availability_group(
string [] ha_groups
) {
this.Invoke("delete_high_availability_group", new object [] {
ha_groups});
}
public System.IAsyncResult Begindelete_high_availability_group(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_high_availability_group", new object[] {
ha_groups}, callback, asyncState);
}
public void Enddelete_high_availability_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_active_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_active_score(
string [] ha_groups
) {
object [] results = this.Invoke("get_active_score", new object [] {
ha_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_active_score(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_active_score", new object[] {
ha_groups}, callback, asyncState);
}
public long [] Endget_active_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_cluster(
string [] ha_groups
) {
object [] results = this.Invoke("get_cluster", new object [] {
ha_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster", new object[] {
ha_groups}, callback, asyncState);
}
public string [] [] Endget_cluster(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemHAGroupHAGroupClusterAttribute [] [] get_cluster_attribute(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute", new object [] {
ha_groups,
clusters});
return ((SystemHAGroupHAGroupClusterAttribute [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public SystemHAGroupHAGroupClusterAttribute [] [] Endget_cluster_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemHAGroupHAGroupClusterAttribute [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_minimum_threshold(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_minimum_threshold", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_minimum_threshold(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_minimum_threshold", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_sufficient_threshold", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_sufficient_threshold(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_sufficient_threshold", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_threshold(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_threshold", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_threshold(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_threshold", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_value(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_value", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_value(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_value", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_score(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_score", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_score(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_score", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_weight(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_weight", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_weight(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_weight", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] ha_groups
) {
object [] results = this.Invoke("get_description", new object [] {
ha_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
ha_groups}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
string [] ha_groups
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
ha_groups});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
ha_groups}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_pool(
string [] ha_groups
) {
object [] results = this.Invoke("get_pool", new object [] {
ha_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool", new object[] {
ha_groups}, callback, asyncState);
}
public string [] [] Endget_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemHAGroupHAGroupPoolAttribute [] [] get_pool_attribute(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute", new object [] {
ha_groups,
pools});
return ((SystemHAGroupHAGroupPoolAttribute [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public SystemHAGroupHAGroupPoolAttribute [] [] Endget_pool_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemHAGroupHAGroupPoolAttribute [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_minimum_threshold(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_minimum_threshold", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_minimum_threshold(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_minimum_threshold", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_sufficient_threshold", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_sufficient_threshold(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_sufficient_threshold", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_threshold(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_threshold", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_threshold(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_threshold", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_value(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_value", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_value(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_value", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_score(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_score", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_score(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_score", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_weight(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_weight", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_weight(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_weight", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_total_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_total_score(
string [] ha_groups
) {
object [] results = this.Invoke("get_total_score", new object [] {
ha_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_total_score(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_total_score", new object[] {
ha_groups}, callback, asyncState);
}
public long [] Endget_total_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_trunk(
string [] ha_groups
) {
object [] results = this.Invoke("get_trunk", new object [] {
ha_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk", new object[] {
ha_groups}, callback, asyncState);
}
public string [] [] Endget_trunk(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemHAGroupHAGroupTrunkAttribute [] [] get_trunk_attribute(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute", new object [] {
ha_groups,
trunks});
return ((SystemHAGroupHAGroupTrunkAttribute [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public SystemHAGroupHAGroupTrunkAttribute [] [] Endget_trunk_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemHAGroupHAGroupTrunkAttribute [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_minimum_threshold(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_minimum_threshold", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_minimum_threshold(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_minimum_threshold", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_sufficient_threshold", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_sufficient_threshold(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_sufficient_threshold", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_threshold(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_threshold", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_threshold(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_threshold", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_value(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_value", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_value(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_value", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_score(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_score", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_score(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_score", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_weight(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_weight", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_weight(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_weight", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_clusters
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_all_clusters(
string [] ha_groups
) {
this.Invoke("remove_all_clusters", new object [] {
ha_groups});
}
public System.IAsyncResult Beginremove_all_clusters(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_clusters", new object[] {
ha_groups}, callback, asyncState);
}
public void Endremove_all_clusters(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_pools
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_all_pools(
string [] ha_groups
) {
this.Invoke("remove_all_pools", new object [] {
ha_groups});
}
public System.IAsyncResult Beginremove_all_pools(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_pools", new object[] {
ha_groups}, callback, asyncState);
}
public void Endremove_all_pools(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_trunks
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_all_trunks(
string [] ha_groups
) {
this.Invoke("remove_all_trunks", new object [] {
ha_groups});
}
public System.IAsyncResult Beginremove_all_trunks(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_trunks", new object[] {
ha_groups}, callback, asyncState);
}
public void Endremove_all_trunks(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_cluster
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_cluster(
string [] ha_groups,
string [] [] clusters
) {
this.Invoke("remove_cluster", new object [] {
ha_groups,
clusters});
}
public System.IAsyncResult Beginremove_cluster(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_cluster", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public void Endremove_cluster(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_pool(
string [] ha_groups,
string [] [] pools
) {
this.Invoke("remove_pool", new object [] {
ha_groups,
pools});
}
public System.IAsyncResult Beginremove_pool(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_pool", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public void Endremove_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_trunk
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_trunk(
string [] ha_groups,
string [] [] trunks
) {
this.Invoke("remove_trunk", new object [] {
ha_groups,
trunks});
}
public System.IAsyncResult Beginremove_trunk(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_trunk", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public void Endremove_trunk(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_active_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_active_score(
string [] ha_groups,
long [] scores
) {
this.Invoke("set_active_score", new object [] {
ha_groups,
scores});
}
public System.IAsyncResult Beginset_active_score(string [] ha_groups,long [] scores, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_active_score", new object[] {
ha_groups,
scores}, callback, asyncState);
}
public void Endset_active_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute(
string [] ha_groups,
string [] [] clusters,
SystemHAGroupHAGroupClusterAttribute [] [] attributes
) {
this.Invoke("set_cluster_attribute", new object [] {
ha_groups,
clusters,
attributes});
}
public System.IAsyncResult Beginset_cluster_attribute(string [] ha_groups,string [] [] clusters,SystemHAGroupHAGroupClusterAttribute [] [] attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute", new object[] {
ha_groups,
clusters,
attributes}, callback, asyncState);
}
public void Endset_cluster_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute_minimum_threshold(
string [] ha_groups,
string [] [] clusters,
long [] [] thresholds
) {
this.Invoke("set_cluster_attribute_minimum_threshold", new object [] {
ha_groups,
clusters,
thresholds});
}
public System.IAsyncResult Beginset_cluster_attribute_minimum_threshold(string [] ha_groups,string [] [] clusters,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute_minimum_threshold", new object[] {
ha_groups,
clusters,
thresholds}, callback, asyncState);
}
public void Endset_cluster_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] clusters,
long [] [] thresholds
) {
this.Invoke("set_cluster_attribute_sufficient_threshold", new object [] {
ha_groups,
clusters,
thresholds});
}
public System.IAsyncResult Beginset_cluster_attribute_sufficient_threshold(string [] ha_groups,string [] [] clusters,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute_sufficient_threshold", new object[] {
ha_groups,
clusters,
thresholds}, callback, asyncState);
}
public void Endset_cluster_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute_threshold(
string [] ha_groups,
string [] [] clusters,
long [] [] thresholds
) {
this.Invoke("set_cluster_attribute_threshold", new object [] {
ha_groups,
clusters,
thresholds});
}
public System.IAsyncResult Beginset_cluster_attribute_threshold(string [] ha_groups,string [] [] clusters,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute_threshold", new object[] {
ha_groups,
clusters,
thresholds}, callback, asyncState);
}
public void Endset_cluster_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_weight(
string [] ha_groups,
string [] [] clusters,
long [] [] weights
) {
this.Invoke("set_cluster_weight", new object [] {
ha_groups,
clusters,
weights});
}
public System.IAsyncResult Beginset_cluster_weight(string [] ha_groups,string [] [] clusters,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_weight", new object[] {
ha_groups,
clusters,
weights}, callback, asyncState);
}
public void Endset_cluster_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_description(
string [] ha_groups,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
ha_groups,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] ha_groups,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
ha_groups,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_enabled_state(
string [] ha_groups,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
ha_groups,
states});
}
public System.IAsyncResult Beginset_enabled_state(string [] ha_groups,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
ha_groups,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute(
string [] ha_groups,
string [] [] pools,
SystemHAGroupHAGroupPoolAttribute [] [] attributes
) {
this.Invoke("set_pool_attribute", new object [] {
ha_groups,
pools,
attributes});
}
public System.IAsyncResult Beginset_pool_attribute(string [] ha_groups,string [] [] pools,SystemHAGroupHAGroupPoolAttribute [] [] attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute", new object[] {
ha_groups,
pools,
attributes}, callback, asyncState);
}
public void Endset_pool_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute_minimum_threshold(
string [] ha_groups,
string [] [] pools,
long [] [] thresholds
) {
this.Invoke("set_pool_attribute_minimum_threshold", new object [] {
ha_groups,
pools,
thresholds});
}
public System.IAsyncResult Beginset_pool_attribute_minimum_threshold(string [] ha_groups,string [] [] pools,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute_minimum_threshold", new object[] {
ha_groups,
pools,
thresholds}, callback, asyncState);
}
public void Endset_pool_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] pools,
long [] [] thresholds
) {
this.Invoke("set_pool_attribute_sufficient_threshold", new object [] {
ha_groups,
pools,
thresholds});
}
public System.IAsyncResult Beginset_pool_attribute_sufficient_threshold(string [] ha_groups,string [] [] pools,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute_sufficient_threshold", new object[] {
ha_groups,
pools,
thresholds}, callback, asyncState);
}
public void Endset_pool_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute_threshold(
string [] ha_groups,
string [] [] pools,
long [] [] thresholds
) {
this.Invoke("set_pool_attribute_threshold", new object [] {
ha_groups,
pools,
thresholds});
}
public System.IAsyncResult Beginset_pool_attribute_threshold(string [] ha_groups,string [] [] pools,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute_threshold", new object[] {
ha_groups,
pools,
thresholds}, callback, asyncState);
}
public void Endset_pool_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_weight(
string [] ha_groups,
string [] [] pools,
long [] [] weights
) {
this.Invoke("set_pool_weight", new object [] {
ha_groups,
pools,
weights});
}
public System.IAsyncResult Beginset_pool_weight(string [] ha_groups,string [] [] pools,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_weight", new object[] {
ha_groups,
pools,
weights}, callback, asyncState);
}
public void Endset_pool_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute(
string [] ha_groups,
string [] [] trunks,
SystemHAGroupHAGroupTrunkAttribute [] [] attributes
) {
this.Invoke("set_trunk_attribute", new object [] {
ha_groups,
trunks,
attributes});
}
public System.IAsyncResult Beginset_trunk_attribute(string [] ha_groups,string [] [] trunks,SystemHAGroupHAGroupTrunkAttribute [] [] attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute", new object[] {
ha_groups,
trunks,
attributes}, callback, asyncState);
}
public void Endset_trunk_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute_minimum_threshold(
string [] ha_groups,
string [] [] trunks,
long [] [] thresholds
) {
this.Invoke("set_trunk_attribute_minimum_threshold", new object [] {
ha_groups,
trunks,
thresholds});
}
public System.IAsyncResult Beginset_trunk_attribute_minimum_threshold(string [] ha_groups,string [] [] trunks,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute_minimum_threshold", new object[] {
ha_groups,
trunks,
thresholds}, callback, asyncState);
}
public void Endset_trunk_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] trunks,
long [] [] thresholds
) {
this.Invoke("set_trunk_attribute_sufficient_threshold", new object [] {
ha_groups,
trunks,
thresholds});
}
public System.IAsyncResult Beginset_trunk_attribute_sufficient_threshold(string [] ha_groups,string [] [] trunks,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute_sufficient_threshold", new object[] {
ha_groups,
trunks,
thresholds}, callback, asyncState);
}
public void Endset_trunk_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute_threshold(
string [] ha_groups,
string [] [] trunks,
long [] [] thresholds
) {
this.Invoke("set_trunk_attribute_threshold", new object [] {
ha_groups,
trunks,
thresholds});
}
public System.IAsyncResult Beginset_trunk_attribute_threshold(string [] ha_groups,string [] [] trunks,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute_threshold", new object[] {
ha_groups,
trunks,
thresholds}, callback, asyncState);
}
public void Endset_trunk_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_weight(
string [] ha_groups,
string [] [] trunks,
long [] [] weights
) {
this.Invoke("set_trunk_weight", new object [] {
ha_groups,
trunks,
weights});
}
public System.IAsyncResult Beginset_trunk_weight(string [] ha_groups,string [] [] trunks,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_weight", new object[] {
ha_groups,
trunks,
weights}, callback, asyncState);
}
public void Endset_trunk_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.HAGroup.HAGroupClusterAttribute", Namespace = "urn:iControl")]
public enum SystemHAGroupHAGroupClusterAttribute
{
HA_GROUP_CLUSTER_UNKNOWN,
HA_GROUP_CLUSTER_PERCENT_MEMBERS_UP,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.HAGroup.HAGroupPoolAttribute", Namespace = "urn:iControl")]
public enum SystemHAGroupHAGroupPoolAttribute
{
HA_GROUP_POOL_UNKNOWN,
HA_GROUP_POOL_PERCENT_MEMBERS_UP,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.HAGroup.HAGroupTrunkAttribute", Namespace = "urn:iControl")]
public enum SystemHAGroupHAGroupTrunkAttribute
{
HA_GROUP_TRUNK_UNKNOWN,
HA_GROUP_TRUNK_PERCENT_MEMBERS_UP,
}
//=======================================================================
// Structs
//=======================================================================
}
| mit |
dejanr77/demo_blog | app/LaravelFilemanager/controllers/DownloadController.php | 473 | <?php
namespace App\LaravelFilemanager\controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
/**
* Class DownloadController
* @package Unisharp\Laravelfilemanager\controllers
*/
class DownloadController extends LfmController {
/**
* Download a file
*
* @return mixed
*/
public function getDownload()
{
return Response::download(parent::getPath('directory') . Input::get('file'));
}
}
| mit |
mlaval/optimize-angular-app | app/list/list.module.ts | 465 | import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {NgbPaginationModule, NgbPaginationConfig} from '@ng-bootstrap/ng-bootstrap/pagination/pagination.module';
import {List} from './list';
const routes: Routes = [
{path: '', component: List},
];
@NgModule({
imports: [NgbPaginationModule, RouterModule.forChild(routes)],
declarations: [List],
providers: [NgbPaginationConfig]
})
export class ListModule {} | mit |
midnightLuke/php-units-of-measure-bundle | Tests/Doctrine/Types/AccelerationTypeTest.php | 772 | <?php
/*
* This file is part of the MidnightLukePhpUnitsOfMeasureBundle package.
*
* (c) Luke Bainbridge <http://www.lukebainbridge.ca/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace MidnightLuke\PhpUnitsOfMeasureBundle\Tests\Doctrine\Types;
use MidnightLuke\PhpUnitsOfMeasureBundle\Doctrine\Types;
use PhpUnitsOfMeasure\PhysicalQuantity;
class AccelerationTypeTest extends AbstractTypeTest
{
public function getTypeName()
{
return 'acceleration';
}
public function getTypeClass()
{
return Types\AccelerationType::class;
}
public function getUnitClass()
{
return PhysicalQuantity\Acceleration::class;
}
}
| mit |
thw17/NextGenUtilities | fasta_utils/Reduce_contigs.py | 6461 | from __future__ import print_function
import argparse
from itertools import groupby
import subprocess
import sys
def main():
""" Main Function """
args = parse_args()
if args.wrap_length != "None":
wrap = int(args.wrap_length)
else:
wrap = None
# Check bioawk install
bioawk = args.bioawk
a = subprocess.call(
"{} -c help".format(bioawk), shell=True)
# The -c help command returns 1 as an exit code
if a != 1:
print("Error. Check bioawk installation and path")
sys.exit(1)
if args.mode == "LENGTH":
# Create temp fasta for large enough contigs/scaffolds
a = subprocess.call(
"""{} -c fastx '{{ if (length($seq) > {} ) print ">"$name"\n"print $seq}}' {} > tmp_pass.fa""".format(
bioawk, int(args.size) - 1, args.fasta), shell=True)
# Create a file of just sequence for too short scaffolds/contigs
a = subprocess.call(
"""{} -c fastx '{{ if (length($seq) < {} ) print $seq}}' {} > tmp_toconcat_seq.txt""".format(
bioawk, args.size, args.fasta), shell=True)
# Create a file of just sequence names for too short scaffolds/contigs
a = subprocess.call(
"""{} -c fastx '{{ if (length($seq) < {} ) print $name}}' {} > tmp_toconcat_name.txt""".format(
bioawk, args.size, args.fasta), shell=True)
elif args.mode == "ID":
# Code to read id text file
with open(args.ids, "r") as f:
id_list = [x.strip() for x in f]
while "" in id_list:
id_list.remove("")
# base code on this kind of a line (this example prints yes if a sequence name is either chr1 or chr4):
# bioawk -c fastx '{split("chr1 chr4",a, " "); for (i in a) value[a[i]]; if ($name in value == 1) print "Yes" }' test.fa
# Create temp fasta for large enough contigs/scaffolds
a = subprocess.call(
"""{} -c fastx '{{split("{}", a, " "); for (i in a) value[a[i]]; if ($name in value == 1) print ">"$name\"\\n\"$seq}}' {} > tmp_pass.fa""".format(
bioawk, " ".join(id_list), args.fasta), shell=True)
print(
"""{} -c fastx '{{split("{}", a, " "); for (i in a) value[a[i]]; if ($name in value == 1) print ">"$name\"\\n\"print $seq}}' {} > tmp_pass.fa""".format(
bioawk, " ".join(id_list), args.fasta))
# Create a file of just sequence for too short scaffolds/contigs
a = subprocess.call(
"""{} -c fastx '{{split("{}", a, " "); for (i in a) value[a[i]]; if ($name in value == 0) print $seq}}' {} > tmp_toconcat_seq.txt""".format(
bioawk, " ".join(id_list), args.fasta), shell=True)
# Create a file of just sequence names for too short scaffolds/contigs
a = subprocess.call(
"""{} -c fastx '{{split("{}", a, " "); for (i in a) value[a[i]]; if ($name in value == 0) print $name}}' {} > tmp_toconcat_name.txt""".format(
bioawk, " ".join(id_list), args.fasta), shell=True)
else:
print("Please set --mode to either ID or LENGTH")
sys.exit(1)
# Concatenate too short sequences
with open("tmp_toconcat_seq.txt", "r") as f:
sequence = ""
lengths = []
for line in f:
sequence += line.rstrip()
lengths.append(len(line))
# Collect sequence names
with open("tmp_toconcat_name.txt", "r") as f:
names = []
for line in f:
names.append(line)
# Write fasta of supercontig
length = len(sequence)
with open("tmp_supercontig.fa", "w") as f:
f.write(">{}\n".format(args.supercontig_name))
if wrap is not None:
for i in range(0, length, wrap):
f.write(sequence[i: i + wrap] + "\n")
else:
f.write(sequence + "\n")
# Write bed containing coordinates of contigs in the supercontig
with open(args.output_bed, "w") as f:
start = 0
stop = 0
for idx, i in enumerate(lengths):
stop += i
f.write("{}\t{}\t{}\t{}".format(
args.supercontig_name, start, stop, names[idx]))
start = stop
# Ensure large enough fasta sequences are wrapped correctly (as bioawk
# doesn't wrap) and in a way consistent with the supercontig record
with open("tmp_pass.fa", "r") as f:
with open("tmp_pass.WRAPPED.fa", "w") as o:
# the following text for parsing fasta based on Brent Pedersen's
# response here: https://www.biostars.org/p/710/
faiter = (x[1] for x in groupby(f, lambda line: line[0] == ">"))
for header in faiter:
# drop the ">"
header = header.next()[1:].strip()
# join all sequence lines to one.
seq = "".join(s.strip() for s in faiter.next())
# Write output to file using same wrapping as supercontig above
o.write(">{}\n".format(header))
length = len(seq)
if wrap is not None:
for i in range(0, length, wrap):
o.write(seq[i: i + wrap] + "\n")
else:
o.write(seq + "\n")
# Concatenate fasta of sequences large enough with supercontig fasta
with open(args.output_fasta, "w") as f:
a = subprocess.call(
["cat", "tmp_pass.WRAPPED.fa", "tmp_supercontig.fa"],
stdout=f)
def parse_args():
""" Parse command line arguments """
parser = argparse.ArgumentParser(
description="Concatenates all contigs smaller than a given length")
parser.add_argument(
"--fasta", required=True,
help="Fasta reference file to be processed")
parser.add_argument(
"--mode", required=True, choices=["LENGTH", "ID"],
help="Mode to determine which contigs to leave intact, and which to "
"combine. Two options: LENGTH and ID. LENGTH will filter by contig "
"length (via --size flag). ID will leave intact contigs with IDs "
"included in a .txt file (via --ids flag)")
parser.add_argument(
"--output_fasta", required=True,
help="Output file to write new reference")
parser.add_argument(
"--output_bed", required=True,
help="Output bed file for annotations of new fasta")
parser.add_argument(
"--ids", default=None,
help="Text file listing contig ids to leave as-is in a single column, one "
"per row. All other contig ids will be combined into the supercontig.")
parser.add_argument(
"--size", type=int, default=1000,
help="Minimum length for contig/scaffold to be included. Default = 1000")
parser.add_argument(
"--supercontig_name", default="chrUn",
help="The name of the supercontig created from the filtered contigs. "
"Default is chrUn")
parser.add_argument(
"--wrap_length", default=50,
help="Provide either intger length of each line to use "
"when writing sequence data or None to prevent wrapping and write "
"sequence on a single line. Default = 50.")
parser.add_argument(
"--bioawk", default="bioawk",
help="Path to bioawk. Default is 'bioawk'")
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
| mit |
klump/neindb | app/models/component/cpu.rb | 501 | class Component::Cpu < Component
store_accessor :properties, :speed_mhz, :cores, :threads_per_core, :extensions
validates :speed_mhz, presence: true, numericality: true
validates :cores, presence: true, numericality: {only_integer: true}
validates :threads_per_core, presence: true, numericality: {only_integer: true}
after_initialize :ensure_default_values
private
def ensure_default_values
write_store_attribute(:properties, :extensions, []) unless extensions
end
end
| mit |
Raul-diffindo/Django-Matcher | setup.py | 1506 | from distutils.core import setup
import os
def get_packages(package):
"""
Return root package & all sub-packages.
"""
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, '__init__.py'))]
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
filepaths = []
for base, filenames in walk:
filepaths.extend([os.path.join(base, filename)
for filename in filenames])
return {package: filepaths}
setup(
name='Django&jqGrid',
version='0.1',
packages=get_packages('Django-jqGrid'),
package_data=get_package_data('Django-jqGrid'),
description='Matching search between objects (model objects or object dictionaries).',
author='Raul Gonzalez',
author_email='[email protected]',
license='Creative Commons Attribution-Noncommercial-Share Alike license',
long_description='https://github.com/Raul-diffindo/Django-Matcher',
install_requires=[],
classifiers=[
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP'
]
) | mit |
surenm/cookbooks | dw/recipes/upgrade_pip.rb | 299 | Chef::Log.info("Updating pip to the latest version")
execute "/usr/bin/pip install -U pip" do
user "root"
only_if { ::File.exists?('/usr/bin/pip')}
action :run
end
execute "/usr/local/bin/pip install -U pip" do
user "root"
only_if { ::File.exists?('/usr/local/bin/pip')}
action :run
end
| mit |
sandeeplinux/testing | app/common/app-directives/dob/dob.directive.js | 2725 | +app.directive('dob', function () {
return {
restrict: 'EA',
scope: {
birthDate: '=birthDate'
},
templateUrl: 'common/app-directives/dob/dob.view.html',
controller: function ($scope) {
$scope.days = [];
$scope.dob = {};
$scope.dob.year = '';
$scope.dob.month = '';
$scope.dob.day = '';
$scope.months = [
{'id': 1, 'name': 'January'},
{'id': 2, 'name': 'February'},
{'id': 3, 'name': 'March'},
{'id': 4, 'name': 'April'},
{'id': 5, 'name': 'May'},
{'id': 6, 'name': 'June'},
{'id': 7, 'name': 'July'},
{'id': 8, 'name': 'August'},
{'id': 9, 'name': 'September'},
{'id': 10, 'name': 'October'},
{'id': 11, 'name': 'November'},
{'id': 12, 'name': 'December'}
];
$scope.getYears = function (startYear) {
var currentYear = new Date().getFullYear(), years = [];
startYear = startYear || currentYear - 130;
while (startYear <= currentYear) {
years.push(startYear++);
}
return years.reverse();
};
function setDays (numDays) {
var days = [], i = 1;
while (i <= numDays) {
days.push(i++);
}
$scope.days = days;
}
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
function setDOBFormate(month, day, year) {
month = (month)? month : 0;
day = (day)? day : 0;
year = (year)? year : 0;
return month + "/" + day + "/" + year;
}
setDays(30);
$scope.$watchGroup(['dob.month', 'dob.day', 'dob.year'], function (newValues, oldValues, scope) {
scope.birthDate = setDOBFormate(scope.dob.month, scope.dob.day, scope.dob.year);
if(scope.dob.month){
setDays(daysInMonth(scope.dob.month, scope.dob.year));
}
});
$scope.$watch('birthDate', function (newValue, oldValue,scope) {
if(newValue){
var val = newValue.split("/");
if(val.length > 1){
if(!isNaN(val[0]) && !isNaN(val[1]) && !isNaN(val[2])){
scope.dob.month = parseInt(val[0]);
scope.dob.day = parseInt(val[1]);
scope.dob.year = parseInt(val[2]);
}
} else {
scope.dob.month = new Date(scope.birthDate).getMonth() + 1;
scope.dob.day = new Date(scope.birthDate).getDate();
scope.dob.year = new Date(scope.birthDate).getFullYear();
}
}
});
}
};
});
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.