code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
import requests
import csv
from configparser import ConfigParser
config = ConfigParser()
config.read("config.cfg")
token = config.get("auth", "token")
domain = config.get("instance", "domain")
headers = {"Authorization" : "Bearer %s" % token}
source_course_id = 311693
csv_file = ""
payload = {'migration_type': 'course_copy_importer', 'settings[source_course_id]': source_course_id}
with open(csv_file, 'rb') as courses:
coursesreader = csv.reader(courses)
for course in coursesreader:
uri = domain + "/api/v1/courses/sis_course_id:%s/content_migrations" % course
r = requests.post(uri, headers=headers,data=payload)
print r.status_code + " " + course | tylerclair/canvas_admin_scripts | course_copy_csv.py | Python | mit | 684 |
<?php
/**
* Created by HKM Corporation.
* User: Hesk
* Date: 14年8月28日
* Time: 上午11:37
*/
abstract class SingleBase
{
protected $db, $table, $stock_operation, $app_comment;
protected $post_id, $lang, $content, $cate_list;
public function __construct($ID)
{
global $wpdb;
$this->post_id = (int)$ID;
if (isset($_GET['lang']))
$this->lang = $_GET['lang'];
if (!$this->isType(get_post_type($this->post_id))) throw new Exception("post type check failed. this object_id is not valid for this post type or this id is not exist", 1047);
if (get_post_status($this->post_id) != 'publish') throw new Exception("the object id is not ready", 1048);
$this->db = $wpdb;
$this->beforeQuery();
$this->content = $this->queryobject();
}
abstract protected function beforeQuery();
public function __destruct()
{
$this->db = NULL;
$this->content = NULL;
$this->stock_operation = NULL;
$this->app_comment = NULL;
}
protected function isType($type)
{
return true;
}
abstract protected function queryobject();
protected function get_terms($tax)
{
$terms = $tax == "category" ? get_the_category($this->post_id) : get_the_terms($this->post_id, $tax);
//resposne in david request for android development
return !$terms ? array() : $terms;
}
protected function get_terms_images($taxonomy_id)
{
$array_terms = $taxonomy_id == "category" ? get_the_category($this->post_id) : get_the_terms($this->post_id, $taxonomy_id);
$this->cate_list = array();
foreach ($array_terms as $cat) :
$this->cate_list[] = $this->cat_loop($cat, true, strtolower($taxonomy_id) == "category", $taxonomy_id);
endforeach;
return count($this->cate_list) == 0 ? array() : $this->cate_list;
}
protected $filter_keys_setting = 0;
/**
* cate data loop
*
* @param $cat
* @param bool $image
* @param bool $isCate
* @param $taxonomy_id
* @throws Exception
* @return array
*/
private function cat_loop($cat, $image = false, $isCate = false, $taxonomy_id)
{
$image_url = "";
if ($image && !function_exists('z_taxonomy_image_url')) {
throw new Exception("image module not found.");
}
if ($isCate) {
$desc = category_description($cat->term_id);
} else {
$text = trim(wp_kses(term_description($cat->term_id, $taxonomy_id), array()));
$desc = str_replace('\n', "", $text);
}
if ($this->filter_keys_setting === 1) {
return array(
"name" => trim($cat->name),
"countrycode" => $desc
);
} else {
if ($image) {
return array(
/* "unpress" => z_taxonomy_image_url($cat->term_id),
"press" => z_taxonomy_image_url($cat->term_id, 2),
"unpress_s" => z_taxonomy_image_url($cat->term_id, 3),
"press_s" => z_taxonomy_image_url($cat->term_id, 4),*/
"name" => trim($cat->name),
"description" => $desc,
"id" => intval($cat->term_id),
);
} else {
return array(
"name" => trim($cat->name),
"description" => $desc,
"id" => intval($cat->term_id),
);
}
}
}
/**
* wordpress: wp_get_attachment_image_src
* @param $key
* @return mixed
*/
protected function get_product_image($key)
{
$list = get_post_meta($this->post_id, $key, true);
$optionpost = wp_get_attachment_image_src($list, 'large');
return $optionpost[0];
}
protected function get_image_series($key)
{
$list = get_post_meta($this->post_id, $key, false);
$arr = array();
if (count($list) > 0)
foreach ($list[0] as $id) {
$image = wp_get_attachment_image_src($id, 'large');
$arr[] = array(
"ID" => $id,
"url" => $image[0],
);
}
return $arr;
}
protected function get_structure()
{
return json_decode(stripslashes(get_post_meta($this->post_id, "ext_v2", true)), true);
}
} | jjhesk/v-server-sdk-bank | core/reuseable/SingleBase.php | PHP | mit | 4,519 |
package equus.webstack.application;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
@Slf4j
public class JettyStarter {
private final int port = 9010;
private final String contextPath = "/java-web-stack/";
private final String apiPath = "api";
@Setter
private boolean resourceEnable = true;
private String resourceBase = "WebContent";
public static void main(String[] args) {
JettyStarter jetty = new JettyStarter();
if (args.length > 0) {
jetty.resourceBase = args[0];
}
jetty.start();
}
@SneakyThrows
public void start() {
Server server = startServer();
server.join();
}
@SneakyThrows
public Server startServer() {
val server = createServer();
val shutdownHook = new Thread(() -> {
try {
server.stop();
} catch (Throwable t) {
log.error("unknown error occurred.", t);
}
}, "shutdown-hook");
Runtime.getRuntime().addShutdownHook(shutdownHook);
server.start();
if (resourceEnable) {
System.out.println("URL " + getBaseURI());
}
System.out.println("API URL " + getAPIBaseURI());
return server;
}
public URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(port).path(contextPath).build();
}
public URI getAPIBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(port).path(contextPath).path(apiPath).build();
}
private Server createServer() {
val server = new Server(port);
val context = new WebAppContext();
context.setServer(server);
context.setContextPath(contextPath);
context.setDescriptor("WebContent/WEB-INF/web.xml");
context.setParentLoaderPriority(true);
if (resourceEnable) {
context.setResourceBase(resourceBase);
}
server.setHandler(context);
return server;
}
}
| equus52/java-web-stack | src/test/java/equus/webstack/application/JettyStarter.java | Java | mit | 2,013 |
package tweaking.concurrency.reetrantLockExample;
public class MainClass {
public static void main(final String[] args) {
final ThreadSafeArrayList<String> threadSafeList = new ThreadSafeArrayList<>();
final ListAdderThread threadA = new ListAdderThread("threadA", threadSafeList);
final ListAdderThread threadB = new ListAdderThread("threadB", threadSafeList);
final ListAdderThread threadC = new ListAdderThread("threadC", threadSafeList);
threadA.start();
threadB.start();
threadC.start();
}
}
| liggetm/Tweaking | TweakingGitHub/src/tweaking/concurrency/reetrantLockExample/MainClass.java | Java | mit | 594 |
# frozen_string_literal: true
module M3u8
# DateRangeItem represents a #EXT-X-DATERANGE tag
class DateRangeItem
include M3u8
attr_accessor :id, :class_name, :start_date, :end_date, :duration,
:planned_duration, :scte35_cmd, :scte35_out, :scte35_in,
:end_on_next, :client_attributes
def initialize(options = {})
options.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def parse(text)
attributes = parse_attributes(text)
@id = attributes['ID']
@class_name = attributes['CLASS']
@start_date = attributes['START-DATE']
@end_date = attributes['END-DATE']
@duration = parse_float(attributes['DURATION'])
@planned_duration = parse_float(attributes['PLANNED-DURATION'])
@scte35_cmd = attributes['SCTE35-CMD']
@scte35_out = attributes['SCTE35-OUT']
@scte35_in = attributes['SCTE35-IN']
@end_on_next = attributes.key?('END-ON-NEXT') ? true : false
@client_attributes = parse_client_attributes(attributes)
end
def to_s
"#EXT-X-DATERANGE:#{formatted_attributes}"
end
private
def formatted_attributes
[%(ID="#{id}"),
class_name_format,
%(START-DATE="#{start_date}"),
end_date_format,
duration_format,
planned_duration_format,
client_attributes_format,
scte35_cmd_format,
scte35_out_format,
scte35_in_format,
end_on_next_format].compact.join(',')
end
def class_name_format
return if class_name.nil?
%(CLASS="#{class_name}")
end
def end_date_format
return if end_date.nil?
%(END-DATE="#{end_date}")
end
def duration_format
return if duration.nil?
"DURATION=#{duration}"
end
def planned_duration_format
return if planned_duration.nil?
"PLANNED-DURATION=#{planned_duration}"
end
def client_attributes_format
return if client_attributes.nil?
client_attributes.map do |attribute|
value = attribute.last
value_format = decimal?(value) ? value : %("#{value}")
"#{attribute.first}=#{value_format}"
end
end
def decimal?(value)
return true if value =~ /\A\d+\Z/
begin
return true if Float(value)
rescue
false
end
end
def scte35_cmd_format
return if scte35_cmd.nil?
"SCTE35-CMD=#{scte35_cmd}"
end
def scte35_out_format
return if scte35_out.nil?
"SCTE35-OUT=#{scte35_out}"
end
def scte35_in_format
return if scte35_in.nil?
"SCTE35-IN=#{scte35_in}"
end
def end_on_next_format
return unless end_on_next
'END-ON-NEXT=YES'
end
def parse_client_attributes(attributes)
attributes.select { |key| key.start_with?('X-') }
end
end
end
| sethdeckard/m3u8 | lib/m3u8/date_range_item.rb | Ruby | mit | 2,868 |
using System;
using System.Collections;
using System.Windows.Media;
using Microsoft.Win32;
using MS.Win32;
namespace System.Windows
{
/// <summary>
/// Contains properties that are queries into the system's various colors.
/// </summary>
public static class SystemColors
{
#region Colors
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ActiveBorderColor
{
get
{
return GetSystemColor(CacheSlot.ActiveBorder);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ActiveCaptionColor
{
get
{
return GetSystemColor(CacheSlot.ActiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ActiveCaptionTextColor
{
get
{
return GetSystemColor(CacheSlot.ActiveCaptionText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color AppWorkspaceColor
{
get
{
return GetSystemColor(CacheSlot.AppWorkspace);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ControlColor
{
get
{
return GetSystemColor(CacheSlot.Control);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ControlDarkColor
{
get
{
return GetSystemColor(CacheSlot.ControlDark);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ControlDarkDarkColor
{
get
{
return GetSystemColor(CacheSlot.ControlDarkDark);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ControlLightColor
{
get
{
return GetSystemColor(CacheSlot.ControlLight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ControlLightLightColor
{
get
{
return GetSystemColor(CacheSlot.ControlLightLight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ControlTextColor
{
get
{
return GetSystemColor(CacheSlot.ControlText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color DesktopColor
{
get
{
return GetSystemColor(CacheSlot.Desktop);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color GradientActiveCaptionColor
{
get
{
return GetSystemColor(CacheSlot.GradientActiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color GradientInactiveCaptionColor
{
get
{
return GetSystemColor(CacheSlot.GradientInactiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color GrayTextColor
{
get
{
return GetSystemColor(CacheSlot.GrayText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color HighlightColor
{
get
{
return GetSystemColor(CacheSlot.Highlight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color HighlightTextColor
{
get
{
return GetSystemColor(CacheSlot.HighlightText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color HotTrackColor
{
get
{
return GetSystemColor(CacheSlot.HotTrack);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color InactiveBorderColor
{
get
{
return GetSystemColor(CacheSlot.InactiveBorder);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color InactiveCaptionColor
{
get
{
return GetSystemColor(CacheSlot.InactiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color InactiveCaptionTextColor
{
get
{
return GetSystemColor(CacheSlot.InactiveCaptionText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color InfoColor
{
get
{
return GetSystemColor(CacheSlot.Info);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color InfoTextColor
{
get
{
return GetSystemColor(CacheSlot.InfoText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color MenuColor
{
get
{
return GetSystemColor(CacheSlot.Menu);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color MenuBarColor
{
get
{
return GetSystemColor(CacheSlot.MenuBar);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color MenuHighlightColor
{
get
{
return GetSystemColor(CacheSlot.MenuHighlight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color MenuTextColor
{
get
{
return GetSystemColor(CacheSlot.MenuText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color ScrollBarColor
{
get
{
return GetSystemColor(CacheSlot.ScrollBar);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color WindowColor
{
get
{
return GetSystemColor(CacheSlot.Window);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color WindowFrameColor
{
get
{
return GetSystemColor(CacheSlot.WindowFrame);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static Color WindowTextColor
{
get
{
return GetSystemColor(CacheSlot.WindowText);
}
}
#endregion
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static SystemResourceKey CreateInstance(SystemResourceKeyID KeyId)
{
return new SystemResourceKey(KeyId);
}
#region Color Keys
/// <summary>
/// ActiveBorderColor System Resource Key
/// </summary>
public static ResourceKey ActiveBorderColorKey
{
get
{
if (_cacheActiveBorderColor == null)
{
_cacheActiveBorderColor = CreateInstance(SystemResourceKeyID.ActiveBorderColor);
}
return _cacheActiveBorderColor;
}
}
/// <summary>
/// ActiveCaptionColor System Resource Key
/// </summary>
public static ResourceKey ActiveCaptionColorKey
{
get
{
if (_cacheActiveCaptionColor == null)
{
_cacheActiveCaptionColor = CreateInstance(SystemResourceKeyID.ActiveCaptionColor);
}
return _cacheActiveCaptionColor;
}
}
/// <summary>
/// ActiveCaptionTextColor System Resource Key
/// </summary>
public static ResourceKey ActiveCaptionTextColorKey
{
get
{
if (_cacheActiveCaptionTextColor == null)
{
_cacheActiveCaptionTextColor = CreateInstance(SystemResourceKeyID.ActiveCaptionTextColor);
}
return _cacheActiveCaptionTextColor;
}
}
/// <summary>
/// AppWorkspaceColor System Resource Key
/// </summary>
public static ResourceKey AppWorkspaceColorKey
{
get
{
if (_cacheAppWorkspaceColor == null)
{
_cacheAppWorkspaceColor = CreateInstance(SystemResourceKeyID.AppWorkspaceColor);
}
return _cacheAppWorkspaceColor;
}
}
/// <summary>
/// ControlColor System Resource Key
/// </summary>
public static ResourceKey ControlColorKey
{
get
{
if (_cacheControlColor == null)
{
_cacheControlColor = CreateInstance(SystemResourceKeyID.ControlColor);
}
return _cacheControlColor;
}
}
/// <summary>
/// ControlDarkColor System Resource Key
/// </summary>
public static ResourceKey ControlDarkColorKey
{
get
{
if (_cacheControlDarkColor == null)
{
_cacheControlDarkColor = CreateInstance(SystemResourceKeyID.ControlDarkColor);
}
return _cacheControlDarkColor;
}
}
/// <summary>
/// ControlDarkDarkColor System Resource Key
/// </summary>
public static ResourceKey ControlDarkDarkColorKey
{
get
{
if (_cacheControlDarkDarkColor == null)
{
_cacheControlDarkDarkColor = CreateInstance(SystemResourceKeyID.ControlDarkDarkColor);
}
return _cacheControlDarkDarkColor;
}
}
/// <summary>
/// ControlLightColor System Resource Key
/// </summary>
public static ResourceKey ControlLightColorKey
{
get
{
if (_cacheControlLightColor == null)
{
_cacheControlLightColor = CreateInstance(SystemResourceKeyID.ControlLightColor);
}
return _cacheControlLightColor;
}
}
/// <summary>
/// ControlLightLightColor System Resource Key
/// </summary>
public static ResourceKey ControlLightLightColorKey
{
get
{
if (_cacheControlLightLightColor == null)
{
_cacheControlLightLightColor = CreateInstance(SystemResourceKeyID.ControlLightLightColor);
}
return _cacheControlLightLightColor;
}
}
/// <summary>
/// ControlTextColor System Resource Key
/// </summary>
public static ResourceKey ControlTextColorKey
{
get
{
if (_cacheControlTextColor == null)
{
_cacheControlTextColor = CreateInstance(SystemResourceKeyID.ControlTextColor);
}
return _cacheControlTextColor;
}
}
/// <summary>
/// DesktopColor System Resource Key
/// </summary>
public static ResourceKey DesktopColorKey
{
get
{
if (_cacheDesktopColor == null)
{
_cacheDesktopColor = CreateInstance(SystemResourceKeyID.DesktopColor);
}
return _cacheDesktopColor;
}
}
/// <summary>
/// GradientActiveCaptionColor System Resource Key
/// </summary>
public static ResourceKey GradientActiveCaptionColorKey
{
get
{
if (_cacheGradientActiveCaptionColor == null)
{
_cacheGradientActiveCaptionColor = CreateInstance(SystemResourceKeyID.GradientActiveCaptionColor);
}
return _cacheGradientActiveCaptionColor;
}
}
/// <summary>
/// GradientInactiveCaptionColor System Resource Key
/// </summary>
public static ResourceKey GradientInactiveCaptionColorKey
{
get
{
if (_cacheGradientInactiveCaptionColor == null)
{
_cacheGradientInactiveCaptionColor = CreateInstance(SystemResourceKeyID.GradientInactiveCaptionColor);
}
return _cacheGradientInactiveCaptionColor;
}
}
/// <summary>
/// GrayTextColor System Resource Key
/// </summary>
public static ResourceKey GrayTextColorKey
{
get
{
if (_cacheGrayTextColor == null)
{
_cacheGrayTextColor = CreateInstance(SystemResourceKeyID.GrayTextColor);
}
return _cacheGrayTextColor;
}
}
/// <summary>
/// HighlightColor System Resource Key
/// </summary>
public static ResourceKey HighlightColorKey
{
get
{
if (_cacheHighlightColor == null)
{
_cacheHighlightColor = CreateInstance(SystemResourceKeyID.HighlightColor);
}
return _cacheHighlightColor;
}
}
/// <summary>
/// HighlightTextColor System Resource Key
/// </summary>
public static ResourceKey HighlightTextColorKey
{
get
{
if (_cacheHighlightTextColor == null)
{
_cacheHighlightTextColor = CreateInstance(SystemResourceKeyID.HighlightTextColor);
}
return _cacheHighlightTextColor;
}
}
/// <summary>
/// HotTrackColor System Resource Key
/// </summary>
public static ResourceKey HotTrackColorKey
{
get
{
if (_cacheHotTrackColor == null)
{
_cacheHotTrackColor = CreateInstance(SystemResourceKeyID.HotTrackColor);
}
return _cacheHotTrackColor;
}
}
/// <summary>
/// InactiveBorderColor System Resource Key
/// </summary>
public static ResourceKey InactiveBorderColorKey
{
get
{
if (_cacheInactiveBorderColor == null)
{
_cacheInactiveBorderColor = CreateInstance(SystemResourceKeyID.InactiveBorderColor);
}
return _cacheInactiveBorderColor;
}
}
/// <summary>
/// InactiveCaptionColor System Resource Key
/// </summary>
public static ResourceKey InactiveCaptionColorKey
{
get
{
if (_cacheInactiveCaptionColor == null)
{
_cacheInactiveCaptionColor = CreateInstance(SystemResourceKeyID.InactiveCaptionColor);
}
return _cacheInactiveCaptionColor;
}
}
/// <summary>
/// InactiveCaptionTextColor System Resource Key
/// </summary>
public static ResourceKey InactiveCaptionTextColorKey
{
get
{
if (_cacheInactiveCaptionTextColor == null)
{
_cacheInactiveCaptionTextColor = CreateInstance(SystemResourceKeyID.InactiveCaptionTextColor);
}
return _cacheInactiveCaptionTextColor;
}
}
/// <summary>
/// InfoColor System Resource Key
/// </summary>
public static ResourceKey InfoColorKey
{
get
{
if (_cacheInfoColor == null)
{
_cacheInfoColor = CreateInstance(SystemResourceKeyID.InfoColor);
}
return _cacheInfoColor;
}
}
/// <summary>
/// InfoTextColor System Resource Key
/// </summary>
public static ResourceKey InfoTextColorKey
{
get
{
if (_cacheInfoTextColor == null)
{
_cacheInfoTextColor = CreateInstance(SystemResourceKeyID.InfoTextColor);
}
return _cacheInfoTextColor;
}
}
/// <summary>
/// MenuColor System Resource Key
/// </summary>
public static ResourceKey MenuColorKey
{
get
{
if (_cacheMenuColor == null)
{
_cacheMenuColor = CreateInstance(SystemResourceKeyID.MenuColor);
}
return _cacheMenuColor;
}
}
/// <summary>
/// MenuBarColor System Resource Key
/// </summary>
public static ResourceKey MenuBarColorKey
{
get
{
if (_cacheMenuBarColor == null)
{
_cacheMenuBarColor = CreateInstance(SystemResourceKeyID.MenuBarColor);
}
return _cacheMenuBarColor;
}
}
/// <summary>
/// MenuHighlightColor System Resource Key
/// </summary>
public static ResourceKey MenuHighlightColorKey
{
get
{
if (_cacheMenuHighlightColor == null)
{
_cacheMenuHighlightColor = CreateInstance(SystemResourceKeyID.MenuHighlightColor);
}
return _cacheMenuHighlightColor;
}
}
/// <summary>
/// MenuTextColor System Resource Key
/// </summary>
public static ResourceKey MenuTextColorKey
{
get
{
if (_cacheMenuTextColor == null)
{
_cacheMenuTextColor = CreateInstance(SystemResourceKeyID.MenuTextColor);
}
return _cacheMenuTextColor;
}
}
/// <summary>
/// ScrollBarColor System Resource Key
/// </summary>
public static ResourceKey ScrollBarColorKey
{
get
{
if (_cacheScrollBarColor == null)
{
_cacheScrollBarColor = CreateInstance(SystemResourceKeyID.ScrollBarColor);
}
return _cacheScrollBarColor;
}
}
/// <summary>
/// WindowColor System Resource Key
/// </summary>
public static ResourceKey WindowColorKey
{
get
{
if (_cacheWindowColor == null)
{
_cacheWindowColor = CreateInstance(SystemResourceKeyID.WindowColor);
}
return _cacheWindowColor;
}
}
/// <summary>
/// WindowFrameColor System Resource Key
/// </summary>
public static ResourceKey WindowFrameColorKey
{
get
{
if (_cacheWindowFrameColor == null)
{
_cacheWindowFrameColor = CreateInstance(SystemResourceKeyID.WindowFrameColor);
}
return _cacheWindowFrameColor;
}
}
/// <summary>
/// WindowTextColor System Resource Key
/// </summary>
public static ResourceKey WindowTextColorKey
{
get
{
if (_cacheWindowTextColor == null)
{
_cacheWindowTextColor = CreateInstance(SystemResourceKeyID.WindowTextColor);
}
return _cacheWindowTextColor;
}
}
#endregion
#region Brushes
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ActiveBorderBrush
{
get
{
return MakeBrush(CacheSlot.ActiveBorder);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ActiveCaptionBrush
{
get
{
return MakeBrush(CacheSlot.ActiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ActiveCaptionTextBrush
{
get
{
return MakeBrush(CacheSlot.ActiveCaptionText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush AppWorkspaceBrush
{
get
{
return MakeBrush(CacheSlot.AppWorkspace);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ControlBrush
{
get
{
return MakeBrush(CacheSlot.Control);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ControlDarkBrush
{
get
{
return MakeBrush(CacheSlot.ControlDark);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ControlDarkDarkBrush
{
get
{
return MakeBrush(CacheSlot.ControlDarkDark);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ControlLightBrush
{
get
{
return MakeBrush(CacheSlot.ControlLight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ControlLightLightBrush
{
get
{
return MakeBrush(CacheSlot.ControlLightLight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ControlTextBrush
{
get
{
return MakeBrush(CacheSlot.ControlText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush DesktopBrush
{
get
{
return MakeBrush(CacheSlot.Desktop);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush GradientActiveCaptionBrush
{
get
{
return MakeBrush(CacheSlot.GradientActiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush GradientInactiveCaptionBrush
{
get
{
return MakeBrush(CacheSlot.GradientInactiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush GrayTextBrush
{
get
{
return MakeBrush(CacheSlot.GrayText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush HighlightBrush
{
get
{
return MakeBrush(CacheSlot.Highlight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush HighlightTextBrush
{
get
{
return MakeBrush(CacheSlot.HighlightText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush HotTrackBrush
{
get
{
return MakeBrush(CacheSlot.HotTrack);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush InactiveBorderBrush
{
get
{
return MakeBrush(CacheSlot.InactiveBorder);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush InactiveCaptionBrush
{
get
{
return MakeBrush(CacheSlot.InactiveCaption);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush InactiveCaptionTextBrush
{
get
{
return MakeBrush(CacheSlot.InactiveCaptionText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush InfoBrush
{
get
{
return MakeBrush(CacheSlot.Info);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush InfoTextBrush
{
get
{
return MakeBrush(CacheSlot.InfoText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush MenuBrush
{
get
{
return MakeBrush(CacheSlot.Menu);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush MenuBarBrush
{
get
{
return MakeBrush(CacheSlot.MenuBar);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush MenuHighlightBrush
{
get
{
return MakeBrush(CacheSlot.MenuHighlight);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush MenuTextBrush
{
get
{
return MakeBrush(CacheSlot.MenuText);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush ScrollBarBrush
{
get
{
return MakeBrush(CacheSlot.ScrollBar);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush WindowBrush
{
get
{
return MakeBrush(CacheSlot.Window);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush WindowFrameBrush
{
get
{
return MakeBrush(CacheSlot.WindowFrame);
}
}
/// <summary>
/// System color of the same name.
/// </summary>
public static SolidColorBrush WindowTextBrush
{
get
{
return MakeBrush(CacheSlot.WindowText);
}
}
/// <summary>
/// Inactive selection highlight brush.
/// </summary>
/// <remarks>
/// Please note that this property does not have an equivalent system color.
/// </remarks>
public static SolidColorBrush InactiveSelectionHighlightBrush
{
get
{
if (SystemParameters.HighContrast)
{
return SystemColors.HighlightBrush;
}
else
{
return SystemColors.ControlBrush;
}
}
}
/// <summary>
/// Inactive selection highlight text brush.
/// </summary>
/// <remarks>
/// Please note that this property does not have an equivalent system color.
/// </remarks>
public static SolidColorBrush InactiveSelectionHighlightTextBrush
{
get
{
if (SystemParameters.HighContrast)
{
return SystemColors.HighlightTextBrush;
}
else
{
return SystemColors.ControlTextBrush;
}
}
}
#endregion
#region Brush Keys
/// <summary>
/// ActiveBorderBrush System Resource Key
/// </summary>
public static ResourceKey ActiveBorderBrushKey
{
get
{
if (_cacheActiveBorderBrush == null)
{
_cacheActiveBorderBrush = CreateInstance(SystemResourceKeyID.ActiveBorderBrush);
}
return _cacheActiveBorderBrush;
}
}
/// <summary>
/// ActiveCaptionBrush System Resource Key
/// </summary>
public static ResourceKey ActiveCaptionBrushKey
{
get
{
if (_cacheActiveCaptionBrush == null)
{
_cacheActiveCaptionBrush = CreateInstance(SystemResourceKeyID.ActiveCaptionBrush);
}
return _cacheActiveCaptionBrush;
}
}
/// <summary>
/// ActiveCaptionTextBrush System Resource Key
/// </summary>
public static ResourceKey ActiveCaptionTextBrushKey
{
get
{
if (_cacheActiveCaptionTextBrush == null)
{
_cacheActiveCaptionTextBrush = CreateInstance(SystemResourceKeyID.ActiveCaptionTextBrush);
}
return _cacheActiveCaptionTextBrush;
}
}
/// <summary>
/// AppWorkspaceBrush System Resource Key
/// </summary>
public static ResourceKey AppWorkspaceBrushKey
{
get
{
if (_cacheAppWorkspaceBrush == null)
{
_cacheAppWorkspaceBrush = CreateInstance(SystemResourceKeyID.AppWorkspaceBrush);
}
return _cacheAppWorkspaceBrush;
}
}
/// <summary>
/// ControlBrush System Resource Key
/// </summary>
public static ResourceKey ControlBrushKey
{
get
{
if (_cacheControlBrush == null)
{
_cacheControlBrush = CreateInstance(SystemResourceKeyID.ControlBrush);
}
return _cacheControlBrush;
}
}
/// <summary>
/// ControlDarkBrush System Resource Key
/// </summary>
public static ResourceKey ControlDarkBrushKey
{
get
{
if (_cacheControlDarkBrush == null)
{
_cacheControlDarkBrush = CreateInstance(SystemResourceKeyID.ControlDarkBrush);
}
return _cacheControlDarkBrush;
}
}
/// <summary>
/// ControlDarkDarkBrush System Resource Key
/// </summary>
public static ResourceKey ControlDarkDarkBrushKey
{
get
{
if (_cacheControlDarkDarkBrush == null)
{
_cacheControlDarkDarkBrush = CreateInstance(SystemResourceKeyID.ControlDarkDarkBrush);
}
return _cacheControlDarkDarkBrush;
}
}
/// <summary>
/// ControlLightBrush System Resource Key
/// </summary>
public static ResourceKey ControlLightBrushKey
{
get
{
if (_cacheControlLightBrush == null)
{
_cacheControlLightBrush = CreateInstance(SystemResourceKeyID.ControlLightBrush);
}
return _cacheControlLightBrush;
}
}
/// <summary>
/// ControlLightLightBrush System Resource Key
/// </summary>
public static ResourceKey ControlLightLightBrushKey
{
get
{
if (_cacheControlLightLightBrush == null)
{
_cacheControlLightLightBrush = CreateInstance(SystemResourceKeyID.ControlLightLightBrush);
}
return _cacheControlLightLightBrush;
}
}
/// <summary>
/// ControlTextBrush System Resource Key
/// </summary>
public static ResourceKey ControlTextBrushKey
{
get
{
if (_cacheControlTextBrush == null)
{
_cacheControlTextBrush = CreateInstance(SystemResourceKeyID.ControlTextBrush);
}
return _cacheControlTextBrush;
}
}
/// <summary>
/// DesktopBrush System Resource Key
/// </summary>
public static ResourceKey DesktopBrushKey
{
get
{
if (_cacheDesktopBrush == null)
{
_cacheDesktopBrush = CreateInstance(SystemResourceKeyID.DesktopBrush);
}
return _cacheDesktopBrush;
}
}
/// <summary>
/// GradientActiveCaptionBrush System Resource Key
/// </summary>
public static ResourceKey GradientActiveCaptionBrushKey
{
get
{
if (_cacheGradientActiveCaptionBrush == null)
{
_cacheGradientActiveCaptionBrush = CreateInstance(SystemResourceKeyID.GradientActiveCaptionBrush);
}
return _cacheGradientActiveCaptionBrush;
}
}
/// <summary>
/// GradientInactiveCaptionBrush System Resource Key
/// </summary>
public static ResourceKey GradientInactiveCaptionBrushKey
{
get
{
if (_cacheGradientInactiveCaptionBrush == null)
{
_cacheGradientInactiveCaptionBrush = CreateInstance(SystemResourceKeyID.GradientInactiveCaptionBrush);
}
return _cacheGradientInactiveCaptionBrush;
}
}
/// <summary>
/// GrayTextBrush System Resource Key
/// </summary>
public static ResourceKey GrayTextBrushKey
{
get
{
if (_cacheGrayTextBrush == null)
{
_cacheGrayTextBrush = CreateInstance(SystemResourceKeyID.GrayTextBrush);
}
return _cacheGrayTextBrush;
}
}
/// <summary>
/// HighlightBrush System Resource Key
/// </summary>
public static ResourceKey HighlightBrushKey
{
get
{
if (_cacheHighlightBrush == null)
{
_cacheHighlightBrush = CreateInstance(SystemResourceKeyID.HighlightBrush);
}
return _cacheHighlightBrush;
}
}
/// <summary>
/// HighlightTextBrush System Resource Key
/// </summary>
public static ResourceKey HighlightTextBrushKey
{
get
{
if (_cacheHighlightTextBrush == null)
{
_cacheHighlightTextBrush = CreateInstance(SystemResourceKeyID.HighlightTextBrush);
}
return _cacheHighlightTextBrush;
}
}
/// <summary>
/// HotTrackBrush System Resource Key
/// </summary>
public static ResourceKey HotTrackBrushKey
{
get
{
if (_cacheHotTrackBrush == null)
{
_cacheHotTrackBrush = CreateInstance(SystemResourceKeyID.HotTrackBrush);
}
return _cacheHotTrackBrush;
}
}
/// <summary>
/// InactiveBorderBrush System Resource Key
/// </summary>
public static ResourceKey InactiveBorderBrushKey
{
get
{
if (_cacheInactiveBorderBrush == null)
{
_cacheInactiveBorderBrush = CreateInstance(SystemResourceKeyID.InactiveBorderBrush);
}
return _cacheInactiveBorderBrush;
}
}
/// <summary>
/// InactiveCaptionBrush System Resource Key
/// </summary>
public static ResourceKey InactiveCaptionBrushKey
{
get
{
if (_cacheInactiveCaptionBrush == null)
{
_cacheInactiveCaptionBrush = CreateInstance(SystemResourceKeyID.InactiveCaptionBrush);
}
return _cacheInactiveCaptionBrush;
}
}
/// <summary>
/// InactiveCaptionTextBrush System Resource Key
/// </summary>
public static ResourceKey InactiveCaptionTextBrushKey
{
get
{
if (_cacheInactiveCaptionTextBrush == null)
{
_cacheInactiveCaptionTextBrush = CreateInstance(SystemResourceKeyID.InactiveCaptionTextBrush);
}
return _cacheInactiveCaptionTextBrush;
}
}
/// <summary>
/// InfoBrush System Resource Key
/// </summary>
public static ResourceKey InfoBrushKey
{
get
{
if (_cacheInfoBrush == null)
{
_cacheInfoBrush = CreateInstance(SystemResourceKeyID.InfoBrush);
}
return _cacheInfoBrush;
}
}
/// <summary>
/// InfoTextBrush System Resource Key
/// </summary>
public static ResourceKey InfoTextBrushKey
{
get
{
if (_cacheInfoTextBrush == null)
{
_cacheInfoTextBrush = CreateInstance(SystemResourceKeyID.InfoTextBrush);
}
return _cacheInfoTextBrush;
}
}
/// <summary>
/// MenuBrush System Resource Key
/// </summary>
public static ResourceKey MenuBrushKey
{
get
{
if (_cacheMenuBrush == null)
{
_cacheMenuBrush = CreateInstance(SystemResourceKeyID.MenuBrush);
}
return _cacheMenuBrush;
}
}
/// <summary>
/// MenuBarBrush System Resource Key
/// </summary>
public static ResourceKey MenuBarBrushKey
{
get
{
if (_cacheMenuBarBrush == null)
{
_cacheMenuBarBrush = CreateInstance(SystemResourceKeyID.MenuBarBrush);
}
return _cacheMenuBarBrush;
}
}
/// <summary>
/// MenuHighlightBrush System Resource Key
/// </summary>
public static ResourceKey MenuHighlightBrushKey
{
get
{
if (_cacheMenuHighlightBrush == null)
{
_cacheMenuHighlightBrush = CreateInstance(SystemResourceKeyID.MenuHighlightBrush);
}
return _cacheMenuHighlightBrush;
}
}
/// <summary>
/// MenuTextBrush System Resource Key
/// </summary>
public static ResourceKey MenuTextBrushKey
{
get
{
if (_cacheMenuTextBrush == null)
{
_cacheMenuTextBrush = CreateInstance(SystemResourceKeyID.MenuTextBrush);
}
return _cacheMenuTextBrush;
}
}
/// <summary>
/// ScrollBarBrush System Resource Key
/// </summary>
public static ResourceKey ScrollBarBrushKey
{
get
{
if (_cacheScrollBarBrush == null)
{
_cacheScrollBarBrush = CreateInstance(SystemResourceKeyID.ScrollBarBrush);
}
return _cacheScrollBarBrush;
}
}
/// <summary>
/// WindowBrush System Resource Key
/// </summary>
public static ResourceKey WindowBrushKey
{
get
{
if (_cacheWindowBrush == null)
{
_cacheWindowBrush = CreateInstance(SystemResourceKeyID.WindowBrush);
}
return _cacheWindowBrush;
}
}
/// <summary>
/// WindowFrameBrush System Resource Key
/// </summary>
public static ResourceKey WindowFrameBrushKey
{
get
{
if (_cacheWindowFrameBrush == null)
{
_cacheWindowFrameBrush = CreateInstance(SystemResourceKeyID.WindowFrameBrush);
}
return _cacheWindowFrameBrush;
}
}
/// <summary>
/// WindowTextBrush System Resource Key
/// </summary>
public static ResourceKey WindowTextBrushKey
{
get
{
if (_cacheWindowTextBrush == null)
{
_cacheWindowTextBrush = CreateInstance(SystemResourceKeyID.WindowTextBrush);
}
return _cacheWindowTextBrush;
}
}
/// <summary>
/// InactiveSelectionHighlightBrush System Resource Key
/// </summary>
public static ResourceKey InactiveSelectionHighlightBrushKey
{
get
{
if (FrameworkCompatibilityPreferences.GetAreInactiveSelectionHighlightBrushKeysSupported())
{
if (_cacheInactiveSelectionHighlightBrush == null)
{
_cacheInactiveSelectionHighlightBrush = CreateInstance(SystemResourceKeyID.InactiveSelectionHighlightBrush);
}
return _cacheInactiveSelectionHighlightBrush;
}
else
{
return ControlBrushKey;
}
}
}
/// <summary>
/// InactiveSelectionHighlightTextBrush System Resource Key
/// </summary>
public static ResourceKey InactiveSelectionHighlightTextBrushKey
{
get
{
if (FrameworkCompatibilityPreferences.GetAreInactiveSelectionHighlightBrushKeysSupported())
{
if (_cacheInactiveSelectionHighlightTextBrush == null)
{
_cacheInactiveSelectionHighlightTextBrush = CreateInstance(SystemResourceKeyID.InactiveSelectionHighlightTextBrush);
}
return _cacheInactiveSelectionHighlightTextBrush;
}
else
{
return ControlTextBrushKey;
}
}
}
#endregion
#region Implementation
internal static bool InvalidateCache()
{
bool color = SystemResources.ClearBitArray(_colorCacheValid);
bool brush = SystemResources.ClearBitArray(_brushCacheValid);
return color || brush;
}
// Shift count and bit mask for A, R, G, B components
private const int AlphaShift = 24;
private const int RedShift = 16;
private const int GreenShift = 8;
private const int BlueShift = 0;
private const int Win32RedShift = 0;
private const int Win32GreenShift = 8;
private const int Win32BlueShift = 16;
private static int Encode(int alpha, int red, int green, int blue)
{
return red << RedShift | green << GreenShift | blue << BlueShift | alpha << AlphaShift;
}
private static int FromWin32Value(int value)
{
return Encode(255,
(value >> Win32RedShift) & 0xFF,
(value >> Win32GreenShift) & 0xFF,
(value >> Win32BlueShift) & 0xFF);
}
/// <summary>
/// Query for system colors.
/// </summary>
/// <param name="slot">The color slot.</param>
/// <returns>The system color.</returns>
private static Color GetSystemColor(CacheSlot slot)
{
Color color;
lock (_colorCacheValid)
{
if (!_colorCacheValid[(int)slot])
{
uint argb;
int sysColor = SafeNativeMethods.GetSysColor(SlotToFlag(slot));
argb = (uint)FromWin32Value(sysColor);
color = Color.FromArgb((byte)((argb & 0xff000000) >>24), (byte)((argb & 0x00ff0000) >>16), (byte)((argb & 0x0000ff00) >>8), (byte)(argb & 0x000000ff));
_colorCache[(int)slot] = color;
_colorCacheValid[(int)slot] = true;
}
else
{
color = _colorCache[(int)slot];
}
}
return color;
}
private static SolidColorBrush MakeBrush(CacheSlot slot)
{
SolidColorBrush brush;
lock (_brushCacheValid)
{
if (!_brushCacheValid[(int)slot])
{
brush = new SolidColorBrush(GetSystemColor(slot));
brush.Freeze();
_brushCache[(int)slot] = brush;
_brushCacheValid[(int)slot] = true;
}
else
{
brush = _brushCache[(int)slot];
}
}
return brush;
}
private static int SlotToFlag(CacheSlot slot)
{
// FxCop: Hashtable would be overkill, using switch instead
switch (slot)
{
case CacheSlot.ActiveBorder:
return (int)NativeMethods.Win32SystemColors.ActiveBorder;
case CacheSlot.ActiveCaption:
return (int)NativeMethods.Win32SystemColors.ActiveCaption;
case CacheSlot.ActiveCaptionText:
return (int)NativeMethods.Win32SystemColors.ActiveCaptionText;
case CacheSlot.AppWorkspace:
return (int)NativeMethods.Win32SystemColors.AppWorkspace;
case CacheSlot.Control:
return (int)NativeMethods.Win32SystemColors.Control;
case CacheSlot.ControlDark:
return (int)NativeMethods.Win32SystemColors.ControlDark;
case CacheSlot.ControlDarkDark:
return (int)NativeMethods.Win32SystemColors.ControlDarkDark;
case CacheSlot.ControlLight:
return (int)NativeMethods.Win32SystemColors.ControlLight;
case CacheSlot.ControlLightLight:
return (int)NativeMethods.Win32SystemColors.ControlLightLight;
case CacheSlot.ControlText:
return (int)NativeMethods.Win32SystemColors.ControlText;
case CacheSlot.Desktop:
return (int)NativeMethods.Win32SystemColors.Desktop;
case CacheSlot.GradientActiveCaption:
return (int)NativeMethods.Win32SystemColors.GradientActiveCaption;
case CacheSlot.GradientInactiveCaption:
return (int)NativeMethods.Win32SystemColors.GradientInactiveCaption;
case CacheSlot.GrayText:
return (int)NativeMethods.Win32SystemColors.GrayText;
case CacheSlot.Highlight:
return (int)NativeMethods.Win32SystemColors.Highlight;
case CacheSlot.HighlightText:
return (int)NativeMethods.Win32SystemColors.HighlightText;
case CacheSlot.HotTrack:
return (int)NativeMethods.Win32SystemColors.HotTrack;
case CacheSlot.InactiveBorder:
return (int)NativeMethods.Win32SystemColors.InactiveBorder;
case CacheSlot.InactiveCaption:
return (int)NativeMethods.Win32SystemColors.InactiveCaption;
case CacheSlot.InactiveCaptionText:
return (int)NativeMethods.Win32SystemColors.InactiveCaptionText;
case CacheSlot.Info:
return (int)NativeMethods.Win32SystemColors.Info;
case CacheSlot.InfoText:
return (int)NativeMethods.Win32SystemColors.InfoText;
case CacheSlot.Menu:
return (int)NativeMethods.Win32SystemColors.Menu;
case CacheSlot.MenuBar:
return (int)NativeMethods.Win32SystemColors.MenuBar;
case CacheSlot.MenuHighlight:
return (int)NativeMethods.Win32SystemColors.MenuHighlight;
case CacheSlot.MenuText:
return (int)NativeMethods.Win32SystemColors.MenuText;
case CacheSlot.ScrollBar:
return (int)NativeMethods.Win32SystemColors.ScrollBar;
case CacheSlot.Window:
return (int)NativeMethods.Win32SystemColors.Window;
case CacheSlot.WindowFrame:
return (int)NativeMethods.Win32SystemColors.WindowFrame;
case CacheSlot.WindowText:
return (int)NativeMethods.Win32SystemColors.WindowText;
}
return 0;
}
private enum CacheSlot : int
{
ActiveBorder,
ActiveCaption,
ActiveCaptionText,
AppWorkspace,
Control,
ControlDark,
ControlDarkDark,
ControlLight,
ControlLightLight,
ControlText,
Desktop,
GradientActiveCaption,
GradientInactiveCaption,
GrayText,
Highlight,
HighlightText,
HotTrack,
InactiveBorder,
InactiveCaption,
InactiveCaptionText,
Info,
InfoText,
Menu,
MenuBar,
MenuHighlight,
MenuText,
ScrollBar,
Window,
WindowFrame,
WindowText,
NumSlots
}
private static BitArray _colorCacheValid = new BitArray((int)CacheSlot.NumSlots);
private static Color[] _colorCache = new Color[(int)CacheSlot.NumSlots];
private static BitArray _brushCacheValid = new BitArray((int)CacheSlot.NumSlots);
private static SolidColorBrush[] _brushCache = new SolidColorBrush[(int)CacheSlot.NumSlots];
private static SystemResourceKey _cacheActiveBorderBrush;
private static SystemResourceKey _cacheActiveCaptionBrush;
private static SystemResourceKey _cacheActiveCaptionTextBrush;
private static SystemResourceKey _cacheAppWorkspaceBrush;
private static SystemResourceKey _cacheControlBrush;
private static SystemResourceKey _cacheControlDarkBrush;
private static SystemResourceKey _cacheControlDarkDarkBrush;
private static SystemResourceKey _cacheControlLightBrush;
private static SystemResourceKey _cacheControlLightLightBrush;
private static SystemResourceKey _cacheControlTextBrush;
private static SystemResourceKey _cacheDesktopBrush;
private static SystemResourceKey _cacheGradientActiveCaptionBrush;
private static SystemResourceKey _cacheGradientInactiveCaptionBrush;
private static SystemResourceKey _cacheGrayTextBrush;
private static SystemResourceKey _cacheHighlightBrush;
private static SystemResourceKey _cacheHighlightTextBrush;
private static SystemResourceKey _cacheHotTrackBrush;
private static SystemResourceKey _cacheInactiveBorderBrush;
private static SystemResourceKey _cacheInactiveCaptionBrush;
private static SystemResourceKey _cacheInactiveCaptionTextBrush;
private static SystemResourceKey _cacheInfoBrush;
private static SystemResourceKey _cacheInfoTextBrush;
private static SystemResourceKey _cacheMenuBrush;
private static SystemResourceKey _cacheMenuBarBrush;
private static SystemResourceKey _cacheMenuHighlightBrush;
private static SystemResourceKey _cacheMenuTextBrush;
private static SystemResourceKey _cacheScrollBarBrush;
private static SystemResourceKey _cacheWindowBrush;
private static SystemResourceKey _cacheWindowFrameBrush;
private static SystemResourceKey _cacheWindowTextBrush;
private static SystemResourceKey _cacheInactiveSelectionHighlightBrush;
private static SystemResourceKey _cacheInactiveSelectionHighlightTextBrush;
private static SystemResourceKey _cacheActiveBorderColor;
private static SystemResourceKey _cacheActiveCaptionColor;
private static SystemResourceKey _cacheActiveCaptionTextColor;
private static SystemResourceKey _cacheAppWorkspaceColor;
private static SystemResourceKey _cacheControlColor;
private static SystemResourceKey _cacheControlDarkColor;
private static SystemResourceKey _cacheControlDarkDarkColor;
private static SystemResourceKey _cacheControlLightColor;
private static SystemResourceKey _cacheControlLightLightColor;
private static SystemResourceKey _cacheControlTextColor;
private static SystemResourceKey _cacheDesktopColor;
private static SystemResourceKey _cacheGradientActiveCaptionColor;
private static SystemResourceKey _cacheGradientInactiveCaptionColor;
private static SystemResourceKey _cacheGrayTextColor;
private static SystemResourceKey _cacheHighlightColor;
private static SystemResourceKey _cacheHighlightTextColor;
private static SystemResourceKey _cacheHotTrackColor;
private static SystemResourceKey _cacheInactiveBorderColor;
private static SystemResourceKey _cacheInactiveCaptionColor;
private static SystemResourceKey _cacheInactiveCaptionTextColor;
private static SystemResourceKey _cacheInfoColor;
private static SystemResourceKey _cacheInfoTextColor;
private static SystemResourceKey _cacheMenuColor;
private static SystemResourceKey _cacheMenuBarColor;
private static SystemResourceKey _cacheMenuHighlightColor;
private static SystemResourceKey _cacheMenuTextColor;
private static SystemResourceKey _cacheScrollBarColor;
private static SystemResourceKey _cacheWindowColor;
private static SystemResourceKey _cacheWindowFrameColor;
private static SystemResourceKey _cacheWindowTextColor;
#endregion
}
}
| mind0n/hive | Cache/Libs/net46/wpf/src/Framework/System/Windows/SystemColors.cs | C# | mit | 58,975 |
require 'bandcamp/band'
require 'bandcamp/album'
require 'bandcamp/track'
require 'bandcamp/request'
module Bandcamp
class Getter
def initialize request
@request = request
end
def track track_id
response = @request.track track_id
response.nil? ? nil : Track.new(response)
end
def tracks *tracks
track_list = tracks.join(',')
response = @request.track track_list
if response.nil?
[]
else
response.collect{|key,val| Track.new val}
end
end
def album album_id
response = @request.album album_id
response.nil? ? nil : Album.new(response)
end
def search band_name
response = @request.search band_name
if response.nil?
[]
else
response.collect{|band_json| Band.new band_json}
end
end
def band name
response = @request.band name
response.nil? ? nil : Band.new(response)
end
def url address
response = @request.url address
return nil if response.nil?
case
when response.has_key?("album_id")
album(response["album_id"])
when response.has_key?("track_id")
track(response["track_id"])
when (response.keys.length == 1) && response.has_key?("band_id")
band(response["band_id"])
end
end
end
end
| sleepycat/bandcamp_api | lib/bandcamp/getter.rb | Ruby | mit | 1,343 |
'use strict';
var format = require('util').format
, scripts = require('./scripts')
, loadScriptSource = require('./load-script-source')
// Ports: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
function ignore(cb) { cb() }
function InspectorDebuggerAgent() {
if (!(this instanceof InspectorDebuggerAgent)) return new InspectorDebuggerAgent();
this._enabled = false;
this._breakpointsCookie = {}
}
module.exports = InspectorDebuggerAgent;
var proto = InspectorDebuggerAgent.prototype;
proto.enable = function enable(cb) {
this._enabled = true;
cb()
}
proto.disable = function disable(cb) {
this._enabled = false;
cb()
}
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=606
proto._resolveBreakpoint = function _resolveBreakpoint(breakpointId, script, breakpoint, cb) {
var result = { breakpointId: breakpointId, locations: [ ] };
// if a breakpoint registers on startup, the script's source may not have been loaded yet
// in that case we load it, the script's source is set automatically during that step
// should not be needed once other debugger methods are implemented
if (script.source) onensuredSource();
else loadScriptSource(script.url, onensuredSource)
function onensuredSource(err) {
if (err) return cb(err);
if (breakpoint.lineNumber < script.startLine || script.endLine < breakpoint.lineNumber) return cb(null, result);
// TODO: scriptDebugServer().setBreakpoint(scriptId, breakpoint, &actualLineNumber, &actualColumnNumber, false);
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/bindings/core/v8/ScriptDebugServer.cpp&l=89
var debugServerBreakpointId = 'TBD'
if (!debugServerBreakpointId) return cb(null, result);
// will be returned from call to script debug server
var actualLineNumber = breakpoint.lineNumber
, actualColumnNumber = breakpoint.columnNumber
result.locations.push({
scriptId : script.id
, lineNumber : actualLineNumber
, columnNumber : actualColumnNumber
})
cb(null, result);
}
}
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=333
proto.setBreakpointByUrl = function setBreakpointByUrl(opts, cb) {
if (opts.urlRegex) return cb(new Error('Not supporting setBreakpointByUrl with urlRegex'));
var isAntibreakpoint = !!opts.isAntibreakpoint
, url = opts.url
, condition = opts.condition || ''
, lineNumber = opts.lineNumber
, columnNumber
if (typeof opts.columnNumber === Number) {
columnNumber = opts.columnNumber;
if (columnNumber < 0) return cb(new Error('Incorrect column number.'));
} else {
columnNumber = isAntibreakpoint ? -1 : 0;
}
var breakpointId = format('%s:%d:%d', url, lineNumber, columnNumber);
if (this._breakpointsCookie[breakpointId]) return cb(new Error('Breakpoint at specified location already exists.'));
this._breakpointsCookie[breakpointId] = {
url : url
, lineNumber : lineNumber
, columnNumber : columnNumber
, condition : condition
, isAntibreakpoint : isAntibreakpoint
}
if (isAntibreakpoint) return cb(null, { breakpointId: breakpointId });
var match = scripts.byUrl[url];
if (!match) return cb(null, { breakpointId: breakpointId, locations: [] })
var breakpoint = { lineNumber: lineNumber, columnNumber: columnNumber, condition: condition }
this._resolveBreakpoint(breakpointId, match, breakpoint, cb)
}
proto._removeBreakpoint = function _removeBreakpoint(breakpointId, cb) {
// todo
cb()
}
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=416
proto.removeBreakpoint = function removeBreakpoint(breakpointId, cb) {
var breakpoint = this._breakpointsCookie[breakpointId];
if (!breakpoint) return;
this._breakpointsCookie[breakpointId] = undefined;
if (!breakpoint.isAntibreakpoint) this._removeBreakpoint(breakpointId, cb);
else cb()
}
proto.getScriptSource = function getScriptSource(id, cb) {
var script = scripts.byId[id];
if (!script) return cb(new Error('Script with id ' + id + 'was not found'))
cb(null, { scriptSource: script.source })
}
proto.setBreakpointsActive = ignore
proto.setSkipAllPauses = ignore
proto.setBreakpoint = ignore
proto.continueToLocation = ignore
proto.stepOver = ignore
proto.stepInto = ignore
proto.stepOut = ignore
proto.pause = ignore
proto.resume = ignore
proto.searchInContent = ignore
proto.canSetScriptSource = ignore
proto.setScriptSource = ignore
proto.restartFrame = ignore
proto.getFunctionDetails = ignore
proto.getCollectionEntries = ignore
proto.setPauseOnExceptions = ignore
proto.evaluateOnCallFrame = ignore
proto.compileScript = ignore
proto.runScript = ignore
proto.setOverlayMessage = ignore
proto.setVariableValue = ignore
proto.getStepInPositions = ignore
proto.getBacktrace = ignore
proto.skipStackFrames = ignore
proto.setAsyncCallStackDepth = ignore
proto.enablePromiseTracker = ignore
proto.disablePromiseTracker = ignore
proto.getPromises = ignore
proto.getPromiseById = ignore
| thlorenz/debugium | lib/inspector/InspectorDebuggerAgent.js | JavaScript | mit | 5,597 |
/* eslint no-console: 0 */
'use strict';
const fs = require('fs');
const mkdirp = require('mkdirp');
const rollup = require('rollup');
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const uglify = require('rollup-plugin-uglify');
const src = 'src';
const dest = 'dist/rollup-aot';
Promise.all([
// build main/app
rollup.rollup({
entry: `${src}/main-aot.js`,
context: 'this',
plugins: [
nodeResolve({ jsnext: true, module: true }),
commonjs(),
uglify({
output: {
comments: /@preserve|@license|@cc_on/i,
},
mangle: {
keep_fnames: true,
},
compress: {
warnings: false,
},
}),
],
}).then(app =>
app.write({
format: 'iife',
dest: `${dest}/app.js`,
sourceMap: false,
})
),
// build polyfills
rollup.rollup({
entry: `${src}/polyfills-aot.js`,
context: 'this',
plugins: [
nodeResolve({ jsnext: true, module: true }),
commonjs(),
uglify(),
],
}).then(app =>
app.write({
format: 'iife',
dest: `${dest}/polyfills.js`,
sourceMap: false,
})
),
// create index.html
new Promise((resolve, reject) => {
fs.readFile(`${src}/index.html`, 'utf-8', (readErr, indexHtml) => {
if (readErr) return reject(readErr);
const newIndexHtml = indexHtml
.replace('</head>', '<script src="polyfills.js"></script></head>')
.replace('</body>', '<script src="app.js"></script></body>');
mkdirp(dest, mkdirpErr => {
if (mkdirpErr) return reject(mkdirpErr);
return true;
});
return fs.writeFile(
`${dest}/index.html`,
newIndexHtml,
'utf-8',
writeErr => {
if (writeErr) return reject(writeErr);
console.log('Created index.html');
return resolve();
}
);
});
}),
]).then(() => {
console.log('Rollup complete');
}).catch(err => {
console.error('Rollup failed with ', err);
});
| marcandrews/angular2-rollup-investigation | rollup-aot.config.js | JavaScript | mit | 2,085 |
function checkHeadersSent(res, cb) {
return (err, results) => {
if (res.headersSent) {
if (err) {
return cb(err)
}
return null
}
cb(err, results)
}
}
exports.finish = function finish(req, res, next) {
const check = checkHeadersSent.bind(null, res)
if (req.method === 'GET') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
res.json(results)
})
} else if (req.method === 'POST') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
/* eslint-disable max-len */
// http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api?hn#useful-post-responses
if (results) {
res.json(results, 200)
} else {
res.json(204, {})
}
})
} else if (req.method === 'PUT') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results, 200)
} else {
res.json(204, {})
}
})
} else if (req.method === 'PATCH') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results)
} else {
res.json(204, {})
}
})
} else if (req.method === 'DELETE') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results)
} else {
res.json(204, {})
}
})
}
}
| cannoneyed/tmm-glare | server/webUtil/routing.js | JavaScript | mit | 1,653 |
package wiselabs.com.br.studylistandcards.entity;
/**
* Created by C.Lucas on 18/12/2016.
*/
public enum TipoProjeto {
LEI_ORDINARIA, LEI_COMPLEMENTAR, EMENDA_LEI_ORGANICA, DECRETO_LEGISLATIVO, RESOLUCAO;
}
| chrislucas/repo-android | views/support/StudyListAndCards/app/src/main/java/wiselabs/com/br/studylistandcards/entity/TipoProjeto.java | Java | mit | 214 |
import math
import re
from collections import defaultdict
def matches(t1, t2):
t1r = "".join([t[-1] for t in t1])
t2r = "".join([t[-1] for t in t2])
t1l = "".join([t[0] for t in t1])
t2l = "".join([t[0] for t in t2])
t1_edges = [t1[0], t1[-1], t1r, t1l]
t2_edges = [t2[0], t2[-1], t2[0][::-1], t2[-1][::-1], t2l, t2l[::-1], t2r, t2r[::-1]]
for et1 in t1_edges:
for et2 in t2_edges:
if et1 == et2:
return True
return False
def flip(t):
return [l[::-1] for l in t]
# https://stackoverflow.com/a/34347121
def rotate(t):
return [*map("".join, zip(*reversed(t)))]
def set_corner(cor, right, down):
rr = "".join([t[-1] for t in right])
dr = "".join([t[-1] for t in down])
rl = "".join([t[0] for t in right])
dl = "".join([t[0] for t in down])
r_edges = [right[0], right[-1], right[0][::-1], right[-1][::-1], rr, rr[::-1], rl, rl[::-1]]
d_edges = [down[0], down[-1], down[0][::-1], down[-1][::-1], dr, dr[::-1], dl, dl[::-1]]
for _ in range(2):
cor = flip(cor)
for _ in range(4):
cor = rotate(cor)
if cor[-1] in d_edges and "".join([t[-1] for t in cor]) in r_edges:
return cor
return None
def remove_border(t):
return [x[1:-1] for x in t[1:-1]]
def set_left_edge(t1, t2):
ref = "".join([t[-1] for t in t1])
for _ in range(2):
t2 = flip(t2)
for _ in range(4):
t2 = rotate(t2)
if "".join([t[0] for t in t2]) == ref:
return t2
return None
def set_upper_edge(t1, t2):
ref = t1[-1]
for _ in range(2):
t2 = flip(t2)
for _ in range(4):
t2 = rotate(t2)
if t2[0] == ref:
return t2
return None
def assemble_image(img, tiles):
whole_image = []
for l in img:
slice = [""] * len(tiles[l[0]])
for t in l:
for i, s in enumerate(tiles[t]):
slice[i] += s
for s in slice:
whole_image.append(s)
return whole_image
def part1():
tiles = defaultdict(list)
for l in open("input.txt"):
if "Tile" in l:
tile = int(re.findall(r"\d+", l)[0])
elif "." in l or "#" in l:
tiles[tile].append(l.strip())
connected = defaultdict(set)
for i in tiles:
for t in tiles:
if i == t:
continue
if matches(tiles[i], tiles[t]):
connected[i].add(t)
connected[t].add(i)
prod = 1
for i in connected:
if len(connected[i]) == 2:
prod *= i
print(prod)
def part2():
tiles = defaultdict(list)
for l in open("input.txt"):
if "Tile" in l:
tile = int(re.findall(r"\d+", l)[0])
elif "." in l or "#" in l:
tiles[tile].append(l.strip())
connected = defaultdict(set)
for i in tiles:
for t in tiles:
if i == t:
continue
if matches(tiles[i], tiles[t]):
connected[i].add(t)
connected[t].add(i)
sz = int(math.sqrt(len(connected)))
image = [[0 for _ in range(sz)] for _ in range(sz)]
for i in connected:
if len(connected[i]) == 2:
corner = i
break
image[0][0] = corner
added = {corner}
for y in range(1, sz):
pos = connected[image[0][y - 1]]
for cand in pos:
if cand not in added and len(connected[cand]) < 4:
image[0][y] = cand
added.add(cand)
break
for x in range(1, sz):
for y in range(sz):
pos = connected[image[x - 1][y]]
for cand in pos:
if cand not in added:
image[x][y] = cand
added.add(cand)
break
tiles[image[0][0]] = set_corner(tiles[image[0][0]], tiles[image[0][1]], tiles[image[1][0]])
for y, l in enumerate(image):
if y != 0:
prv = image[y - 1][0]
tiles[l[0]] = set_upper_edge(tiles[prv], tiles[l[0]])
for x, tile in enumerate(l):
if x != 0:
prv = image[y][x - 1]
tiles[tile] = set_left_edge(tiles[prv], tiles[tile])
for t in tiles:
tiles[t] = remove_border(tiles[t])
image = assemble_image(image, tiles)
ky = 0
monster = set()
for l in open("monster.txt").read().split("\n"):
kx = len(l)
for i, ch in enumerate(l):
if ch == "#":
monster.add((i, ky))
ky += 1
for _ in range(2):
image = flip(image)
for _ in range(4):
image = rotate(image)
for x in range(0, len(image) - kx):
for y in range(0, len(image) - ky):
parts = []
for i, p in enumerate(monster):
dx = x + p[0]
dy = y + p[1]
parts.append(image[dy][dx] == "#")
if all(parts):
for p in monster:
dx = x + p[0]
dy = y + p[1]
image[dy] = image[dy][:dx] + "O" + image[dy][dx + 1 :]
with open("output.txt", "w+") as f:
for l in rotate(rotate(rotate(image))):
f.write(l + "\n")
print(sum([l.count("#") for l in image]))
if __name__ == "__main__":
part1()
part2()
| BrendanLeber/adventofcode | 2020/20-jurassic_jigsaw/code.py | Python | mit | 5,544 |
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("Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Library")]
[assembly: AssemblyCopyright("Copyright © 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("7fe95ccf-31a1-463d-905f-3356047487df")]
// 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")]
| abdelkarim/HeaderPersister | Library/Properties/AssemblyInfo.cs | C# | mit | 1,390 |
def is_isogram(s):
""" Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter.
Examples of isograms:
- lumberjacks
- background
- downstream
"""
from collections import Counter
s = s.lower().strip()
s = [c for c in s if c.isalpha()]
counts = Counter(s).values()
return max(counts or [1]) == 1
| developerQuinnZ/this_will_work | student-work/hobson_lane/exercism/python/isogram/isogram.py | Python | mit | 428 |
import isEqual from '../util/isEqual';
import Delta from '../delta/Delta';
import Op from '../delta/Op';
import Line, { LineRanges, LineIds } from './Line';
import LineOp from './LineOp';
import AttributeMap from '../delta/AttributeMap';
import { EditorRange, normalizeRange } from './EditorRange';
import TextChange from './TextChange';
import { deltaToText } from './deltaToText';
const EMPTY_RANGE: EditorRange = [ 0, 0 ];
const EMPTY_OBJ = {};
const DELTA_CACHE = new WeakMap<TextDocument, Delta>();
const excludeProps = new Set([ 'id' ]);
export interface FormattingOptions {
nameOnly?: boolean;
allFormats?: boolean;
}
export default class TextDocument {
private _ranges: LineRanges;
byId: LineIds;
lines: Line[];
length: number;
selection: EditorRange | null;
constructor(lines?: TextDocument | Line[] | Delta, selection: EditorRange | null = null) {
if (lines instanceof TextDocument) {
this.lines = lines.lines;
this.byId = lines.byId;
this._ranges = lines._ranges;
this.length = lines.length;
} else {
this.byId = new Map();
if (Array.isArray(lines)) {
this.lines = lines;
} else if (lines) {
this.lines = Line.fromDelta(lines);
} else {
this.lines = [ Line.create() ];
}
if (!this.lines.length) {
this.lines.push(Line.create());
}
this.byId = Line.linesToLineIds(this.lines);
// Check for line id duplicates (should never happen, indicates bug)
this.lines.forEach(line => {
if (this.byId.get(line.id) !== line)
throw new Error('TextDocument has duplicate line ids: ' + line.id);
});
this._ranges = Line.getLineRanges(this.lines);
this.length = this.lines.reduce((length, line) => length + line.length, 0);
}
this.selection = selection && selection.map(index => Math.min(this.length - 1, Math.max(0, index))) as EditorRange;
}
get change() {
const change = new TextChange(this);
change.apply = () => this.apply(change);
return change;
}
getText(range?: EditorRange): string {
if (range) range = normalizeRange(range);
return deltaToText(range ? this.slice(range[0], range[1]) : this.slice(0, this.length - 1));
}
getLineBy(id: string) {
return this.byId.get(id) as Line;
}
getLineAt(at: number) {
return this.lines.find(line => {
const [ start, end ] = this.getLineRange(line);
return start <= at && end > at;
}) as Line;
}
getLinesAt(at: number | EditorRange, encompassed?: boolean) {
let to = at as number;
if (Array.isArray(at)) [ at, to ] = normalizeRange(at);
return this.lines.filter(line => {
const [ start, end ] = this.getLineRange(line);
return encompassed
? start >= at && end <= to
: (start < to || start === at) && end > at;
});
}
getLineRange(at: number | string | Line): EditorRange {
const { lines, _ranges: lineRanges } = this;
if (typeof at === 'number') {
for (let i = 0; i < lines.length; i++) {
const range = lineRanges.get(lines[i]) || EMPTY_RANGE;
if (range[0] <= at && range[1] > at) return range;
}
return EMPTY_RANGE;
} else {
if (typeof at === 'string') at = this.getLineBy(at);
return lineRanges.get(at) as EditorRange;
}
}
getLineRanges(at?: number | EditorRange) {
if (at == null) {
return Array.from(this._ranges.values());
} else {
return this.getLinesAt(at).map(line => this.getLineRange(line));
}
}
getLineFormat(at: number | EditorRange = this.selection as EditorRange, options?: FormattingOptions) {
let to = at as number;
if (Array.isArray(at)) [ at, to ] = normalizeRange(at);
if (at === to) to++;
return getAttributes(Line, this.lines, at, to, undefined, options);
}
getTextFormat(at: number | EditorRange = this.selection as EditorRange, options?: FormattingOptions) {
let to = at as number;
if (Array.isArray(at)) [ at, to ] = normalizeRange(at);
if (at === to) at--;
return getAttributes(LineOp, this.lines, at, to, op => op.insert !== '\n', options);
}
getFormats(at: number | EditorRange = this.selection as EditorRange, options?: FormattingOptions): AttributeMap {
return { ...this.getTextFormat(at, options), ...this.getLineFormat(at, options) };
}
slice(start: number = 0, end: number = Infinity): Delta {
const ops: Op[] = [];
const iter = LineOp.iterator(this.lines);
let index = 0;
while (index < end && iter.hasNext()) {
let nextOp: Op;
if (index < start) {
nextOp = iter.next(start - index);
} else {
nextOp = iter.next(end - index);
ops.push(nextOp);
}
index += Op.length(nextOp);
}
return new Delta(ops);
}
apply(change: Delta | TextChange, selection?: EditorRange | null, throwOnError?: boolean): TextDocument {
let delta: Delta;
if (change instanceof TextChange) {
delta = change.delta;
selection = change.selection;
} else {
delta = change;
}
// If no change, do nothing
if (!delta.ops.length && (selection === undefined || isEqual(this.selection, selection))) {
return this;
}
// Optimization for selection-only change
if (!delta.ops.length && selection) {
return new TextDocument(this, selection);
}
if (selection === undefined && this.selection) {
selection = [ delta.transformPosition(this.selection[0]), delta.transformPosition(this.selection[1]) ];
// If the selection hasn't changed, keep the original reference
if (isEqual(this.selection, selection)) {
selection = this.selection;
}
}
const thisIter = LineOp.iterator(this.lines, this.byId);
const otherIter = Op.iterator(delta.ops);
let lines: Line[] = [];
const firstChange = otherIter.peek();
if (firstChange && firstChange.retain && !firstChange.attributes) {
let firstLeft = firstChange.retain;
while (thisIter.peekLineLength() <= firstLeft) {
firstLeft -= thisIter.peekLineLength();
lines.push(thisIter.nextLine());
}
if (firstChange.retain - firstLeft > 0) {
otherIter.next(firstChange.retain - firstLeft);
}
}
if (!thisIter.hasNext()) {
if (throwOnError) throw new Error('apply() called with change that extends beyond document');
}
let line = Line.createFrom(thisIter.peekLine());
// let wentBeyond = false;
function addLine(line: Line) {
line.length = line.content.length() + 1;
lines.push(line);
}
while (thisIter.hasNext() || otherIter.hasNext()) {
if (otherIter.peekType() === 'insert') {
const otherOp = otherIter.peek();
const index = typeof otherOp.insert === 'string' ? otherOp.insert.indexOf('\n', otherIter.offset) : -1;
if (index < 0) {
line.content.push(otherIter.next());
} else {
const nextIndex = index - otherIter.offset;
if (nextIndex) line.content.push(otherIter.next(nextIndex));
const newlineOp = otherIter.next(1);
const nextAttributes = line.attributes;
line.attributes = newlineOp.attributes || {};
addLine(line);
line = Line.create(undefined, nextAttributes, this.byId);
}
} else {
const length = Math.min(thisIter.peekLength(), otherIter.peekLength());
const thisOp = thisIter.next(length);
const otherOp = otherIter.next(length);
if (typeof thisOp.retain === 'number') {
if (throwOnError) throw new Error('apply() called with change that extends beyond document');
// line.content.push({ insert: '#'.repeat(otherOp.retain || 1) });
// wentBeyond = true;
continue;
}
if (typeof otherOp.retain === 'number') {
const isLine = thisOp.insert === '\n';
let newOp: Op = thisOp;
// Preserve null when composing with a retain, otherwise remove it for inserts
const attributes = otherOp.attributes && AttributeMap.compose(thisOp.attributes, otherOp.attributes);
if (otherOp.attributes && !isEqual(attributes, thisOp.attributes)) {
if (isLine) {
line.attributes = attributes || {};
} else {
newOp = { insert: thisOp.insert };
if (attributes) newOp.attributes = attributes;
}
}
if (isLine) {
addLine(line);
line = Line.createFrom(thisIter.peekLine());
} else {
line.content.push(newOp);
}
// Optimization if at the end of other
if (otherOp.retain === Infinity || !otherIter.hasNext()) {
if (thisIter.opIterator.index !== 0 || thisIter.opIterator.offset !== 0) {
const ops = thisIter.restCurrentLine();
for (let i = 0; i < ops.length; i++) {
line.content.push(ops[i]);
}
addLine(line);
thisIter.nextLine();
}
lines.push(...thisIter.restLines());
break;
}
} // else ... otherOp should be a delete so we won't add the next thisOp insert
}
}
// if (wentBeyond) {
// console.log('went beyond:', line);
// addLine(line);
// }
return new TextDocument(lines, selection);
}
replace(delta?: Delta, selection?: EditorRange | null) {
return new TextDocument(delta, selection);
}
toDelta(): Delta {
const cache = DELTA_CACHE;
let delta = cache.get(this);
if (!delta) {
delta = Line.toDelta(this.lines);
cache.set(this, delta);
}
return delta;
}
equals(other: TextDocument, options?: { contentOnly?: boolean }) {
return this === other
|| (options?.contentOnly || isEqual(this.selection, other.selection))
&& isEqual(this.lines, other.lines, { excludeProps });
}
toJSON() {
return this.toDelta();
}
toString() {
return this.lines
.map(line => line.content
.map(op => typeof op.insert === 'string' ? op.insert : ' ')
.join(''))
.join('\n') + '\n';
}
}
function getAttributes(Type: any, data: any, from: number, to: number, filter?: (next: any) => boolean, options?: FormattingOptions): AttributeMap {
const iter = Type.iterator(data);
let attributes: AttributeMap | undefined;
let index = 0;
if (iter.skip) index += iter.skip(from);
while (index < to && iter.hasNext()) {
let next = iter.next() as { attributes: AttributeMap };
index += Type.length(next);
if (index > from && (!filter || filter(next))) {
if (!next.attributes) attributes = {};
else if (!attributes) attributes = { ...next.attributes };
else if (options?.allFormats) attributes = AttributeMap.compose(attributes, next.attributes);
else attributes = intersectAttributes(attributes, next.attributes, options?.nameOnly);
}
}
return attributes || EMPTY_OBJ;
}
// Intersect 2 attibute maps, keeping only those that are equal in both
function intersectAttributes(attributes: AttributeMap, other: AttributeMap, nameOnly?: boolean) {
return Object.keys(other).reduce(function(intersect, name) {
if (nameOnly) {
if (name in attributes && name in other) intersect[name] = true;
} else if (isEqual(attributes[name], other[name], { partial: true })) {
intersect[name] = other[name];
} else if (isEqual(other[name], attributes[name], { partial: true })) {
intersect[name] = attributes[name];
}
return intersect;
}, {});
}
| jacwright/typewriter | src/doc/TextDocument.ts | TypeScript | mit | 11,631 |
using System;
using System.Linq;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using BTDeploy.ServiceDaemon.TorrentClients;
using System.IO;
namespace BTDeploy.ServiceDaemon
{
[Route("/api/admin/kill", "DELETE")]
public class AdminKillRequest : IReturnVoid
{
}
public class AdminService : ServiceStack.ServiceInterface.Service
{
public void Delete(AdminKillRequest request)
{
Response.Close ();
Environment.Exit (0);
}
}
} | dipeshc/BTDeploy | BTDeploy/ServiceDaemon/AdminService.cs | C# | mit | 466 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace EasyEmit.Creator
{
public class ConstructorCreator : Metadata.MenberData
{
private MethodAttributes methodAttributes;
private ConstructorBuilder constructorBuilder;
private ConstructorInfo constructorInfo;
public ConstructorInfo ConstructorInfo { get { return constructorInfo; } }
private IEnumerable<Metadata.Metadata> parameters;
private List<ParameterCreator> configurationParameter = new List<ParameterCreator>();
private List<CustomAttributeBuilder> customAttributes = new List<CustomAttributeBuilder>();
private ConstructorCreator(ConstructorInfo constructorInfo)
{
State = Metadata.State.Defined;
this.constructorInfo = constructorInfo;
}
internal ConstructorCreator(MethodAttributes methodAttributes,IEnumerable<Metadata.Metadata> parameters)
{
this.methodAttributes = methodAttributes;
this.parameters = parameters;
}
#region BaseDefinition
/// <summary>
/// Configure one parameter of the constructor
/// </summary>
/// <param name="position">Position of parameter in the contrusctor</param>
/// <param name="parameterAttributes"></param>
/// <param name="parameterName">Name of parameter</param>
/// <returns></returns>
public ParameterCreator ConfigureParameter(int position,ParameterAttributes parameterAttributes,string parameterName)
{
if (State == Metadata.State.NotDefined)
{
if (parameters.ElementAt(position - 1) == null)
{
throw new Exception("This parameter doesnt exist");
}
if (configurationParameter.Count(cp => cp.Position == position) == 1)
{
throw new Exception("This parameter is alreadty configure");
}
if (configurationParameter.Count(cp => cp.Name == parameterName) == 1)
{
throw new Exception("An another parameter already have this name");
}
else
{
ParameterCreator parameterCreator = new ParameterCreator(position, parameterAttributes, parameterName, parameters.ElementAt(position - 1));
configurationParameter.Add(parameterCreator);
return parameterCreator;
}
}
else
{
throw new Exception((State == Metadata.State.AllDefiniton) ? "The type has been partialy compile" : "The type has been compile");
}
}
/// <summary>
/// Suppress one parameter using position
/// </summary>
/// <param name="position">Position of parameter to suppress</param>
public void SuppressConfigurationParameter(int position)
{
if (State == Metadata.State.NotDefined)
{
configurationParameter.RemoveAll(cp => cp.Position == position);
}
else
{
throw new Exception((State == Metadata.State.AllDefiniton) ? "The type has been partialy compile" : "The type has been compile");
}
}
/// <summary>
/// Suppress one parameter using name
/// </summary>
/// <param name="name">Name of parameter to suppress</param>
public void SuppressConfigurationParameter(string name)
{
if (State == Metadata.State.NotDefined)
{
configurationParameter.RemoveAll(cp => cp.Name == name);
}
else
{
throw new Exception((State == Metadata.State.AllDefiniton) ? "The type has been partialy compile" : "The type has been compile");
}
}
/// <summary>
/// Add CustomAttribute
/// </summary>
/// <param name="customAttributeBuilder"></param>
/// <exception cref="System.Exception">Throw when type has been already compile</exception>
public void SetCustomAttribute(CustomAttributeBuilder customAttributeBuilder)
{
if (State == Metadata.State.NotDefined)
{
customAttributes.Add(customAttributeBuilder);
}
else
{
throw new Exception((State == Metadata.State.AllDefiniton) ? "The type has been partialy compile" : "The type has been compile");
}
}
/// <summary>
/// Remove all CustomAttribute
/// </summary>
/// <exception cref="System.Exception">Throw when type has been already compile</exception>
public void RemoveAllCustomAttribute()
{
if (State == Metadata.State.NotDefined)
{
customAttributes.Clear();
}
else
{
throw new Exception((State == Metadata.State.AllDefiniton) ? "The type has been partialy compile" : "The type has been compile");
}
}
#endregion
#region Compilation
public bool VerificationBaseDefinition(bool throwException)
{
if (parameters != null)
{
if (parameters.Any(p => p == null || p.State == Metadata.State.NotDefined))
{
if (throwException)
{
throw new Exception(string.Format("The type {0} is null or not defined", parameters.First(p => p == null || p.State == Metadata.State.NotDefined).Name));
}
else { return false; }
}
foreach(ParameterCreator parameter in configurationParameter)
{
parameter.Verification(throwException);
}
}
return true;
}
internal void CompileBaseDefinition(TypeBuilder typeBuilder)
{
VerificationBaseDefinition(true);
Type[] parameters = (this.parameters == null) ? Type.EmptyTypes : this.parameters.Select(m => (Type)m).ToArray();
constructorBuilder = typeBuilder.DefineConstructor(methodAttributes, CallingConventions.Standard, parameters);
foreach(ParameterCreator parameter in configurationParameter)
{
parameter.Compile(constructorBuilder);
}
foreach(CustomAttributeBuilder customAttribute in customAttributes)
{
constructorBuilder.SetCustomAttribute(customAttribute);
}
constructorInfo = constructorBuilder;
State = Metadata.State.BaseDefinition;
}
internal void Compile(TypeBuilder typeBuilder)
{
if(State == Metadata.State.NotDefined)
{
CompileBaseDefinition(typeBuilder);
}
constructorBuilder.GetILGenerator().Emit(OpCodes.Ret);
constructorInfo = constructorBuilder;
State = Metadata.State.Defined;
}
#endregion
public static implicit operator ConstructorCreator(ConstructorInfo constructorInfo)
{
return new ConstructorCreator(constructorInfo);
}
}
} | TheKeyblader/EasyEmit | EasyEmit/EasyEmit/Creator/ConstructorCreator.cs | C# | mit | 7,516 |
<?php
namespace App\Models;
use App\Models\BaseModel;
class MessageModel extends BaseModel
{
public function __construct(\Silex\Application $app)
{
parent::__construct($app, 'message');
}
protected function getAllowedParams()
{
return array(
'author' => true,
'title' => true,
'content' => true
);
}
}
| loganbraga/api.loganbraga.fr | App/Models/MessageModel.php | PHP | mit | 392 |
const createImmutableEqualsSelector = require('./customSelectorCreator');
const compare = require('../util/compare');
const exampleReducers = require('../reducers/exampleReducers');
/**
* Get state function
*/
const getSortingState = exampleReducers.getSortingState;
const getPaginationState = exampleReducers.getPaginationState;
const getDataState = exampleReducers.getDataState;
/**
* Sorting immutable data source
* @param {Map} source immutable data source
* @param {string} sortingKey property of data
* @param {string} orderByCondition 'asc' or 'desc'
* @return {List} immutable testing data source with sorting
*/
const sortingData = (source, sortingKey, orderByCondition) => {
let orderBy = orderByCondition === 'asc' ? 1 : -1;
return source.sortBy(data => data.get(sortingKey), (v, k) => orderBy * compare(v, k));
}
/**
* Paginating data from sortingSelector
* @param {List} sortedData immutable data source with sorting
* @param {number} start
* @param {number} end
* @return {array} sorting data with pagination and converting Immutable.List to array
*/
const pagination = (sortedData, start, end) => sortedData.slice(start, end).toList().toJS()
/**
* Partial selector only to do sorting
*/
const sortingSelector = createImmutableEqualsSelector(
[
getDataState, // get data source
getSortingState
],
(dataState, sortingCondition) => sortingData(dataState, sortingCondition.get('sortingKey'), sortingCondition.get('orderBy'))
)
/**
* Root selector to paginate data from sortingSelector
*/
const paginationSelector = createImmutableEqualsSelector(
[
sortingSelector, // bind selector to be new data source
getPaginationState
],
(sortedData, paginationCondition) => pagination(sortedData, paginationCondition.get('start'), paginationCondition.get('end'))
)
module.exports = paginationSelector;
| ysaaron/reselect-demo | src/selector/exampleSelector.js | JavaScript | mit | 1,908 |
/**
* Filesystem based directory storage.
*/
package com.github.basking2.sdsai.dsds.fs;
| basking2/sdsai-dsds | sdsai-dsds-core/src/main/java/com/github/basking2/sdsai/dsds/fs/package-info.java | Java | mit | 90 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.peering.models;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
/** Resource collection API of ReceivedRoutes. */
public interface ReceivedRoutes {
/**
* Lists the prefixes received over the specified peering under the given subscription and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param peeringName The name of the peering.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the paginated list of received routes for the peering.
*/
PagedIterable<PeeringReceivedRoute> listByPeering(String resourceGroupName, String peeringName);
/**
* Lists the prefixes received over the specified peering under the given subscription and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param peeringName The name of the peering.
* @param prefix The optional prefix that can be used to filter the routes.
* @param asPath The optional AS path that can be used to filter the routes.
* @param originAsValidationState The optional origin AS validation state that can be used to filter the routes.
* @param rpkiValidationState The optional RPKI validation state that can be used to filter the routes.
* @param skipToken The optional page continuation token that is used in the event of paginated result.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the paginated list of received routes for the peering.
*/
PagedIterable<PeeringReceivedRoute> listByPeering(
String resourceGroupName,
String peeringName,
String prefix,
String asPath,
String originAsValidationState,
String rpkiValidationState,
String skipToken,
Context context);
}
| Azure/azure-sdk-for-java | sdk/peering/azure-resourcemanager-peering/src/main/java/com/azure/resourcemanager/peering/models/ReceivedRoutes.java | Java | mit | 2,571 |
/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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 3 of the License, or
* (at your option) any later version.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.component;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: ContextAwareComponent.java 7199 2014-08-27 13:58:10Z teodord $
*/
public interface ContextAwareComponent extends Component
{
/**
*
*/
void setContext(ComponentContext context);
/**
*
*/
ComponentContext getContext();
}
| juniormesquitadandao/report4all | lib/src/net/sf/jasperreports/engine/component/ContextAwareComponent.java | Java | mit | 1,351 |
package example.naoki.ble_myo;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Created by naoki on 15/04/09.
*
*/
public class EmgData {
private ArrayList<Double> emgData = new ArrayList<>();
public EmgData() {
}
public EmgData(EmgCharacteristicData characteristicData) {
this.emgData = new ArrayList<>( characteristicData.getEmg8Data_abs().getEmgArray() );
}
public EmgData(ArrayList<Double> emgData) {
this.emgData = emgData;
}
public String getLine() {
StringBuilder return_SB = new StringBuilder();
for (int i_emg_num = 0; i_emg_num < 8; i_emg_num++) {
return_SB.append(String.format("%f,", emgData.get(i_emg_num)));
}
return return_SB.toString();
}
public void setLine(String line) {
ArrayList<Double> data = new ArrayList<>();
StringTokenizer st = new StringTokenizer(line , ",");
for (int i_emg_num = 0; i_emg_num < 8; i_emg_num++) {
data.add(Double.parseDouble(st.nextToken()));
}
emgData = data;
}
public void addElement(double element) {
emgData.add(element);
}
public void setElement(int index ,double element) {
emgData.set(index,element);
}
public Double getElement(int index) {
if (index < 0 || index > emgData.size() - 1) {
return null;
} else {
return emgData.get(index);
}
}
public ArrayList<Double> getEmgArray() {
return this.emgData;
}
public Double getDistanceFrom(EmgData baseData) {
Double distance = 0.00;
for (int i_element = 0; i_element < 8; i_element++) {
distance += Math.pow((emgData.get(i_element) - baseData.getElement(i_element)),2.0);
}
return Math.sqrt(distance);
}
public Double getInnerProductionTo(EmgData baseData) {
Double val = 0.00;
for (int i_element = 0; i_element < 8; i_element++) {
val += emgData.get(i_element) * baseData.getElement(i_element);
}
return val;
}
public Double getNorm(){
Double norm = 0.00;
for (int i_element = 0; i_element < 8; i_element++) {
norm += Math.pow( emgData.get(i_element) ,2.0);
}
return Math.sqrt(norm);
}
}
| meleap/myo_AndoridEMG | BLE_myo/app/src/main/java/example/naoki/ble_myo/EmgData.java | Java | mit | 2,341 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
package fixtures.bodyfile;
/**
* The interface for AutoRestSwaggerBATFileService class.
*/
public interface AutoRestSwaggerBATFileService {
/**
* Gets the URI used as the base for all cloud service requests.
* @return The BaseUri value.
*/
String getBaseUri();
/**
* Gets the Files object to access its operations.
* @return the files value.
*/
Files getFiles();
}
| BretJohnson/autorest | AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/AutoRestSwaggerBATFileService.java | Java | mit | 746 |
package com.xinyiglass.springSample.entity;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.jdbc.core.RowMapper;
@SuppressWarnings("rawtypes")
public class FuncVO implements FactoryBean,RowMapper<FuncVO>, Cloneable{
private Long functionId;
private String functionCode;
private String functionName;
private String functionHref;
private String description;
private Long iconId;
private String iconCode;
private Long createdBy;
private java.util.Date creationDate;
private Long lastUpdatedBy;
private java.util.Date lastUpdateDate;
private Long lastUpdateLogin;
//GET&SET Method
public Long getFunctionId() {
return functionId;
}
public void setFunctionId(Long functionId) {
this.functionId = functionId;
}
public String getFunctionCode() {
return functionCode;
}
public void setFunctionCode(String functionCode) {
this.functionCode = functionCode;
}
public String getFunctionName() {
return functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
public String getFunctionHref() {
return functionHref;
}
public void setFunctionHref(String functionHref) {
this.functionHref = functionHref;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getIconId() {
return iconId;
}
public void setIconId(Long iconId) {
this.iconId = iconId;
}
public String getIconCode() {
return iconCode;
}
public void setIconCode(String iconCode) {
this.iconCode = iconCode;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public java.util.Date getCreationDate() {
return creationDate;
}
public void setCreationDate(java.util.Date creationDate) {
this.creationDate = creationDate;
}
public Long getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(Long lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public java.util.Date getLastUpdateDate() {
return lastUpdateDate;
}
public void setLastUpdateDate(java.util.Date lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
public Long getLastUpdateLogin() {
return lastUpdateLogin;
}
public void setLastUpdateLogin(Long lastUpdateLogin) {
this.lastUpdateLogin = lastUpdateLogin;
}
@Override
public Object clone() {
FuncVO funcVO = null;
try{
funcVO = (FuncVO)super.clone();
}catch(CloneNotSupportedException e) {
e.printStackTrace();
}
return funcVO;
}
@Override
public FuncVO mapRow(ResultSet rs, int rowNum) throws SQLException {
FuncVO func = new FuncVO();
func.setFunctionId(rs.getLong("function_id"));
func.setFunctionCode(rs.getString("function_code"));
func.setFunctionName(rs.getString("function_name"));
func.setFunctionHref(rs.getString("function_href"));
func.setDescription(rs.getObject("description")==null?null:rs.getString("description"));
func.setIconId(rs.getLong("icon_id"));
func.setIconCode(rs.getString("icon_code"));
func.setCreatedBy(rs.getLong("created_by"));
func.setCreationDate(rs.getDate("creation_date"));
func.setLastUpdatedBy(rs.getLong("last_updated_by"));
func.setLastUpdateDate(rs.getDate("last_update_date"));
func.setLastUpdateLogin(rs.getLong("last_update_login"));
return func;
}
@Override
public Object getObject() throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public Class getObjectType() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isSingleton() {
// TODO Auto-generated method stub
return false;
}
}
| xygdev/XYG_ALB2B | src/com/xinyiglass/springSample/entity/FuncVO.java | Java | mit | 4,250 |
var stream = require('readable-stream')
var util = require('util')
var fifo = require('fifo')
var toStreams2 = function(s) {
if (s._readableState) return s
var wrap = new stream.Readable().wrap(s)
if (s.destroy) wrap.destroy = s.destroy.bind(s)
return wrap
}
var Parallel = function(streams, opts) {
if (!(this instanceof Parallel)) return new Parallel(streams, opts)
stream.Readable.call(this, opts)
this.destroyed = false
this._forwarding = false
this._drained = false
this._queue = fifo()
for (var i = 0; i < streams.length; i++) this.add(streams[i])
this._current = this._queue.node
}
util.inherits(Parallel, stream.Readable)
Parallel.obj = function(streams) {
return new Parallel(streams, {objectMode: true, highWaterMark: 16})
}
Parallel.prototype.add = function(s) {
s = toStreams2(s)
var self = this
var node = this._queue.push(s)
var onend = function() {
if (node === self._current) self._current = node.next
self._queue.remove(node)
s.removeListener('readable', onreadable)
s.removeListener('end', onend)
s.removeListener('error', onerror)
s.removeListener('close', onclose)
self._forward()
}
var onreadable = function() {
self._forward()
}
var onclose = function() {
if (!s._readableState.ended) self.destroy()
}
var onerror = function(err) {
self.destroy(err)
}
s.on('end', onend)
s.on('readable', onreadable)
s.on('close', onclose)
s.on('error', onerror)
}
Parallel.prototype._read = function () {
this._drained = true
this._forward()
}
Parallel.prototype._forward = function () {
if (this._forwarding || !this._drained) return
this._forwarding = true
var stream = this._get()
if (!stream) return
var chunk
while ((chunk = stream.read()) !== null) {
this._current = this._current.next
this._drained = this.push(chunk)
stream = this._get()
if (!stream) return
}
this._forwarding = false
}
Parallel.prototype._get = function() {
var stream = this._current && this._queue.get(this._current)
if (!stream) this.push(null)
else return stream
}
Parallel.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
var next
while ((next = this._queue.shift())) {
if (next.destroy) next.destroy()
}
if (err) this.emit('error', err)
this.emit('close')
}
module.exports = Parallel | mafintosh/parallel-multistream | index.js | JavaScript | mit | 2,398 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ARM::Network
module Models
#
# Properties of Backend address pool settings of application gateway
#
class ApplicationGatewayBackendHttpSettingsPropertiesFormat
include MsRestAzure
# @return [Integer] Gets or sets the port
attr_accessor :port
# @return [ApplicationGatewayProtocol] Gets or sets the protocol.
# Possible values for this property include: 'Http', 'Https'.
attr_accessor :protocol
# @return [ApplicationGatewayCookieBasedAffinity] Gets or sets the
# cookie affinity. Possible values for this property include:
# 'Enabled', 'Disabled'.
attr_accessor :cookie_based_affinity
# @return [String] Gets or sets Provisioning state of the backend http
# settings resource Updating/Deleting/Failed
attr_accessor :provisioning_state
#
# Validate the object. Throws ValidationError if validation fails.
#
def validate
end
#
# Serializes given Model object into Ruby Hash.
# @param object Model object to serialize.
# @return [Hash] Serialized object in form of Ruby Hash.
#
def self.serialize_object(object)
object.validate
output_object = {}
serialized_property = object.port
output_object['port'] = serialized_property unless serialized_property.nil?
serialized_property = object.protocol
output_object['protocol'] = serialized_property unless serialized_property.nil?
serialized_property = object.cookie_based_affinity
output_object['cookieBasedAffinity'] = serialized_property unless serialized_property.nil?
serialized_property = object.provisioning_state
output_object['provisioningState'] = serialized_property unless serialized_property.nil?
output_object
end
#
# Deserializes given Ruby Hash into Model object.
# @param object [Hash] Ruby Hash object to deserialize.
# @return [ApplicationGatewayBackendHttpSettingsPropertiesFormat]
# Deserialized object.
#
def self.deserialize_object(object)
return if object.nil?
output_object = ApplicationGatewayBackendHttpSettingsPropertiesFormat.new
deserialized_property = object['port']
deserialized_property = Integer(deserialized_property) unless deserialized_property.to_s.empty?
output_object.port = deserialized_property
deserialized_property = object['protocol']
if (!deserialized_property.nil? && !deserialized_property.empty?)
enum_is_valid = ApplicationGatewayProtocol.constants.any? { |e| ApplicationGatewayProtocol.const_get(e).to_s.downcase == deserialized_property.downcase }
fail MsRest::DeserializationError.new('Error occured while deserializing the enum', nil, nil, nil) unless enum_is_valid
end
output_object.protocol = deserialized_property
deserialized_property = object['cookieBasedAffinity']
if (!deserialized_property.nil? && !deserialized_property.empty?)
enum_is_valid = ApplicationGatewayCookieBasedAffinity.constants.any? { |e| ApplicationGatewayCookieBasedAffinity.const_get(e).to_s.downcase == deserialized_property.downcase }
fail MsRest::DeserializationError.new('Error occured while deserializing the enum', nil, nil, nil) unless enum_is_valid
end
output_object.cookie_based_affinity = deserialized_property
deserialized_property = object['provisioningState']
output_object.provisioning_state = deserialized_property
output_object.validate
output_object
end
end
end
end
| gadgetmg/azure_mgmt_network | lib/azure_mgmt_network/models/application_gateway_backend_http_settings_properties_format.rb | Ruby | mit | 3,845 |
<?php
/* AdminBundle::layoutSUP.html.twig */
class __TwigTemplate_66433e67719e263cb349ed4744109ccf2266f78b6012a7d47e226769c3932f4d extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'user_content' => array($this, 'block_user_content'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<!DOCTYPE html>
<html>
<head>
<meta charset=\"UTF-8\">
<title>AfrikIsol | Dashboard</title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<!-- Bootstrap 3.3.4 -->
<link href=\"";
// line 8
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bootstrap/css/bootstrap.min.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- FontAwesome 4.3.0 -->
<link href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\" rel=\"stylesheet\" type=\"text/css\" />
<!-- Ionicons 2.0.0 -->
<link href=\"https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css\" rel=\"stylesheet\" type=\"text/css\" />
<!-- Theme style -->
<link href=\"";
// line 14
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("dist/css/AdminLTE.min.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- DATA TABLES -->
<link href=\"";
// line 16
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/datatables/dataTables.bootstrap.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<link href=\"";
// line 18
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("dist/css/skins/_all-skins.min.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- iCheck -->
<link href=\"";
// line 20
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/iCheck/flat/blue.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- Morris chart -->
<link href=\"";
// line 22
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/morris/morris.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- jvectormap -->
<link href=\"";
// line 24
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/jvectormap/jquery-jvectormap-1.2.2.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- Date Picker -->
<link href=\"";
// line 26
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/datepicker/datepicker3.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- Daterange picker -->
<link href=\"";
// line 28
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/daterangepicker/daterangepicker-bs3.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- bootstrap wysihtml5 - text editor -->
<link href=\"";
// line 30
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
\$(function () {
\$(\"#example1\").dataTable();
\$('#example2').dataTable({
\"bPaginate\": true,
\"bLengthChange\": false,
\"bFilter\": false,
\"bSort\": true,
\"bInfo\": true,
\"bAutoWidth\": false
});
});
</script>
</head>
<body class=\"skin-blue sidebar-mini\">
<div class=\"wrapper\">
<header class=\"main-header\">
<!-- Logo -->
<a href=\"\" class=\"logo\" height=\"40\" width=\"40\">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class=\"logo-mini\"><b>A</b>AI</span>
<!-- logo for regular state and mobile devices -->
<span class=\"logo-lg\"><b>Admin</b>AfrikIsol<br></span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class=\"navbar navbar-static-top\" role=\"navigation\">
<!-- Sidebar toggle button-->
<a href=\"#\" class=\"sidebar-toggle\" data-toggle=\"offcanvas\" role=\"button\">
<span class=\"sr-only\">Toggle navigation</span>
</a>
<div class=\"navbar-custom-menu\">
<ul class=\"nav navbar-nav\">
<li class=\"dropdown user user-menu\">
";
// line 69
$context["imag"] = $this->env->getExtension('img_extension')->afficheImg($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()));
// line 70
echo " <a href=\"";
echo $this->env->getExtension('routing')->getPath("fos_user_security_logout");
echo "\" class=\"dropdown-toggle\" >
<img src=\"data:image/png;base64,";
// line 71
echo twig_escape_filter($this->env, (isset($context["imag"]) ? $context["imag"] : $this->getContext($context, "imag")), "html", null, true);
echo "\" class=\"user-image\" alt=\"User Image\" />
<span class=\"hidden-xs\">Déconnexion</span>
</a>
</li>
<!-- Control Sidebar Toggle Button
<li>
<a href=\"#\" data-toggle=\"control-sidebar\"><i class=\"fa fa-gears\"></i></a>
</li>
-->
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class=\"main-sidebar\">
<!-- sidebar: style can be found in sidebar.less -->
<section class=\"sidebar\">
<!-- Sidebar user panel -->
<div class=\"user-panel\">
<div class=\"pull-left image\">
<img src=\"data:image/png;base64,";
// line 93
echo twig_escape_filter($this->env, (isset($context["imag"]) ? $context["imag"] : $this->getContext($context, "imag")), "html", null, true);
echo "\" class=\"img-circle\" alt=\"User Image\" />
</div>
<div class=\"pull-left info\">
<p>";
// line 97
echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "username", array()), "html", null, true);
echo " </p>
<a href=\"#\"><i class=\"fa fa-circle text-success\"></i> Online</a>
</div>
</div>
<!-- search form -->
<form action=\"#\" method=\"get\" class=\"sidebar-form\">
<div class=\"input-group\">
<input type=\"text\" name=\"q\" class=\"form-control\" placeholder=\"Search...\"/>
<span class=\"input-group-btn\">
<button type='submit' name='search' id='search-btn' class=\"btn btn-flat\"><i class=\"fa fa-search\"></i></button>
</span>
</div>
</form>
<!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class=\"sidebar-menu\">
<li class=\"header\">Menu de navigation</li>
<li class=\"active treeview\">
<a href=\"#\">
<i class=\"fa fa-desktop\"></i> <span>Gestion des comptes</span> <i class=\"fa fa-angle-left pull-right\"></i>
</a>
<ul class=\"treeview-menu\">
<li class=\"active\">
<a href=\"";
// line 120
echo $this->env->getExtension('routing')->getPath("fos_user_profile_show");
echo "\"><i class=\"fa fa-user-secret\"></i> Mon compte<i class=\"fa fa-angle-left pull-right\"></i></a>
<ul class=\"treeview-menu\">
<li><a href=\"";
// line 122
echo $this->env->getExtension('routing')->getPath("admin_updateprofile");
echo "\"><i class=\"fa fa-wrench\"></i> Modifier infos</a></li>
<li><a href=\"";
// line 123
echo $this->env->getExtension('routing')->getPath("fos_user_change_password");
echo "\"><i class=\"fa fa-lock\"></i> Changer mot de passe</a></li>
</ul>
</li>
<li>
<a href=\"index2.html\"><i class=\"fa fa-users\"></i> Tous les utilisateurs<i class=\"fa fa-angle-left pull-right\"></i></a>
<ul class=\"treeview-menu\">
<li><a href=\"";
// line 129
echo $this->env->getExtension('routing')->getPath("fos_user_registration_register");
echo "\"><i class=\"fa fa-user-plus\"></i> Créer</a></li>
<li><a href=\"";
// line 130
echo $this->env->getExtension('routing')->getPath("admin_listerUser");
echo "\"><i class=\"fa fa-list-alt\"></i> Lister</a></li>
</ul>
</li>
</ul>
</li>
<li class=\"active treeview\">
<a href=\"#\">
<i class=\"fa fa-slideshare\"></i> <span>Gestion des Clients</span> <i class=\"fa fa-angle-left pull-right\"></i>
</a>
<ul class=\"treeview-menu\">
<li class=\"active\">
<a href=\"";
// line 141
echo $this->env->getExtension('routing')->getPath("tech_addClient");
echo "\"><i class=\"fa fa-plus\"></i> Ajouter Client</a>
</li>
<li>
<a href=\"";
// line 145
echo $this->env->getExtension('routing')->getPath("tech_listClient");
echo "\"><i class=\"fa fa-th-list\"></i> Lister Clients</a>
</li>
</ul>
</li>
<li class=\"active treeview\">
<a href=\"#\">
<i class=\"fa fa-clipboard\"></i> <span>Gestion des Projets</span> <i class=\"fa fa-angle-left pull-right\"></i>
</a>
<ul class=\"treeview-menu\">
<li class=\"active\">
<a href=\"";
// line 157
echo $this->env->getExtension('routing')->getPath("tech_addProjet");
echo "\"><i class=\"fa fa-plus-square-o\"></i> Ajouter Projet</a>
</li>
<li>
<a href=\"";
// line 161
echo $this->env->getExtension('routing')->getPath("tech_listProjet");
echo "\"><i class=\"fa fa-list-ul\"></i> Lister projets</a>
</li>
<li>
<a href=\"";
// line 165
echo $this->env->getExtension('routing')->getPath("tech_listGantt");
echo "\"><i class=\"fa fa-bar-chart\"></i>Planification des travaux</a>
</li>
<li>
<a href=\"";
// line 168
echo $this->env->getExtension('routing')->getPath("tech_listTole");
echo "\"><i class=\"fa fa-edit\"></i> Ajouter/Lister tôles</a>
</li>
<li>
<a href=\"";
// line 171
echo $this->env->getExtension('routing')->getPath("tech_listPlan");
echo "\"><i class=\"fa fa-area-chart\"></i>Planification </a>
</li>
<li>
<a href=\"";
// line 174
echo $this->env->getExtension('routing')->getPath("tech_listAvancement");
echo "\"><i class=\"fa fa-area-chart\"></i>Avancement</a>
</li>
<li>
<a href=\"";
// line 177
echo $this->env->getExtension('routing')->getPath("tech_listMAD");
echo "\"><i class=\"fa fa-area-chart\"></i>Mise à disposition</a>
</li>
</ul>
</li>
<li class=\"active treeview\">
<a href=\"#\">
<i class=\"fa fa-database\"></i> <span>Gestion de Stock</span> <i class=\"fa fa-angle-left pull-right\"></i>
</a>
<ul class=\"treeview-menu\">
<li class=\"active\">
<a href=\"";
// line 189
echo $this->env->getExtension('routing')->getPath("log_addStock");
echo "\"><i class=\"fa fa-calculator\"></i> Ajouter au stock</a>
</li>
<li>
<a href=\"";
// line 193
echo $this->env->getExtension('routing')->getPath("log_listStock");
echo "\"><i class=\"fa fa-list\"></i> Lister Stock</a>
</li>
<li>
<a href=\"";
// line 197
echo $this->env->getExtension('routing')->getPath("log_listDmd");
echo "\"><i class=\"fa fa-list\"></i> Demandes <span class=\"label label-primary pull-right\">";
echo twig_escape_filter($this->env, $this->env->getExtension('dmd_extension')->calcul(0), "html", null, true);
echo "</span></a>
</li>
</ul>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class=\"content-wrapper\">
<!-- Content Header (Page header) -->
<section class=\"content-header\">
<h1>
Tableau de bord
<small>Panneau de contrôle</small>
</h1>
<ol class=\"breadcrumb\">
<li><a href=\"#\"><i class=\"fa fa-dashboard\"></i> Accueil</a></li>
<li class=\"active\">Tableau de bord</li>
</ol>
</section>
<!-- Main content -->
<section class=\"content\">
<br>
<br>
<br>
<br>
";
// line 227
$this->displayBlock('user_content', $context, $blocks);
// line 242
echo "
<br>
<br>
";
// line 245
if ($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "request", array()), "hasPreviousSession", array())) {
// line 246
echo " ";
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session", array()), "flashbag", array()), "all", array(), "method"));
foreach ($context['_seq'] as $context["type"] => $context["messages"]) {
// line 247
echo " ";
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($context["messages"]);
foreach ($context['_seq'] as $context["_key"] => $context["message"]) {
// line 248
echo " <div class=\"flash-";
echo twig_escape_filter($this->env, $context["type"], "html", null, true);
echo "\">
<h3> ";
// line 249
echo twig_escape_filter($this->env, $context["message"], "html", null, true);
echo " </h3>
</div>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['message'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 252
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['type'], $context['messages'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 253
echo " ";
}
// line 254
echo " </section><!-- /.content -->
</div><!-- /.content-wrapper -->
<footer class=\"main-footer\">
<strong>Copyright © 2014-2015 <a href=\"\">Ali Brahem</a>.</strong> All rights reserved.
</footer>
<!-- Control Sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class='control-sidebar-bg'></div>
</div><!-- ./wrapper -->
<!-- jQuery 2.1.4 -->
<script src=\"";
// line 269
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/jQuery/jQuery-2.1.4.min.js"), "html", null, true);
echo "\"></script>
<!-- jQuery UI 1.11.2 -->
<script src=\"http://code.jquery.com/ui/1.11.2/jquery-ui.min.js\" type=\"text/javascript\"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
\$.widget.bridge('uibutton', \$.ui.button);
</script>
<!-- Bootstrap 3.3.2 JS -->
<script src=\"";
// line 277
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bootstrap/js/bootstrap.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- Morris.js charts -->
<script src=\"http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js\"></script>
<script src=\"";
// line 280
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/morris/morris.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- Sparkline -->
<script src=\"";
// line 282
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/sparkline/jquery.sparkline.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- jvectormap -->
<script src=\"";
// line 284
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<script src=\"";
// line 285
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/jvectormap/jquery-jvectormap-world-mill-en.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- jQuery Knob Chart -->
<script src=\"";
// line 287
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/knob/jquery.knob.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- daterangepicker -->
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js\" type=\"text/javascript\"></script>
<script src=\"";
// line 290
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/daterangepicker/daterangepicker.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- datepicker -->
<script src=\"";
// line 292
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/datepicker/bootstrap-datepicker.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src=\"";
// line 294
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- Slimscroll -->
<script src=\"";
// line 296
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/slimScroll/jquery.slimscroll.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- FastClick -->
<script src=\"";
// line 298
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/fastclick/fastclick.min.js"), "html", null, true);
echo "\"></script>
<!-- AdminLTE App -->
<script src=\"";
// line 300
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("dist/js/app.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<script src=\"";
// line 301
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bootstrap/js/calculTole.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<script src=\"";
// line 302
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bootstrap/js/avancement.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<script src=\"";
// line 303
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bootstrap/js/stock.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src=\"";
// line 305
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("dist/js/pages/dashboard.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<!-- DATA TABES SCRIPT -->
<script src=\"";
// line 307
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/datatables/jquery.dataTables.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<script src=\"";
// line 308
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("plugins/datatables/dataTables.bootstrap.min.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
<link href=\"";
// line 309
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bootstrap/css/loading.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" />
<!-- AdminLTE for demo purposes -->
<script src=\"";
// line 312
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("dist/js/demo.js"), "html", null, true);
echo "\" type=\"text/javascript\"></script>
</body>
</html>";
}
// line 227
public function block_user_content($context, array $blocks = array())
{
// line 228
echo "
<!-- Small boxes (Stat box) -->
<div class=\"row\">
<div class=\"col-lg-3 col-xs-6\">
<!-- small box -->
</div><!-- ./col -->
<!-- Main row -->
<div class=\"row\">
</div><!-- /.row (main row) -->
";
}
public function getTemplateName()
{
return "AdminBundle::layoutSUP.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 517 => 228, 514 => 227, 507 => 312, 501 => 309, 497 => 308, 493 => 307, 488 => 305, 483 => 303, 479 => 302, 475 => 301, 471 => 300, 466 => 298, 461 => 296, 456 => 294, 451 => 292, 446 => 290, 440 => 287, 435 => 285, 431 => 284, 426 => 282, 421 => 280, 415 => 277, 404 => 269, 387 => 254, 384 => 253, 378 => 252, 369 => 249, 364 => 248, 359 => 247, 354 => 246, 352 => 245, 347 => 242, 345 => 227, 310 => 197, 303 => 193, 296 => 189, 281 => 177, 275 => 174, 269 => 171, 263 => 168, 257 => 165, 250 => 161, 243 => 157, 228 => 145, 221 => 141, 207 => 130, 203 => 129, 194 => 123, 190 => 122, 185 => 120, 159 => 97, 152 => 93, 127 => 71, 122 => 70, 120 => 69, 78 => 30, 73 => 28, 68 => 26, 63 => 24, 58 => 22, 53 => 20, 48 => 18, 43 => 16, 38 => 14, 29 => 8, 20 => 1,);
}
}
| AliBrahem/AfrikIsol | app/cache/prod/twig/6/6/66433e67719e263cb349ed4744109ccf2266f78b6012a7d47e226769c3932f4d.php | PHP | mit | 28,170 |
const App = require('./spec/app');
module.exports = config => {
const params = {
basePath: '',
frameworks: [
'express-http-server',
'jasmine'
],
files: [
'lib/**/*.js'
],
colors: true,
singleRun: true,
logLevel: config.LOG_WARN,
browsers: [
'Chrome',
'PhantomJS'
],
concurrency: Infinity,
reporters: [
'spec',
'coverage'
],
preprocessors: {
'lib/**/*.js': ['coverage']
},
coverageReporter: {
dir: 'coverage/',
reporters: [
{
type: 'html',
subdir: 'report'
},
{
type: 'lcovonly',
subdir: './',
file: 'coverage-front.info'
},
{
type: 'lcov',
subdir: '.'
}
]
},
browserDisconnectTimeout: 15000,
browserNoActivityTimeout: 120000,
expressHttpServer: {
port: 8092,
appVisitor: App
}
};
if (process.env.TRAVIS) {
params.browsers = [
'PhantomJS'
];
}
config.set(params);
};
| kylekatarnls/momentum | karma.conf.js | JavaScript | mit | 1,377 |
from feature import *
from pymongo import MongoClient
from bson.binary import Binary as BsonBinary
import pickle
import os
from operator import itemgetter
import time
import sys
imagelocation = "" #Input Image path
indir = "" #Directory Path
client = MongoClient('mongodb://localhost:27017')
db = client.coil #Insert your database in place of coil
col = db.images #Insert your collection in place of images
class Image(object):
"""docstring for Image"""
def __init__(self, path):
self.path = path
img = cv2.imread(self.path,0)
imgm = preprocess(img)
segm = segment(imgm)
self.glfeature = globalfeature(imgm,16)
self.llfeature = localfeature(segm)
self.numberofones = self.glfeature.sum(dtype=int)
start_time = time.time()
count = 0
for root, dirs, filenames in os.walk(indir):
for f in filenames:
i1 = Image(f)
count = count+1
perc = (count/360) * 100
sys.stdout.write("\r%d%%" % perc)
sys.stdout.flush()
new_posts = [{'path': i1.path,
'llfeature': BsonBinary(pickle.dumps(i1.llfeature,protocol=2)),
'glfeature': BsonBinary(pickle.dumps(i1.glfeature,protocol=2)),
'numberofones' : int(i1.numberofones)}]
post_id = col.insert(new_posts)
# print(post_id)
img = Image(imagelocation)
count = 0
maxglosim = 0
maxlocsim = 0
maximum = 0
gridmax=0
vectormax=0
for f in col.find():
llfeature = pickle.loads(f['llfeature'])
glfeature = pickle.loads(f['glfeature'])
count = count+1
perc = (count/360) * 100
sys.stdout.write("\r%d%%" % perc)
sys.stdout.flush()
locsim = np.absolute((llfeature-img.llfeature).sum())
glosim = np.logical_xor(glfeature,img.glfeature).sum()
distance = locsim+glosim
if(glosim>maxglosim):
gridmax = glfeature
maxglosim=glosim
if(locsim>maxlocsim):
maxlocsim=locsim
vectormax = llfeature
if(distance>maximum):
vectmostdif= llfeature
gridmostdif = glfeature
maximum = distance
maxilocsim = np.absolute((vectormax-img.llfeature).sum())
maxiglosim = np.logical_xor(gridmax,img.glfeature).sum()
processed_time = time.time()
print("\nTotal Processing Time : {0:.2f} seconds".format(processed_time-start_time))
def gloDist(gridA,gridB):
glosim = np.logical_xor(gridA,gridB).sum()
return glosim/maxiglosim
def locDist(vectorA,vectorB):
locsim = np.absolute((vectorA-vectorB).sum())
return locsim/maxilocsim
ranking = []
count = 0
print("\nSearching:")
for f in col.find():
llfeature = pickle.loads(f['llfeature'])
glfeature = pickle.loads(f['glfeature'])
count = count+1
perc = (count/360) * 100
sys.stdout.write("\r%d%%" % perc)
sys.stdout.flush()
g1 = gloDist(glfeature,img.glfeature)
l1 = locDist(llfeature,img.llfeature)
sim = ((2-(g1+l1))/2)*100
ranking.append([sim,f['path']])
search_time = time.time()
print("\nTotal Searching Time : {0:.2f} seconds".format(search_time-processed_time))
print("\nTotal Time : {0:.2f} seconds".format(search_time-start_time))
ranking = sorted(ranking, key=itemgetter(0),reverse=True)
#Ranking : Results in a list
| devashishp/Content-Based-Image-Retrieval | optimized.py | Python | mit | 3,209 |
package com.pandu.remotemouse;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Help extends Dialog{
public Help(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
setTitle("Help");
Button but = (Button) findViewById(R.id.bCloseDialog);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
dismiss();
}
});
}
}
| pandu1990/AndroidRemote | src/com/pandu/remotemouse/Help.java | Java | mit | 750 |
<?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014-2015 Elcodi.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Admin\PluginBundle\Controller;
use Mmoreram\ControllerExtraBundle\Annotation\JsonResponse;
use RuntimeException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Elcodi\Admin\CoreBundle\Controller\Abstracts\AbstractAdminController;
use Elcodi\Component\Plugin\Entity\Plugin;
use Elcodi\Component\Plugin\Form\Type\PluginType;
use Elcodi\Component\Plugin\PluginTypes;
/**
* Class Controller for Plugins
*
* @Route(
* path = "/plugin",
* )
*/
class PluginController extends AbstractAdminController
{
/**
* List plugins
*
* @param string $category Optional plugin category
*
* @return array Result
*
* @Route(
* path = "s",
* name = "admin_plugin_list",
* methods = {"GET"}
* )
*
* @Route(
* path = "s/{category}",
* name = "admin_plugin_categorized_list",
* methods = {"GET"}
* )
*
* @Template
*/
public function listAction($category = null)
{
$criteria = [
'type' => PluginTypes::TYPE_PLUGIN,
];
if ($category !== null) {
$criteria['category'] = $category;
}
$plugins = $this
->get('elcodi.repository.plugin')
->findBy(
$criteria,
[ 'category' => 'ASC' ]
);
return [
'plugins' => $plugins,
'category' => $category,
];
}
/**
* Configure plugin
*
* @param Request $request Request
* @param string $pluginHash Plugin hash
*
* @return array Result
*
* @throws RuntimeException Plugin not available for configuration
*
* @Route(
* path = "/{pluginHash}",
* name = "admin_plugin_configure",
* methods = {"GET", "POST"}
* )
* @Template
*/
public function configureAction(
Request $request,
$pluginHash
) {
/**
* @var Plugin $plugin
*/
$plugin = $this
->get('elcodi.repository.plugin')
->findOneBy([
'hash' => $pluginHash,
]);
$form = $this
->createForm(
new PluginType($plugin),
$plugin->getFieldValues()
);
if ($request->isMethod(Request::METHOD_POST)) {
$form->handleRequest($request);
$pluginValues = $form->getData();
$plugin->setFieldValues($pluginValues);
$this
->get('elcodi.object_manager.plugin')
->flush($plugin);
$this->addFlash(
'success',
$this
->get('translator')
->trans('admin.plugin.saved')
);
return $this
->redirectToRoute('admin_plugin_configure', [
'pluginHash' => $plugin->getHash(),
]);
}
return [
'form' => $form->createView(),
'plugin' => $plugin,
];
}
/**
* Enable/Disable plugin
*
* @param Request $request Request
* @param string $pluginHash Plugin hash
*
* @return array Result
*
* @Route(
* path = "/{pluginHash}/enable",
* name = "admin_plugin_enable",
* methods = {"POST"}
* )
* @JsonResponse()
*/
public function enablePluginAction(
Request $request,
$pluginHash
) {
/**
* @var Plugin $plugin
*/
$plugin = $this
->get('elcodi.repository.plugin')
->findOneBy([
'hash' => $pluginHash,
]);
$enabled = (boolean) $request
->request
->get('value');
$plugin->setEnabled($enabled);
$this
->get('elcodi.object_manager.plugin')
->flush($plugin);
$this
->get('elcodi.manager.menu')
->removeFromCache('admin');
return [
'status' => 200,
'response' => [
$this
->get('translator')
->trans('admin.plugin.saved'),
],
];
}
/**
* Check if, given a plugin hash, a configuration page is available
*
* @param Plugin $plugin Plugin
*
* @return boolean Is available
*/
protected function isPluginConfigurable(Plugin $plugin = null)
{
return ($plugin instanceof Plugin) && $plugin->hasFields();
}
}
| deliberryeng/bamboo | src/Elcodi/Admin/PluginBundle/Controller/PluginController.php | PHP | mit | 5,157 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// 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.
//
//*********************************************************
namespace CompositionSampleGallery
{
public sealed partial class ShadowInterop : SamplePage
{
public ShadowInterop()
{
this.InitializeComponent();
}
public static string StaticSampleName { get { return "Shadow Interop"; } }
public override string SampleName { get { return StaticSampleName; } }
public override string SampleDescription { get { return "Demonstrates how to apply drop shadows to Xaml elements."; } }
public override string SampleCodeUri { get { return "http://go.microsoft.com/fwlink/p/?LinkID=761171"; } }
}
}
| clarkezone/composition | SampleGallery/Samples/SDK 14393/ShadowInterop/ShadowInterop.cs | C# | mit | 1,374 |
"use strict";
// Controller
function Avatar(app, req, res) {
// HTTP action
this.action = (params) => {
app.sendFile(res, './storage/users/' + params[0] + '/' + params[1]);
};
};
module.exports = Avatar; | taviroquai/NodeVueBootstrapDemo | app/controller/Avatar.js | JavaScript | mit | 240 |
<?php
namespace Models;
/**
* Class Candidate
* @package Models
*
* @Source("candidates")
*
*/
class Candidate extends \Phalcon\Mvc\Model
{
/**
* @Id
* @Identity
* @GeneratedValue
* @Primary
* @Column(type="integer")
* @var integer
*/
public $id;
/**
* @Column(column="pib", type="string")
* @var string
*/
public $pib;
/**
* @Column(column="birthDate", type="timestamp")
* @var string
*/
public $birthDate;
/**
* @Column(name="maritalStatus", type="enum")
* @var string
*/
public $maritalStatus;
/**
* @Column(name="cityId", type="integer")
* @var string
*/
public $cityId;
/**
* @Column(name="educationId", type="integer")
* @var string
*/
public $educationId;
/**
* @Column(name="phoneMobile", type="string", length=200)
* @var string
*/
public $phoneMobile;
/**
* @Column(name="phoneHome", type="string")
* @var string
*/
public $phoneHome;
/**
* @Column(name="email", type="string")
* @var string
*/
public $email;
/**
* @Column(name="drivingExp", type="string")
* @var string
*/
public $drivingExp;
/**
* @Column(type="$recommendations", nullable=false, name="group_id", size="11")
*/
public $recommendations;
/**
* @Column(column="changed", type="timestamp")
* @var string
*/
public $changed;
/**
* @Column(column="created", type="timestamp")
* @var string
*/
public $created;
public function getSource()
{
return "candidates";
}
}
| AC7ION/police-recruit | application/models/Candidate.php | PHP | mit | 1,696 |
"use strict";
var Response = (function () {
function Response(result, childWork) {
this.result = result;
this.childWork = childWork;
}
return Response;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Response;
//# sourceMappingURL=response.js.map | colinmathews/node-workhorse | dist/lib/models/response.js | JavaScript | mit | 313 |
require 'digest/sha1'
require 'yaml'
module SimpleCov
#
# A simplecov code coverage result, initialized from the Hash Ruby 1.9's built-in coverage
# library generates (Coverage.result).
#
class Result
# Returns the original Coverage.result used for this instance of SimpleCov::Result
attr_reader :original_result
# Returns all files that are applicable to this result (sans filters!) as instances of SimpleCov::SourceFile. Aliased as :source_files
attr_reader :files
alias_method :source_files, :files
# Explicitly set the Time this result has been created
attr_writer :created_at
# Explicitly set the command name that was used for this coverage result. Defaults to SimpleCov.command_name
attr_writer :command_name
# Initialize a new SimpleCov::Result from given Coverage.result (a Hash of filenames each containing an array of
# coverage data)
def initialize(original_result)
@original_result = original_result.freeze
@files = original_result.map {|filename, coverage| SimpleCov::SourceFile.new(filename, coverage)}.sort_by(&:filename)
filter!
end
# Returns all filenames for source files contained in this result
def filenames
files.map(&:filename)
end
# Returns a Hash of groups for this result. Define groups using SimpleCov.add_group 'Models', 'app/models'
def groups
@groups ||= SimpleCov.grouped(files)
end
# The overall percentual coverage for this result
def covered_percent
missed_lines, covered_lines = 0, 0
@files.each do |file|
original_result[file.filename].each do |line_result|
case line_result
when 0
missed_lines += 1
when 1
covered_lines += 1
end
end
end
total = (missed_lines + covered_lines)
if total.zero?
0
else
100.0 * covered_lines / total
end
end
# Applies the configured SimpleCov.formatter on this result
def format!
SimpleCov.formatter.new.format(self)
end
# Defines when this result has been created. Defaults to Time.now
def created_at
@created_at ||= Time.now
end
# The command name that launched this result.
# Retrieved from SimpleCov.command_name
def command_name
@command_name ||= SimpleCov.command_name
end
# Returns a hash representation of this Result that can be used for marshalling it into YAML
def to_hash
{command_name => {:original_result => original_result.reject {|filename, result| !filenames.include?(filename) }, :created_at => created_at}}
end
# Returns a yaml dump of this result, which then can be reloaded using SimpleCov::Result.from_yaml
def to_yaml
to_hash.to_yaml
end
# Loads a SimpleCov::Result#to_hash dump
def self.from_hash(hash)
command_name, data = hash.first
result = SimpleCov::Result.new(data[:original_result])
result.command_name = command_name
result.created_at = data[:created_at]
result
end
# Loads a SimpleCov::Result#to_yaml dump
def self.from_yaml(yaml)
from_hash(YAML.load(yaml))
end
private
# Applies all configured SimpleCov filters on this result's source files
def filter!
@files = SimpleCov.filtered(files)
end
end
end
| bborn/simplecov | lib/simplecov/result.rb | Ruby | mit | 3,418 |
'use strict';
import Application from '../../core/Application.js';
import Action from '../../core/Action.js';
describe('Action', () => {
var app;
var action;
class ChildAction extends Action {
get name() {
return 'ChildAction';
}
}
beforeEach(() => {
app = new Application();
action = new ChildAction(app);
});
it('has to be defined, be a function and can be instantiated', () => {
expect(ChildAction).toBeDefined();
expect(ChildAction).toEqual(jasmine.any(Function));
expect(action instanceof ChildAction).toBe(true);
});
it('holds an app instance', () => {
var myApp = action.app;
expect(myApp).toEqual(jasmine.any(Application));
expect(myApp).toBe(app);
});
it('has an execute function that throws an error if it is not implemented', () => {
expect(action.execute).toEqual(jasmine.any(Function));
expect(() => action.execute(payload)).toThrow();
});
}); | m4n3z40/fluxone | __tests__/core/Action-test.js | JavaScript | mit | 1,021 |
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
puts "There are #{cars} available."
puts "There are only #{drivers} available."
puts "There will be #{cars_not_driven} empty cars today."
puts "We can transport #{carpool_capacity} today."
puts "We have #{passengers} to carpool today."
puts "We need to put about #{average_passengers_per_car} in each car."
| joeryan/rubyhardway | ex4.rb | Ruby | mit | 527 |
namespace _3.RefactorLoop
{
using System;
class RefactorLoop
{
static void Main()
{
int[] array = new int[100];
int expectedValue = 666; // It's not necessary to be 666 :)
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
if (i % 10 == 0)
{
if (array[i] == expectedValue)
{
Console.WriteLine("Value Found");
}
}
}
}
}
}
| 2She2/HighQualityProgrammingCode | 07.UsingControlStructuresStatementsAndLoops/3.RefactorLoop/RefactorLoop.cs | C# | mit | 594 |
$(document).ready(function() {
$('#mostrar_menu').click(function() {
$('#sidebar-wrapper').toggle(300);
});
});
| AnaClaudiaConde/teste-lazyphp | template/vertical/menu.js | JavaScript | mit | 135 |
<?php
/*
* This file is part of Okatea.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
$GLOBALS['okt_l10n']['m_contact_recipients'] = 'Destinataires';
$GLOBALS['okt_l10n']['m_contact_recipients_email_address_$s_is_invalid'] = 'L’adresse électronique "%s" est invalide.';
$GLOBALS['okt_l10n']['m_contact_recipients_page_description'] = 'Cette page permet de gérer les destinataires de la page contact.';
$GLOBALS['okt_l10n']['m_contact_recipients_default_recipient_%s'] = 'Si vous n’utilisez pas cette page, le destinataire sera celui du site : %s.';
$GLOBALS['okt_l10n']['m_contact_recipients_copy_hidden_copy'] = 'En plus des destinataires vous pouvez ajouter des destinataires en copie, ainsi que des destinataires en copie cachée.';
$GLOBALS['okt_l10n']['m_contact_recipients_howto_delete_recipent'] = 'Pour supprimer un destinataire, supprimez son adresse.';
$GLOBALS['okt_l10n']['m_contact_recipients_recipient_%s'] = 'Destinataire %s';
$GLOBALS['okt_l10n']['m_contact_recipients_add_recipient'] = 'Ajouter un destinataire';
$GLOBALS['okt_l10n']['m_contact_recipients_copy'] = 'Destinataires en copie';
$GLOBALS['okt_l10n']['m_contact_recipients_copy_%s'] = 'Destinataire %s en copie';
$GLOBALS['okt_l10n']['m_contact_recipients_add_copy'] = 'Ajouter un destinataire en copie';
$GLOBALS['okt_l10n']['m_contact_recipients_hidden_copy'] = 'Destinataires en copie cachée';
$GLOBALS['okt_l10n']['m_contact_recipients_hidden_copy_%s'] = 'Destinataire %s en copie cachée';
$GLOBALS['okt_l10n']['m_contact_recipients_add_hidden_copy'] = 'Ajouter un destinataire en copie cachée';
| forxer/okatea | Okatea/Modules/Contact/Locales/fr/admin.recipients.lang.php | PHP | mit | 1,681 |
const { app, BrowserWindow } = require('electron');
const {ipcMain} = require('electron');
// shared to-do list data
global.sharedData = {
itemList: [
{
id: 0,
text: "First meet up with David Lau on 5th July",
isCompleted: true
},
{
id: 1,
text: "David Bewick meet with David Lau on Monday",
isCompleted: true
},
{
id: 2,
text: "David Lau to speak with Kaspar on Wednesday",
isCompleted: false
}
],
itemLatestID: 2
};
// electron main process
app.on('ready', () => {
const numOfWindows = 3; // number of windows, can grow dynamically
var windows = [];
for(var i = 0; i < numOfWindows; i++){
const win = new BrowserWindow({
width: 800,
height: 600,
show: true,
});
win.loadURL(`file://${__dirname}/dist/index.html`);
// win.openDevTools();
windows.push(win);
}
ipcMain.on('item-list-update', () => {
windows.forEach((win) => {
win.webContents.send('refresh-item-data');
});
});
});
| davidlau325/bh-todo-list | main.js | JavaScript | mit | 1,183 |
function generalAttack(attacker, receiver, weaponBonus){
//Weapon bonus of one means attacker gets bonus, 0 = neutral, and -1 = penalty
if(attacker.attack > receiver.defense){
if(weaponBonus == 1){
receiver.health = receiver.health - ((attacker.attack + 2) - receiver.defense);
}else if(weaponBonus == -1){
receiver.health = receiver.health - ((attacker.attack - 2) - receiver.defense);
}else{
receiver.health = receiver.health - (attacker.attack - receiver.defense);
}
}else {
receiver.health -= 2;
}
}
function death(){
console.log("should be dead");
hero.alive = false;
}
// Global variables, we're all going to hell
var healthPlaceholder = 0;
var damageTaken = 0;
var totalDamageDealt = 0;
var totalDamageTaken = 0;
var totalKills = 0;
var totalTurns = 0;
function wolvesAttack() {
var wolf = new Character();
wolf.health = 30;
wolf.attack = 5;
wolf.defense = 5;
while(wolf.health > 0 && hero.health > 0)
{
var chance = Math.floor((Math.random() * 100) + 1);
if(chance < 20){
print_to_path(hero.name + " currently has " + hero.health + " health");
healthPlaceholder = hero.health;
generalAttack(wolf, hero);
damageTaken = healthPlaceholder - hero.health;
totalDamageTaken += damageTaken;
if(chance % 2 == 0){
print_to_path("A wolf runs up and bites "+hero.name+" for " + damageTaken + " damage");
}else{
print_to_path("A wolf claww "+hero.name+" for " + damageTaken + " damage");
}
}
else {
healthPlaceholder = wolf.health;
generalAttack(hero, wolf,0);
totalDamageDealt += (healthPlaceholder - wolf.health);
print_to_path(hero.name+" attacks the wolf!");
print_to_path("The wolf's health falls to "+wolf.health);
}
totalTurns += 1;
}
if(wolf.health <= 0){
console.log("wolf dead");
totalKills += 1;
}
if(hero.health<= 0){
death();
}
}
function banditsAttack() {
var bandit = new Character();
bandit.health = 40;
bandit.attack = 10;
bandit.defense = 5;
while(bandit.health > 0 && hero.health > 0)
{
var chance = Math.floor((Math.random() * 100) + 1);
if(chance < 30){
print_to_path(hero.name + " currently has " + hero.health + " health");
healthPlaceholder = hero.health;
generalAttack(bandit, hero);
damageTaken = healthPlaceholder - hero.health;
totalDamageTaken += damageTaken;
if(chance % 2 == 0){
print_to_path("A clan of bandits knocks "+hero.name+" to the ground dealing " + damageTaken + " Damage");
}else{
print_to_path("A bandit Seaks up from behind stabbs "+hero.name+" dealing " + damageTaken + " Damage");
}
}
else {
healthPlaceholder = bandit.health;
if(hero.weapon == "Sword"){
generalAttack(hero, bandit,1);
}else if(hero.weapon == "Bow"){
generalAttack(hero, bandit,-1);
}else{
generalAttack(hero, bandit,0);
}
totalDamageDealt += (healthPlaceholder - bandit.health);
print_to_path(hero.name+" attacks a bandit!");
print_to_path("The bandit's health falls to "+bandit.health);
}
totalTurns += 1;
}
if(bandit.health <= 0){
console.log("bandit dead");
totalKills += 1;
}
if(hero.health<= 0){
death();
}
}
function trollsAttack() {
var troll = new Character();
troll.health = 50;
troll.attack = 25;
troll.defense = 15;
while(troll.health > 0 && hero.health > 0)
{
var chance = Math.floor((Math.random() * 100) + 1);
if(chance < 35){
print_to_path(hero.name + " currently has " + hero.health + " health");
healthPlaceholder = hero.health;
generalAttack(troll, hero);
damageTaken = healthPlaceholder - hero.health;
totalDamageTaken += damageTaken;
if(chance % 2 == 0){
print_to_path("A troll throws a small axe at "+hero.name+" dealing " + damageTaken + " damage");
}else{
print_to_path("A troll smashes "+hero.name+" with his club for " + damageTaken + " damage");
}
}
else {
healthPlaceholder = troll.health;
generalAttack(hero, troll);
totalDamageDealt += (healthPlaceholder - troll.health);
print_to_path(hero.name+" attacks the troll!");
print_to_path("The troll's health falls to "+troll.health);
}
totalTurns += 1;
}
if(troll.health <= 0){
console.log("troll dead");
totalKills += 1;
}
if(hero.health<= 0){
death();
}
}
function golemsAttack() {
var golem = new Character();
golem.health = 60;
golem.attack = 10;
golem.defense = 50;
while(golem.health > 0 && hero.health > 0)
{
var chance = Math.floor((Math.random() * 100) + 1);
if(chance < 20){
print_to_path(hero.name + " currently has " + hero.health + " health");
healthPlaceholder = hero.health;
generalAttack(golem, hero);
damageTaken = healthPlaceholder - hero.health;
totalDamageTaken += damageTaken;
if(chance % 2 == 0){
print_to_path("A golem flails its arms, smashing "+hero.name+" into the ground, dealing " + damageTaken + " damage");
}else{
print_to_path("A golem stomps its foot on the ground causing rocks to fall on "+hero.name+" from the nearby mountain. dealing " + damageTaken + " Damage");
}
}
else {
healthPlaceholder = golem.health;
if(hero.weapon == "Mace"){
generalAttack(hero, golem,1);
}else if(hero.weapon == "Sword"){
generalAttack(hero, golem,-1);
}else{
generalAttack(hero, golem,0);
}
totalDamageDealt += (healthPlaceholder - golem.health);
print_to_path(hero.name+" attacks the golem!");
print_to_path("The golem's health falls to "+golem.health);
}
totalTurns += 1;
}
if(golem.health <= 0){
console.log("golem dead");
totalKills += 1;
}
if(hero.health<= 0){
death();
}
}
function dragonAttack() {
// atk 30
var dragon = new Character();
dragon.health = 60;
dragon.attack = 30;
dragon.defense = 30;
while(dragon.health > 0 && hero.health > 0)
{
var chance = Math.floor((Math.random() * 100) + 1);
if(chance < 20){
print_to_path(hero.name + " currently has " + hero.health + " health");
healthPlaceholder = hero.health;
generalAttack(dragon, hero);
damageTaken = healthPlaceholder - hero.health;
totalDamageTaken += damageTaken;
if(chance % 2 == 0){
print_to_path("A dragon breaths green flames at "+hero.name+" which inflicted a burn, dealing " + damageTaken + " damage");
}else{
print_to_path("A dragon wipes its tail along the floor flinging "+hero.name+" into the wall, dealing " + damageTaken + " damage");
}
}
else {
healthPlaceholder = dragon.health;
if(hero.weapon == "Bow"){
generalAttack(hero, dragon,1);
}else if(hero.weapon == "Mace"){
generalAttack(hero, dragon,-1);
}else{
generalAttack(hero, dragon,0);
}
totalDamageDealt += (healthPlaceholder - dragon.health);
print_to_path(hero.name+" attacks the dragon!");
print_to_path("The dragon's health falls to: "+dragon.health);
}
totalTurns += 1;
}
if(dragon.health <= 0){
console.log("dragon dead");
totalKills += 1;
}
if(hero.health<= 0){
death();
}
}
function blackSquirrelAttacks() {
// I has no Tail D:
}
function statistics() {
print_to_path("<b>Score:</b>");
print_to_path("Total kills: " + totalKills + " | " +
"Total turns: " + totalTurns + " | " +
"Total damage dealt: " + totalDamageDealt + " | " +
"Total damage taken: " + totalDamageTaken
);
}
| YSUatKHE14/zeroPlayerGame | js/pathFunctions.js | JavaScript | mit | 7,261 |
package ro.ubb.samples.structural.facade.point;
public class Client {
public static void main(String[] args) {
// 3. Client uses the Facade
Line lineA = new Line(new Point(2, 4), new Point(5, 7));
lineA.move(-2, -4);
System.out.println( "after move: " + lineA );
lineA.rotate(45);
System.out.println( "after rotate: " + lineA );
Line lineB = new Line( new Point(2, 1), new Point(2.866, 1.5));
lineB.rotate(30);
System.out.println("30 degrees to 60 degrees: " + lineB);
}
}
| bmariesan/iStudent | src/main/java/ro/ubb/samples/structural/facade/point/Client.java | Java | mit | 558 |
# encoding: utf-8
# xreq_xrep_poll.rb
#
# It illustrates the use of xs_poll(), as wrapped by the Ruby library,
# for detecting and responding to read and write events recorded on sockets.
# It also shows how to use XS::NO_BLOCK/XS::DONTWAIT for non-blocking send
# and receive.
require File.join(File.dirname(__FILE__), '..', 'lib', 'ffi-rxs')
def assert(rc)
raise "Last API call failed at #{caller(1)}" unless rc >= 0
end
link = "tcp://127.0.0.1:5555"
begin
ctx = XS::Context.new
s1 = ctx.socket(XS::XREQ)
s2 = ctx.socket(XS::XREP)
rescue ContextError => e
STDERR.puts "Failed to allocate context or socket"
raise
end
s1.identity = 'socket1.xreq'
s2.identity = 'socket2.xrep'
assert(s1.setsockopt(XS::LINGER, 100))
assert(s2.setsockopt(XS::LINGER, 100))
assert(s1.bind(link))
assert(s2.connect(link))
poller = XS::Poller.new
poller.register_readable(s2)
poller.register_writable(s1)
start_time = Time.now
@unsent = true
until @done do
assert(poller.poll_nonblock)
# send the message after 5 seconds
if Time.now - start_time > 5 && @unsent
puts "sending payload nonblocking"
5.times do |i|
payload = "#{ i.to_s * 40 }"
assert(s1.send_string(payload, XS::NonBlocking))
end
@unsent = false
end
# check for messages after 1 second
if Time.now - start_time > 1
poller.readables.each do |sock|
if sock.identity =~ /xrep/
routing_info = ''
assert(sock.recv_string(routing_info, XS::NonBlocking))
puts "routing_info received [#{routing_info}] on socket.identity [#{sock.identity}]"
else
routing_info = nil
received_msg = ''
assert(sock.recv_string(received_msg, XS::NonBlocking))
# skip to the next iteration if received_msg is nil; that means we got an EAGAIN
next unless received_msg
puts "message received [#{received_msg}] on socket.identity [#{sock.identity}]"
end
while sock.more_parts? do
received_msg = ''
assert(sock.recv_string(received_msg, XS::NonBlocking))
puts "message received [#{received_msg}]"
end
puts "kick back a reply"
assert(sock.send_string(routing_info, XS::SNDMORE | XS::NonBlocking)) if routing_info
time = Time.now.strftime "%Y-%m-%dT%H:%M:%S.#{Time.now.usec}"
reply = "reply " + sock.identity.upcase + " #{time}"
puts "sent reply [#{reply}], #{time}"
assert(sock.send_string(reply))
@done = true
poller.register_readable(s1)
end
end
end
puts "executed in [#{Time.now - start_time}] seconds"
assert(s1.close)
assert(s2.close)
ctx.terminate
| celldee/ffi-rxs | examples/xreq_xrep_poll.rb | Ruby | mit | 2,621 |
var draw = SVG('mainPage');
var energyBar = draw.rect(0,5).move(0,598)
.fill({ color: '#cc0', opacity: '1' })
.stroke({ color: '#fff', width: '1', opacity: '0.6'});
var port = 25550;
var images = "http://"+document.location.hostname+":"+port+"/game/images/";
var localPlayers = new Array();
var localBullets = new Array();
var localBonus = new Array();
var bonusBars = new Array();
function PlayerEntity(mark, text) {
this.mark = mark;
this.text = text;
}
// Gestion des joueurs
socket.on('refreshPlayers', function (players) {
for(var i in players) {
// Création des nouveaux joueurs
if(typeof(localPlayers[i]) === "undefined") {
var ownColor = '#fff';
if(players[i].id == socket.socket.sessionid) {
// Attribution d'un marqueur de couleur pour le joueur en cours
ownColor = '#c00';
}
// Création des éléments
var circle = draw.circle(6).move(players[i].x,players[i].y)
.fill({ color: ownColor, opacity: '1' })
.stroke({ color: '#fff', width: '1' });
var text = draw.text(players[i].pseudo).font({ size: 12 })
.fill({ color: '#fff', opacity: '0.6' })
.stroke({ color: '#fff', width: '1', opacity: '0.4'});
// Déplacement du texte au dessus du marqueur
text.move(players[i].x - text.bbox().width /2, players[i].y - text.bbox().height - 10);
// Ajout de l'entité au tableau
localPlayers[i] = new PlayerEntity(circle, text);
}
else {
// Déplacement du joueur
localPlayers[i].mark.move(players[i].x, players[i].y);
localPlayers[i].text.move(players[i].x - localPlayers[i].text.bbox().width /2, players[i].y - localPlayers[i].text.bbox().height - 10);
// Actualisation du joueur local
if(players[i].id == socket.socket.sessionid) {
// Affichage du bouton au bon endroit en fonction du mode
if(players[i].spec == false) {
document.getElementById("b1").style.display = "none";
document.getElementById("b2").style.display = "block";
}
else {
document.getElementById("b2").style.display = "none";
document.getElementById("b1").style.display = "block";
}
// Actualisation de la barre d'énergie
if (players[i].energy > 1)
{ energyBar.width(((players[i].energy-1)/100)*800); }
else
{ energyBar.width(0); }
// Actualisation des barres de bonus
for(var j in bonusBars) {
switch(bonusBars[j].name) {
case "speed":
bonusBars[j].bar.width(players[i].bSpeed);
break;
case "arrow":
bonusBars[j].bar.width(players[i].bArrow);
break;
}
}
}
}
}
});
// Passage en spectateur
function _setSpec() {
socket.emit('setSpec', 1);
}
// Ajout d'une barre de bonus
socket.on('newPlayerBonus', function (bonus) {
// Vérification de la non existence de la barre
for(var i in bonusBars) {
if(bonusBars[i].name == bonus.name) {
return;
}
}
var rect = draw.rect(0,12).move(0,15*(bonusBars.length+1))
.fill({ color: bonus.color, opacity: '0.4' });
bonusBars.push({name: bonus.name, bar: rect});
});
// Rerait d'un joueur
socket.on('removePlayer', function (id) {
localPlayers[id].mark.remove(); localPlayers[id].text.remove();
localPlayers.splice(id,1);
});
// Affichage d'un bonus
socket.on('displayBonus', function (bonus) {
for(var i in bonus) {
// Création des nouveaux bonus
if(typeof(localBonus[i]) === "undefined") {
localBonus[i] = draw.image(images+""+bonus[i].image+".png")
.move(bonus[i].x,bonus[i].y);
}
}
});
// Retrait d'un bonus
socket.on('removeBonus', function (bonusID) {
if (bonusID == -1) {
for(var i in localBonus) {
localBonus[i].remove();
}
localBonus = [];
}
else {
localBonus[bonusID].remove();
localBonus.splice(bonusID,1);
}
});
// Rafraichissement du tableau de scores
socket.on('refreshScores', function (players) {
// Arrangement du tableau en fonction des scores
players = players.sort(function(a,b) {
return a.points > b.points;
}).reverse();
// Formattage de la liste des joueurs
var list = "<b>Joueurs en ligne : </b><br />";
var listSpec = "<b>Spectateurs : </b><br />";
for(var i in players) {
if(players[i].spec == 0) {
if(players[i].alive == 0) {
list = list + "<span style='color:#" + players[i].color + "; float:left;'><s>" + players[i].pseudo + "</s></span><span style='float:right;'>- " + players[i].points + " points</span><br />";
} else {
list = list + "<span style='color:#" + players[i].color + "; float:left;'>" + players[i].pseudo + "</span><span style='float:right;'>- " + players[i].points + " points</span><br />";
}
}
else {
listSpec = listSpec + "<span style='color:#" + players[i].color + "; float:left;'>" + players[i].pseudo + "</span><br />";
}
}
// Mise à jour de l'affichage de la liste des joueurs
document.getElementById("scores").innerHTML = list;
document.getElementById("specs").innerHTML = listSpec;
});
// Ajout des nouvelles balles contenues dans le buffer
var max = 0;
socket.on('refreshBullets', function (bulletTable) {
for(var i in bulletTable) {
// Création des traces
var length = max + i;
if(typeof(localBullets[length]) === "undefined") {
localBullets[length] = draw.circle(5/*heignt line*/)
.move(bulletTable[i].x,bulletTable[i].y)
.fill({ color:'#'+bulletTable[i].color })
.stroke({ color: '#fff', width: '1', opacity: '0.5' });
max++;
}
}
});
// Réinitialisation du terrain
socket.on('resetGround', function (e) {
for(var i in localBullets) {
localBullets[i].remove();
}
localBullets = [];
});
// Arret du serveur
socket.on('stopServer', function (e) {
window.location.replace("http://"+document.location.hostname+"/?alert=1");
});
// Kick du joueur
socket.on('kickPlayer', function (e) {
window.location.replace("http://"+document.location.hostname+"/?kick=1");
});
// Gestion d'un nouveau message
socket.on('newMessage', function (e) {
var tmp = document.getElementById("comments").innerHTML;
document.getElementById("comments").innerHTML = "<b>"+e.pseudo+" : </b>"+e.message+"<br />"+tmp;
});
// Affichage d'une alerte
socket.on('displayAlert', function(text, color, duration) {
if(color == '') {
color = "#fff";
}
if(duration == '') {
duration = 1000;
}
var appear, disappear, deleteAlert,
alert = draw.text(text).font({ size: 36 });
appear = function() {
alert.move(400-(alert.bbox().width / 2), 100)
.fill({ color: color, opacity: '0' })
.animate(100).fill({ opacity: '1' })
.after(disappear);
};
disappear = function() {
setTimeout(function() {
alert.animate(500).fill({ opacity: '0' }).after(deleteAlert);
}, duration);
};
deleteAlert = function() {
alert.remove();
}
appear();
});
// Affichage d'une victoire
socket.on('displayVictory', function(pseudo) {
var appear, disappear, deleteAlert,
alert = draw.text("Victoire de "+pseudo+" !").font({ size: 20 });
appear = function() {
alert.move(400-(alert.bbox().width / 2), 50)
.fill({ color: '#fff', opacity: '0' })
.animate(100).fill({ opacity: '1' })
.after(disappear);
};
disappear = function() {
setTimeout(function() {
alert.animate(500).fill({ opacity: '0' }).after(deleteAlert);
}, 1000);
};
deleteAlert = function() {
alert.remove();
}
appear();
}); | wardensfx/E-Tron | game/scripts/events.js | JavaScript | mit | 7,363 |
goog.provide('gmf.DisplayquerygridController');
goog.provide('gmf.displayquerygridDirective');
goog.require('gmf');
goog.require('ngeo.CsvDownload');
goog.require('ngeo.GridConfig');
/** @suppress {extraRequire} */
goog.require('ngeo.gridDirective');
goog.require('ngeo.FeatureOverlay');
goog.require('ngeo.FeatureOverlayMgr');
goog.require('ol.Collection');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');
ngeo.module.value('gmfDisplayquerygridTemplateUrl',
/**
* @param {angular.JQLite} element Element.
* @param {angular.Attributes} attrs Attributes.
* @return {string} Template.
*/
function(element, attrs) {
var templateUrl = attrs['gmfDisplayquerygridTemplateurl'];
return templateUrl !== undefined ? templateUrl :
gmf.baseTemplateUrl + '/displayquerygrid.html';
});
/**
* Provides a directive to display results of the {@link ngeo.queryResult} in a
* grid and shows related features on the map using
* the {@link ngeo.FeatureOverlayMgr}.
*
* You can override the default directive's template by setting the
* value `gmfDisplayquerygridTemplateUrl`.
*
* Features displayed on the map use a default style but you can override these
* styles by passing ol.style.Style objects as attributes of this directive.
*
* Example:
*
* <gmf-displayquerygrid
* gmf-displayquerygrid-map="ctrl.map"
* gmf-displayquerygrid-featuresstyle="ctrl.styleForAllFeatures"
* gmf-displayquerygrid-selectedfeaturestyle="ctrl.styleForTheCurrentFeature">
* </gmf-displayquerygrid>
*
* @htmlAttribute {boolean} gmf-displayquerygrid-active The active state of the component.
* @htmlAttribute {ol.style.Style} gmf-displayquerygrid-featuresstyle A style
* object for all features from the result of the query.
* @htmlAttribute {ol.style.Style} gmf-displayquerygrid-selectedfeaturestyle A style
* object for the currently selected features.
* @htmlAttribute {ol.Map} gmf-displayquerygrid-map The map.
* @htmlAttribute {boolean?} gmf-displayquerygrid-removeemptycolumns Optional. Should
* empty columns be hidden? Default: `false`.
* @htmlAttribute {number?} gmf-displayquerygrid-maxrecenterzoom Optional. Maximum
* zoom-level to use when zooming to selected features.
* @htmlAttribute {gmfx.GridMergeTabs?} gmf-displayquerygrid-gridmergetabas Optional.
* Configuration to merge grids with the same attributes into a single grid.
* @param {string} gmfDisplayquerygridTemplateUrl URL to a template.
* @return {angular.Directive} Directive Definition Object.
* @ngInject
* @ngdoc directive
* @ngname gmfDisplayquerygrid
*/
gmf.displayquerygridDirective = function(
gmfDisplayquerygridTemplateUrl) {
return {
bindToController: true,
controller: 'GmfDisplayquerygridController',
controllerAs: 'ctrl',
templateUrl: gmfDisplayquerygridTemplateUrl,
replace: true,
restrict: 'E',
scope: {
'active': '=gmfDisplayquerygridActive',
'featuresStyleFn': '&gmfDisplayquerygridFeaturesstyle',
'selectedFeatureStyleFn': '&gmfDisplayquerygridSourceselectedfeaturestyle',
'getMapFn': '&gmfDisplayquerygridMap',
'removeEmptyColumnsFn': '&?gmfDisplayquerygridRemoveemptycolumns',
'maxResultsFn': '&?gmfDisplayquerygridMaxresults',
'maxRecenterZoomFn': '&?gmfDisplayquerygridMaxrecenterzoom',
'mergeTabsFn': '&?gmfDisplayquerygridMergetabs'
}
};
};
gmf.module.directive('gmfDisplayquerygrid', gmf.displayquerygridDirective);
/**
* Controller for the query grid.
*
* @param {!angular.Scope} $scope Angular scope.
* @param {ngeox.QueryResult} ngeoQueryResult ngeo query result.
* @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr The ngeo feature
* overlay manager service.
* @param {angular.$timeout} $timeout Angular timeout service.
* @param {ngeo.CsvDownload} ngeoCsvDownload CSV download service.
* @param {ngeo.Query} ngeoQuery Query service.
* @param {angular.JQLite} $element Element.
* @constructor
* @export
* @ngInject
* @ngdoc Controller
* @ngname GmfDisplayquerygridController
*/
gmf.DisplayquerygridController = function($scope, ngeoQueryResult,
ngeoFeatureOverlayMgr, $timeout, ngeoCsvDownload, ngeoQuery, $element) {
/**
* @type {!angular.Scope}
* @private
*/
this.$scope_ = $scope;
/**
* @type {angular.$timeout}
* @private
*/
this.$timeout_ = $timeout;
/**
* @type {ngeox.QueryResult}
* @export
*/
this.ngeoQueryResult = ngeoQueryResult;
/**
* @type {ngeo.CsvDownload}
* @private
*/
this.ngeoCsvDownload_ = ngeoCsvDownload;
/**
* @type {angular.JQLite}
* @private
*/
this.$element_ = $element;
/**
* @type {number}
* @export
*/
this.maxResults = ngeoQuery.getLimit();
/**
* @type {boolean}
* @export
*/
this.active = false;
/**
* @type {boolean}
* @export
*/
this.pending = false;
/**
* @type {!Object.<string, gmfx.GridSource>}
* @export
*/
this.gridSources = {};
/**
* IDs of the grid sources in the order they were loaded.
* @type {Array.<string>}
* @export
*/
this.loadedGridSources = [];
/**
* The id of the currently shown query source.
* @type {string|number|null}
* @export
*/
this.selectedTab = null;
/**
* @type {boolean}
* @private
*/
this.removeEmptyColumns_ = this['removeEmptyColumnsFn'] ?
this['removeEmptyColumnsFn']() === true : false;
/**
* @type {number|undefined}
* @export
*/
this.maxRecenterZoom = this['maxRecenterZoomFn'] ? this['maxRecenterZoomFn']() : undefined;
var mergeTabs = this['mergeTabsFn'] ? this['mergeTabsFn']() : {};
/**
* @type {!gmfx.GridMergeTabs}
* @private
*/
this.mergeTabs_ = mergeTabs ? mergeTabs : {};
/**
* A mapping between row uid and the corresponding feature for each
* source.
* @type {!Object.<string, Object.<string, ol.Feature>>}
* @private
*/
this.featuresForSources_ = {};
// Styles for displayed features (features) and selected features
// (highlightFeatures_) (user can set both styles).
/**
* @type {ol.Collection}
* @private
*/
this.features_ = new ol.Collection();
var featuresOverlay = ngeoFeatureOverlayMgr.getFeatureOverlay();
var featuresStyle = this['featuresStyleFn']();
if (featuresStyle !== undefined) {
goog.asserts.assertInstanceof(featuresStyle, ol.style.Style);
featuresOverlay.setStyle(featuresStyle);
}
featuresOverlay.setFeatures(this.features_);
/**
* @type {ngeo.FeatureOverlay}
* @private
*/
this.highlightFeatureOverlay_ = ngeoFeatureOverlayMgr.getFeatureOverlay();
/**
* @type {ol.Collection}
* @private
*/
this.highlightFeatures_ = new ol.Collection();
this.highlightFeatureOverlay_.setFeatures(this.highlightFeatures_);
var highlightFeatureStyle = this['selectedFeatureStyleFn']();
if (highlightFeatureStyle !== undefined) {
goog.asserts.assertInstanceof(highlightFeatureStyle, ol.style.Style);
} else {
var fill = new ol.style.Fill({color: [255, 0, 0, 0.6]});
var stroke = new ol.style.Stroke({color: [255, 0, 0, 1], width: 2});
highlightFeatureStyle = new ol.style.Style({
fill: fill,
image: new ol.style.Circle({fill: fill, radius: 5, stroke: stroke}),
stroke: stroke,
zIndex: 10
});
}
this.highlightFeatureOverlay_.setStyle(highlightFeatureStyle);
var map = null;
var mapFn = this['getMapFn'];
if (mapFn) {
map = mapFn();
goog.asserts.assertInstanceof(map, ol.Map);
}
/**
* @type {ol.Map}
* @private
*/
this.map_ = map;
// Watch the ngeo query result service.
this.$scope_.$watchCollection(
function() {
return ngeoQueryResult;
},
function(newQueryResult, oldQueryResult) {
if (newQueryResult !== oldQueryResult) {
this.updateData_();
}
}.bind(this));
/**
* An unregister function returned from `$scope.$watchCollection` for
* "on-select" changes (when rows are selected/unselected).
* @type {?function()}
* @private
*/
this.unregisterSelectWatcher_ = null;
};
/**
* Returns a list of grid sources in the order they were loaded.
* @export
* @return {Array.<gmfx.GridSource>} Grid sources.
*/
gmf.DisplayquerygridController.prototype.getGridSources = function() {
return this.loadedGridSources.map(function(sourceId) {
return this.gridSources[sourceId];
}.bind(this));
};
/**
* @private
*/
gmf.DisplayquerygridController.prototype.updateData_ = function() {
// close if there are no results
if (this.ngeoQueryResult.total === 0 && !this.hasOneWithTooManyResults_()) {
var oldActive = this.active;
this.clear();
if (oldActive) {
// don't close if there are pending queries
this.active = this.ngeoQueryResult.pending;
this.pending = this.ngeoQueryResult.pending;
}
return;
}
this.active = true;
this.pending = false;
var sources = this.ngeoQueryResult.sources;
// merge sources if requested
if (Object.keys(this.mergeTabs_).length > 0) {
sources = this.getMergedSources_(sources);
}
// create grids (only for source with features or with too many results)
sources.forEach(function(source) {
if (source.tooManyResults) {
this.makeGrid_(null, source);
} else {
var features = source.features;
if (features.length > 0) {
this.collectData_(source);
}
}
}.bind(this));
if (this.loadedGridSources.length == 0) {
// if no grids were created, do not show
this.active = false;
return;
}
// keep the first existing navigation tab open
if (this.selectedTab === null || !(('' + this.selectedTab) in this.gridSources)) {
// selecting the tab is done in a timeout, because otherwise in rare cases
// `ng-class` might set the `active` class on multiple tabs.
this.$timeout_(function() {
var firstSourceId = this.loadedGridSources[0];
this.selectTab(this.gridSources[firstSourceId]);
this.reflowGrid_(firstSourceId);
}.bind(this), 0);
}
};
/**
* @private
* @return {boolean} If one of the source has too many results.
*/
gmf.DisplayquerygridController.prototype.hasOneWithTooManyResults_ = function() {
return this.ngeoQueryResult.sources.some(function(source) {
return source.tooManyResults;
});
};
/**
* Returns if the given grid source is selected?
* @export
* @param {gmfx.GridSource} gridSource Grid source.
* @return {boolean} Is selected?
*/
gmf.DisplayquerygridController.prototype.isSelected = function(gridSource) {
return this.selectedTab === gridSource.source.id;
};
/**
* Try to merge the mergable sources.
* @param {Array.<ngeox.QueryResultSource>} sources Sources.
* @return {Array.<ngeox.QueryResultSource>} The merged sources.
* @private
*/
gmf.DisplayquerygridController.prototype.getMergedSources_ = function(sources) {
var allSources = [];
/** @type {Object.<string, ngeox.QueryResultSource>} */
var mergedSources = {};
sources.forEach(function(source) {
// check if this source can be merged
var mergedSource = this.getMergedSource_(source, mergedSources);
if (mergedSource === null) {
// this source should not be merged, add as is
allSources.push(source);
}
}.bind(this));
for (var mergedSourceId in mergedSources) {
allSources.push(mergedSources[mergedSourceId]);
}
return allSources;
};
/**
* Check if the given source should be merged. If so, an artificial source
* that will contain the features of all mergable sources is returned. If not,
* `null` is returned.
* @param {ngeox.QueryResultSource} source Source.
* @param {Object.<string, ngeox.QueryResultSource>} mergedSources Merged sources.
* @return {?ngeox.QueryResultSource} A merged source of null if the source should
* not be merged.
* @private
*/
gmf.DisplayquerygridController.prototype.getMergedSource_ = function(source, mergedSources) {
var mergeSourceId = null;
for (var currentMergeSourceId in this.mergeTabs_) {
var sourceIds = this.mergeTabs_[currentMergeSourceId];
var containsSource = sourceIds.some(function(sourceId) {
return sourceId == source.id;
});
if (containsSource) {
mergeSourceId = currentMergeSourceId;
break;
}
}
if (mergeSourceId === null) {
// this source should not be merged
return null;
}
/** @type {ngeox.QueryResultSource} */
var mergeSource;
if (mergeSourceId in mergedSources) {
mergeSource = mergedSources[mergeSourceId];
} else {
mergeSource = {
features: [],
id: mergeSourceId,
label: mergeSourceId,
pending: false,
queried: true,
tooManyResults: false,
totalFeatureCount: undefined
};
mergedSources[mergeSourceId] = mergeSource;
}
// add features of source to merge source
source.features.forEach(function(feature) {
mergeSource.features.push(feature);
});
// if one of the source has too many results, the resulting merged source will
// also be marked with `tooManyResults` and will not contain any features.
mergeSource.tooManyResults = mergeSource.tooManyResults || source.tooManyResults;
if (mergeSource.tooManyResults) {
mergeSource.totalFeatureCount = (mergeSource.totalFeatureCount !== undefined) ?
mergeSource.totalFeatureCount + mergeSource.features.length : mergeSource.features.length;
mergeSource.features = [];
}
if (source.totalFeatureCount !== undefined) {
mergeSource.totalFeatureCount = (mergeSource.totalFeatureCount !== undefined) ?
mergeSource.totalFeatureCount + source.totalFeatureCount : source.totalFeatureCount;
}
return mergeSource;
};
/**
* Collect all features in the queryResult object.
* @param {ngeox.QueryResultSource} source Result source.
* @private
*/
gmf.DisplayquerygridController.prototype.collectData_ = function(source) {
var features = source.features;
var allProperties = [];
var featureGeometriesNames = [];
var featuresForSource = {};
var properties, featureGeometryName;
features.forEach(function(feature) {
properties = feature.getProperties();
if (properties !== undefined) {
// Keeps distinct geometry names to remove theme later.
featureGeometryName = feature.getGeometryName();
if (featureGeometriesNames.indexOf(featureGeometryName) === -1) {
featureGeometriesNames.push(featureGeometryName);
}
allProperties.push(properties);
featuresForSource[ngeo.GridConfig.getRowUid(properties)] = feature;
}
}.bind(this));
this.cleanProperties_(allProperties, featureGeometriesNames);
if (allProperties.length > 0) {
var gridCreated = this.makeGrid_(allProperties, source);
if (gridCreated) {
this.featuresForSources_['' + source.id] = featuresForSource;
}
}
};
/**
* Remove all unwanted columns.
* @param {Array.<Object>} allProperties A row.
* @param {Array.<string>} featureGeometriesNames Geometry names.
* @private
*/
gmf.DisplayquerygridController.prototype.cleanProperties_ = function(
allProperties, featureGeometriesNames) {
allProperties.forEach(function(properties) {
featureGeometriesNames.forEach(function(featureGeometryName) {
delete properties[featureGeometryName];
});
delete properties['boundedBy'];
});
if (this.removeEmptyColumns_ === true) {
this.removeEmptyColumnsFn_(allProperties);
}
};
/**
* Remove columns that will be completely empty between each properties.
* @param {Array.<Object>} allProperties A row.
* @private
*/
gmf.DisplayquerygridController.prototype.removeEmptyColumnsFn_ = function(
allProperties) {
// Keep all keys that correspond to at least one value in a properties object.
var keysToKeep = [];
var i, key;
for (key in allProperties[0]) {
for (i = 0; i < allProperties.length; i++) {
if (allProperties[i][key] !== undefined) {
keysToKeep.push(key);
break;
}
}
}
// Get all keys that previously always refers always to an empty value.
var keyToRemove;
allProperties.forEach(function(properties) {
keyToRemove = [];
for (key in properties) {
if (keysToKeep.indexOf(key) === -1) {
keyToRemove.push(key);
}
}
// Remove these keys.
keyToRemove.forEach(function(key) {
delete properties[key];
});
});
};
/**
* @param {?Array.<Object>} data Grid rows.
* @param {ngeox.QueryResultSource} source Query source.
* @return {boolean} Returns true if a grid was created.
* @private
*/
gmf.DisplayquerygridController.prototype.makeGrid_ = function(data, source) {
var sourceId = '' + source.id;
var gridConfig = null;
if (data !== null) {
gridConfig = this.getGridConfiguration_(data);
if (gridConfig === null) {
return false;
}
}
if (this.loadedGridSources.indexOf(sourceId) == -1) {
this.loadedGridSources.push(sourceId);
}
this.gridSources[sourceId] = {
configuration: gridConfig,
source: source
};
return true;
};
/**
* @param {Array.<!Object>} data Grid rows.
* @return {?ngeo.GridConfig} Grid config.
* @private
*/
gmf.DisplayquerygridController.prototype.getGridConfiguration_ = function(
data) {
goog.asserts.assert(data.length > 0);
var columns = Object.keys(data[0]);
/** @type {Array.<ngeox.GridColumnDef>} */
var columnDefs = [];
columns.forEach(function(column) {
if (column !== 'ol_uid') {
columnDefs.push(/** @type {ngeox.GridColumnDef} */ ({
name: column
}));
}
});
if (columnDefs.length > 0) {
return new ngeo.GridConfig(data, columnDefs);
} else {
// no columns, do not show grid
return null;
}
};
/**
* Remove the current selected feature and source and remove all features
* from the map.
* @export
*/
gmf.DisplayquerygridController.prototype.clear = function() {
this.active = false;
this.pending = false;
this.gridSources = {};
this.loadedGridSources = [];
this.selectedTab = null;
this.tooManyResults = false;
this.features_.clear();
this.highlightFeatures_.clear();
this.featuresForSources_ = {};
if (this.unregisterSelectWatcher_) {
this.unregisterSelectWatcher_();
}
};
/**
* Select the tab for the given grid source.
* @param {gmfx.GridSource} gridSource Grid source.
* @export
*/
gmf.DisplayquerygridController.prototype.selectTab = function(gridSource) {
var source = gridSource.source;
this.selectedTab = source.id;
if (this.unregisterSelectWatcher_) {
this.unregisterSelectWatcher_();
this.unregisterSelectWatcher_ = null;
}
if (gridSource.configuration !== null) {
this.unregisterSelectWatcher_ = this.$scope_.$watchCollection(
function() {
return gridSource.configuration.selectedRows;
},
function(newSelected, oldSelectedRows) {
if (Object.keys(newSelected) !== Object.keys(oldSelectedRows)) {
this.onSelectionChanged_();
}
}.bind(this));
}
this.updateFeatures_(gridSource);
};
/**
* @private
* @param {string|number} sourceId Id of the source that should be refreshed.
*/
gmf.DisplayquerygridController.prototype.reflowGrid_ = function(sourceId) {
// this is a "work-around" to make sure that the grid is rendered correctly.
// when a pane is activated by setting `this.selectedTab`, the class `active`
// is not yet set on the pane. that's why the class is set manually, and
// after the pane is shown (in the next digest loop), the grid table can
// be refreshed.
var activePane = this.$element_.find('div.tab-pane#' + sourceId);
activePane.removeClass('active').addClass('active');
this.$timeout_(function() {
activePane.find('div.ngeo-grid-table-container table')['trigger']('reflow');
});
};
/**
* Called when the row selection has changed.
* @private
*/
gmf.DisplayquerygridController.prototype.onSelectionChanged_ = function() {
if (this.selectedTab === null) {
return;
}
var gridSource = this.gridSources['' + this.selectedTab];
this.updateFeatures_(gridSource);
};
/**
* @param {gmfx.GridSource} gridSource Grid source
* @private
*/
gmf.DisplayquerygridController.prototype.updateFeatures_ = function(gridSource) {
this.features_.clear();
this.highlightFeatures_.clear();
if (gridSource.configuration === null) {
return;
}
var sourceId = '' + gridSource.source.id;
var featuresForSource = this.featuresForSources_[sourceId];
var selectedRows = gridSource.configuration.selectedRows;
for (var rowId in featuresForSource) {
var feature = featuresForSource[rowId];
if (rowId in selectedRows) {
this.highlightFeatures_.push(feature);
} else {
this.features_.push(feature);
}
}
};
/**
* Get the currently shown grid source.
* @export
* @return {gmfx.GridSource|null} Grid source.
*/
gmf.DisplayquerygridController.prototype.getActiveGridSource = function() {
if (this.selectedTab === null) {
return null;
} else {
return this.gridSources['' + this.selectedTab];
}
};
/**
* Returns if a row of the currently active grid is selected?
* @export
* @return {boolean} Is one selected?
*/
gmf.DisplayquerygridController.prototype.isOneSelected = function() {
var source = this.getActiveGridSource();
if (source === null || source.configuration === null) {
return false;
} else {
return source.configuration.getSelectedCount() > 0;
}
};
/**
* Returns the number of selected rows of the currently active grid.
* @export
* @return {number} The number of selected rows.
*/
gmf.DisplayquerygridController.prototype.getSelectedRowCount = function() {
var source = this.getActiveGridSource();
if (source === null || source.configuration === null) {
return 0;
} else {
return source.configuration.getSelectedCount();
}
};
/**
* Select all rows of the currently active grid.
* @export
*/
gmf.DisplayquerygridController.prototype.selectAll = function() {
var source = this.getActiveGridSource();
if (source !== null) {
source.configuration.selectAll();
}
};
/**
* Unselect all rows of the currently active grid.
* @export
*/
gmf.DisplayquerygridController.prototype.unselectAll = function() {
var source = this.getActiveGridSource();
if (source !== null) {
source.configuration.unselectAll();
}
};
/**
* Invert the selection of the currently active grid.
* @export
*/
gmf.DisplayquerygridController.prototype.invertSelection = function() {
var source = this.getActiveGridSource();
if (source !== null) {
source.configuration.invertSelection();
}
};
/**
* Zoom to the selected features.
* @export
*/
gmf.DisplayquerygridController.prototype.zoomToSelection = function() {
var source = this.getActiveGridSource();
if (source !== null) {
var extent = ol.extent.createEmpty();
this.highlightFeatures_.forEach(function(feature) {
ol.extent.extend(extent, feature.getGeometry().getExtent());
});
var mapSize = this.map_.getSize();
goog.asserts.assert(mapSize !== undefined);
this.map_.getView().fit(extent, mapSize, {maxZoom: this.maxRecenterZoom});
}
};
/**
* Start a CSV download for the selected features.
* @export
*/
gmf.DisplayquerygridController.prototype.downloadCsv = function() {
var source = this.getActiveGridSource();
if (source !== null) {
var columnDefs = source.configuration.columnDefs;
goog.asserts.assert(columnDefs !== undefined);
var selectedRows = source.configuration.getSelectedRows();
this.ngeoCsvDownload_.startDownload(
selectedRows, columnDefs, 'query-results');
}
};
gmf.module.controller('GmfDisplayquerygridController',
gmf.DisplayquerygridController);
| kalbermattenm/ngeo | contribs/gmf/src/directives/displayquerygrid.js | JavaScript | mit | 23,829 |
using SQLite;
namespace KinderChat
{
/// <summary>
/// Business entity base class. Provides the ID property.
/// </summary>
public abstract class EntityBase
{
/// <summary>
/// Gets or sets the Database ID.
/// </summary>
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
}
}
| xamarin/KinderChat | SharedClient/Models/EntityBase.cs | C# | mit | 302 |
var expect = chai.expect;
describe("sails", function() {
beforeEach(function() { });
afterEach(function() { });
it('should not fail', function() { expect(true).to.be.true; });
});
| ioisup/CAMS | test/bootstrap.Spec.js | JavaScript | mit | 190 |
// external imports
import axios from 'axios'
import { Base64 } from 'js-base64'
import path from 'path'
import fm from 'front-matter'
// local imports
import zipObject from '../zipObject'
import decrypt from '../decrypt'
/** 从github调用并在本地缓存期刊内容,返回Promise。主要函数:
* getContent: 调取特定期刊特定内容。如获取第1期“心智”子栏目中第2篇文章正文:getContent(['issues', '1', '心智', '2', 'article.md'])。
* getCurrentIssue: 获取最新期刊号,无需参数。
* getAbstracts: 获取所有文章简介,需要提供期刊号。
*/
class magazineStorage {
/**
* 建立新期刊instance.
* @param {string} owner - github项目有所有者
* @param {string} repo - github项目名称
* @param {array} columns - 各子栏目列表
*/
constructor(owner = 'Perspicere', repo = 'PerspicereContent', columns = ['心智', '此岸', '梦境']) {
// github account settings
this.owner = owner
this.repo = repo
// array of submodules
this.columns = columns
// grap window storage
this.storage = window.sessionStorage
// keys to be replaced with content
this.urlReplace = ['img', 'image']
// github api
this.baseURL = 'https://api.github.com/'
// github api
// github 禁止使用明文储存access token,此处使用加密token
// 新生成token之后可以通过encrypt函数加密
// TODO: use OAuth?
this.github = axios.create({
baseURL: this.baseURL,
auth: {
username: 'guoliu',
password: decrypt(
'6a1975233d2505057cfced9c0c847f9c99f97f8f54df8f4cd90d4d3949d8dff02afdac79c3dec4a9135fad4a474f8288'
)
},
timeout: 10000
})
}
// get content from local storage
// 总数据大小如果超过5mb限制,需要优化存储
get content() {
let content = this.storage.getItem('content')
if (!content) {
return {}
}
return JSON.parse(content)
}
// cache content to local storage
set content(tree) {
this.storage.setItem('content', JSON.stringify(tree))
}
// get current issue number from local storage
get currentIssue() {
return this.storage.getItem('currentIssue')
}
// cache current issue number
set currentIssue(issue) {
this.storage.setItem('currentIssue', issue)
}
// locate leaf note in a tree
static locateLeaf(tree, location) {
if (location.length === 0) {
return tree
}
try {
return magazineStorage.locateLeaf(tree[location[0]], location.slice(1))
} catch (err) {
return null
}
}
// helper function to return tree with an extra leaf node
static appendLeaf(tree, location, leaf) {
if (location.length === 0) {
return leaf
} else if (!tree) {
tree = {}
}
return {
...tree,
[location[0]]: magazineStorage.appendLeaf(tree[location[0]], location.slice(1), leaf)
}
}
// build url for image
imageURL = location => `https://github.com/${this.owner}/${this.repo}/raw/master/${path.join(...location)}`
// pull content from github with given path
pullContent = async location => {
try {
const res = await this.github.get(`/repos/${this.owner}/${this.repo}/contents/${path.join(...location)}`)
return res.data
} catch (err) {
console.warn(`Error pulling data from [${location.join(', ')}], null value will be returned instead`, err)
return null
}
}
// parse responce, returns an object
parseData = data => {
if (!data) {
return null
}
// if we get an array, parse every element
if (data.constructor === Array) {
return data.reduce(
(accumulated, current) => ({
...accumulated,
[current.name]: this.parseData(current)
}),
{}
)
}
if (data.content) {
const ext = path.extname(data.path)
const content = Base64.decode(data.content)
// if it's a markdown file, parse it and get meta info
if (ext === '.md') {
const { attributes, body } = fm(content)
// replace image paths
const bodyWithUrl = body.replace(
/(!\[.*?\]\()(.*)(\)\s)/,
(_, prev, url, post) => `${prev}${this.imageURL([...data.path.split('/').slice(0, -1), url])}${post}`
)
return {
...attributes,
body: bodyWithUrl
}
}
if (ext === '.json') {
// if it's a json, parse it
return JSON.parse(content)
}
return content
}
if (data.type === 'dir') {
// if we get a directory
return {}
}
return null
}
/**
* 调用期刊内容.
* @param {string} location - 内容位置,描述目标文档位置。例如第1期“心智”子栏目中第2篇文章正文:['issues', '1', '心智', '2', 'article.md']。
* @return {object} 目标内容
*/
getContent = async location => {
// 尝试从本地获取
let contentNode = magazineStorage.locateLeaf(this.content, location) || {}
// 本地无值,从远程调用
if (contentNode.constructor === Object && Object.keys(contentNode).length === 0) {
const data = await this.pullContent(location)
contentNode = this.parseData(data)
// 将json中路径替换为url,例如图片
if (contentNode && contentNode.constructor === Object && Object.keys(contentNode).length > 0) {
const URLkeys = Object.keys(contentNode).filter(field => this.urlReplace.includes(field))
const URLs = URLkeys.map(key => this.imageURL([...location.slice(0, -1), contentNode[key]]))
contentNode = { ...contentNode, ...zipObject(URLkeys, URLs) }
}
this.content = magazineStorage.appendLeaf(this.content, location, contentNode)
}
return contentNode
}
/**
* 获取最新期刊号。
* @return {int} 最新期刊号。
*/
getCurrentIssue = async () => {
if (!this.currentIssue) {
const data = await this.getContent(['issues'])
this.currentIssue = Object.keys(data)
.filter(
entry => data[entry] && data[entry].constructor === Object // is a directory
)
.reduce((a, b) => Math.max(parseInt(a), parseInt(b)))
}
return this.currentIssue
}
/**
* 获取期刊所有文章简介。
* @param {int} issue - 期刊号。
* @return {object} 该期所有文章简介。
*/
getIssueAbstract = async issue => {
// 默认获取最新一期
let issueNumber = issue
if (!issue) {
issueNumber = await this.getCurrentIssue()
}
const issueContent = await Promise.all(
this.columns.map(async column => {
// 栏目文章列表
const articleList = Object.keys(await this.getContent(['issues', issueNumber, column]))
// 各文章元信息
const columnContent = await Promise.all(
articleList.map(article => this.getContent(['issues', issueNumber, column, article, 'article.md']))
)
return zipObject(articleList, columnContent)
})
)
// 本期信息
const meta = await this.getContent(['issues', issueNumber, 'meta.json'])
return {
...meta,
content: zipObject(this.columns, issueContent)
}
}
/**
* 获取期刊所有单篇文章。
* @return {object} 所有单篇文章。
* TODO: 仅返回一定数量各子栏目最新文章
*/
getArticleAbstract = async () => {
// 各栏目
const articlesContent = await Promise.all(
this.columns.map(async column => {
// 栏目文章列表
const articleList = Object.keys((await this.getContent(['articles', column])) || {})
// 各文章元信息
const columnContent = await Promise.all(
articleList.map(article => this.getContent(['articles', column, article, 'article.md']))
)
return zipObject(articleList, columnContent)
})
)
return zipObject(this.columns, articlesContent)
}
}
export default new magazineStorage()
| Perspicere/PerspicereMagazine | src/store/actions/utils/magazineStorage/index.js | JavaScript | mit | 8,028 |
package ncbiutils
import (
"bufio"
"bytes"
"io"
"os"
"path/filepath"
"strings"
)
var GCTABLES map[string]*GeneticCode
type Taxa struct {
Id string // node id in GenBank taxonomy database
Name string // the unique variant of names
Parent string // parent node id in GenBank taxonomy database
Rank string // rank of this node (superkingdom, kingdom ...)
EmblCode string // locus-name prefix
Division string // division
InheritedDivFlag string // 1 if node inherits division from parent
GeneticCode *GeneticCode // genetic code
InheriteGCFlag string // 1 if node inherits genetic code from parent
MitochondrialGC *GeneticCode // mitochondrial genetic code
InheriteMGCFlag string // 1 if node inherits mitochondrial genetic code from parent
Comments string // free-text comments and citations
}
// read taxonomy from NCBI taxonomy database dmp
// returns a map[id]Taxa
func ReadTaxas(dir string) map[string]Taxa {
taxaMap := make(map[string]Taxa)
namesFilePath := filepath.Join(dir, "names.dmp")
f, err := os.Open(namesFilePath)
if err != nil {
panic(err)
}
defer f.Close()
nameMap := getNames(f)
gcFilePath := filepath.Join(dir, "gencode.dmp")
f, err = os.Open(gcFilePath)
if err != nil {
panic(err)
}
defer f.Close()
gencodes := ReadGeneticCodes(f)
nodesFilePath := filepath.Join(dir, "nodes.dmp")
f, err = os.Open(nodesFilePath)
if err != nil {
panic(err)
}
defer f.Close()
r := bufio.NewReader(f)
for {
l, err := r.ReadString('\n')
if err != nil {
if err != io.EOF {
panic(err)
}
break
}
fields := strings.Split(l, "\t|\t")
id := fields[0]
parent := fields[1]
rank := fields[2]
embl := fields[3]
division := fields[4]
idivflag := fields[5]
gcid := fields[6]
igcflag := fields[7]
mgcid := fields[8]
imgcflag := fields[9]
comments := fields[12]
taxa := Taxa{
Id: id,
Parent: parent,
Rank: rank,
EmblCode: embl,
Division: division,
InheritedDivFlag: idivflag,
GeneticCode: gencodes[gcid],
InheriteGCFlag: igcflag,
MitochondrialGC: gencodes[mgcid],
InheriteMGCFlag: imgcflag,
Comments: comments,
Name: nameMap[id],
}
taxaMap[id] = taxa
}
return taxaMap
}
type GeneticCode struct {
Id string // GenBank genetic code id
Abbreviation string // genetic code name abbreviation
Name string // genetic code name
Table map[string]byte // translate table for this genetic code
Starts []string // start codon for this genetic code
FFCodons map[string]bool // four-fold codons
}
func GeneticCodes() (gcMap map[string]*GeneticCode) {
buf := bytes.NewBufferString(GCSTRING)
gcMap = ReadGeneticCodes(buf)
return
}
func ReadGeneticCodes(f io.Reader) (gcMap map[string]*GeneticCode) {
gcMap = make(map[string]*GeneticCode)
rd := bufio.NewReader(f)
for {
l, err := rd.ReadString('\n')
if err != nil {
if err != io.EOF {
panic(err)
}
break
}
fields := strings.Split(l, "\t|\t")
id := fields[0]
abb := fields[1]
name := fields[2]
cde := fields[3]
starts := fields[4]
table, ffs := getTables(cde[:64])
startCodons := getStartCodons(starts[:64])
gc := GeneticCode{
Id: id,
Abbreviation: abb,
Name: name,
Table: table,
Starts: startCodons,
FFCodons: ffs,
}
gcMap[id] = &gc
}
return
}
func getTables(s string) (table map[string]byte, ffCodons map[string]bool) {
table = make(map[string]byte)
nn := "TCAG"
l := 0
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
for k := 0; k < 4; k++ {
c := string([]byte{nn[i], nn[j], nn[k]})
table[c] = s[l]
l++
}
}
}
ffCodons = make(map[string]bool)
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
ff := true
aa := table[string([]byte{nn[i], nn[j], nn[0]})]
for k := 0; k < 4; k++ {
c := string([]byte{nn[i], nn[j], nn[k]})
if table[c] != aa {
ff = false
break
}
}
for k := 0; k < 4; k++ {
c := string([]byte{nn[i], nn[j], nn[k]})
ffCodons[c] = ff
}
}
}
return
}
func getStartCodons(s string) (starts []string) {
nn := "TCAG"
l := 0
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
for k := 0; k < 4; k++ {
c := string([]byte{nn[i], nn[j], nn[k]})
if s[l] == 'M' {
starts = append(starts, c)
}
l++
}
}
}
return
}
// returns a map[id][scientific name]
func getNames(f io.Reader) map[string]string {
nameMap := make(map[string]string)
r := bufio.NewReader(f)
for {
l, err := r.ReadString('\n')
if err != nil {
if err != io.EOF {
panic(err)
}
break
}
fields := strings.Split(l, "\t|\t")
id := fields[0]
name := fields[1]
class := strings.Split(strings.TrimSpace(fields[3]), "\t|")[0]
if class == "scientific name" {
nameMap[id] = name
}
}
return nameMap
}
| mingzhi/ncbiutils | taxa.go | GO | mit | 5,076 |
<?php
namespace Oqq\Minc\Serializer\Encoder\Encode;
use Oqq\Minc\Serializer\Exception\UnexpectedEncodingFormatException;
/**
* @author Eric Braun <eb@oqq.be>
*/
abstract class AbstractEncode implements EncodeInterface
{
/**
* @param string $format
*
* @throws UnexpectedEncodingFormatException
*/
protected function assertCanEncode($format)
{
if (!$this->canEncode($format)) {
throw new UnexpectedEncodingFormatException($format);
}
}
}
| oqq/minc-serializer | src/Encoder/Encode/AbstractEncode.php | PHP | mit | 507 |
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <set>
#include <sstream>
#include <vector>
using namespace std;
int main() {
while (true) {
int N, M;
cin >> N;
if (!cin)
break;
multiset<int> prices;
for (int i = 0; i < N; ++i) {
int p;
cin >> p;
prices.insert(p);
}
cin >> M;
int best_i, best_j;
bool got_best = false;
for (multiset<int>::const_iterator itr = prices.begin();
itr != prices.end();
++itr) {
int i = *itr, j = M - i;
if ( (j <= 0) ||
(prices.count(j) == 0) ||
((i == j) && (prices.count(i) < 2)) )
continue;
if (!got_best || (abs(i - j) < abs(best_i - best_j))) {
best_i = i;
best_j = j;
got_best = true;
}
}
if (best_i > best_j) {
swap(best_i, best_j);
}
cout << "Peter should buy books whose prices are " << best_i << " and " << best_j << "." << endl << endl;
}
return 0;
}
| acm-csuf/icpc | 2014-Battle_of_the_Bits/kwortman-solutions/11057.cpp | C++ | mit | 977 |
export default {
navigator: {
doc: 'Docs',
demo: 'Demo',
started: 'Get Started'
},
features: {
userExperience: {
title: 'Optimize Experience',
desc: 'To make scroll more smoothly, We support flexible configurations about inertial scrolling, rebound, fade scrollbar, etc. which could optimize user experience obviously.'
},
application: {
title: 'Rich Features',
desc: 'It can be applied to normal scroll list, picker, slide, index list, start guidance, etc. What\'s more, some complicated needs like pull down refresh and pull up load can be implemented much easier.'
},
dependence: {
title: 'Dependence Free',
desc: 'As a plain JavaScript library, BetterScroll doesn\'t depend on any framework, you could use it alone, or with any other MVVM frameworks.'
}
},
examples: {
normalScrollList: 'Normal Scroll List',
indexList: 'Index List',
picker: 'Picker',
slide: 'Slide',
startGuidance: 'Start Guidance',
freeScroll: 'Free Scroll',
formList: 'Form List',
verticalScrollImg: 'vertical-scroll-en.jpeg',
indexListImg: 'index-list.jpeg',
pickerImg: 'picker-en.jpeg',
slideImg: 'slide.jpeg',
startGuidanceImg: 'full-page-slide.jpeg',
freeScrollImg: 'free-scroll.jpeg',
formListImg: 'form-list-en.jpeg'
},
normalScrollListPage: {
desc: 'Nomal scroll list based on BetterScroll',
scrollbar: 'Scrollbar',
pullDownRefresh: 'Pull Down Refresh',
pullUpLoad: 'Pull Up Load',
previousTxt: 'I am the No.',
followingTxt: ' line',
newDataTxt: 'I am new data: '
},
scrollComponent: {
defaultLoadTxtMore: 'Load more',
defaultLoadTxtNoMore: 'There is no more data',
defaultRefreshTxt: 'Refresh success'
},
indexListPage: {
title: 'Current City: Beijing'
},
pickerPage: {
desc: 'Picker is a typical choose component at mobile end. And it could dynamic change the data of every column to realize linkage picker.',
picker: ' picker',
pickerDemo: ' picker demo ...',
oneColumn: 'One column',
twoColumn: 'Two column',
threeColumn: 'Three column',
linkage: 'Linkage',
confirmTxt: 'confirm | ok',
cancelTxt: 'cancel | close'
},
slidePage: {
desc: 'Slide is a typical component at mobile end, support horizontal move.'
},
fullPageSlideComponent: {
buttonTxt: 'Start Use'
},
freeScrollPage: {
desc: 'Free scroll supports horizontal and vertical move at the same time.'
},
formListPage: {
desc: 'To use form in better-scroll, you need to make sure the option click is configured as false, since some native element events will be prevented when click is true. And in this situation, we recommend to handle click by listening tap event.',
previousTxt: 'No.',
followingTxt: ' option'
}
}
| neurotoxinvx/better-scroll | example/language/english.js | JavaScript | mit | 2,844 |
share_examples_for 'a datastore adapter' do |adapter_name|
let(:persisted_job_class) do
adapter_module = namespace
Class.new do
include SuckerPunch::Job
prepend adapter_module
def perform(mutant_name)
'Hamato Yoshi' if mutant_name == 'Splinter'
end
end
end
subject { persisted_job_class.new }
#need a better way to test this: this passees even if the job is only created
#immediately before it is executed
it 'persists asynchronous jobs as they are queued' do
adapter_class.any_instance.stub(:update_status)
subject.async.perform('Donatello')
job_record.arguments.should eq ['Donatello']
job_record.status.should eq 'queued'
end
it 'persists synchronous jobs when they are queued' do
adapter_class.any_instance.stub(:update_status)
subject.perform('Raphael')
job_record.arguments.should eq ['Raphael']
job_record.status.should eq 'queued'
end
it 'marks job records as finished after executing them' do
subject.perform('Leonardo')
job_record.status.should eq 'complete'
end
it 'persists the job execution result' do
subject.perform('Splinter')
job_record.result.should eq 'Hamato Yoshi'
end
#Override in spec when data store does not support .first
let(:job_record) { job_class.first }
#Override in spec when data store uses a different naming convention
let(:adapter_class) { namespace.const_get('Adapter') }
let(:job_class) { namespace.const_get('Job') }
let(:namespace) { JobSecurity.const_get(adapter_name) }
end
| joshjordan/job_security | spec/support/adapter_examples.rb | Ruby | mit | 1,560 |
/* @flow */
import assert from 'assert';
import { CONVERSION_TABLE } from './06-export';
import type { Unit, UnitValue } from './06-export';
// We didn't cover any edge cases yet, so let's do this now
export function convertUnit(from: Unit, to: Unit, value: number): ?number {
if (from === to) {
return value;
}
// If there is no conversion possible, return null
// Note how we are using '== null' instead of '=== null'
// because the first notation will cover both cases, 'null'
// and 'undefined', which spares us a lot of extra code.
// You will need to set eslint's 'eqeqeq' rule to '[2, "smart"]'
if (CONVERSION_TABLE[from] == null || CONVERSION_TABLE[from][to] == null) {
return null;
}
const transform = CONVERSION_TABLE[from][to];
return transform(value);
}
// Intersection Type for assuming unit to be 'm'
// unit cannot be anything but a `Unit`, so we even
// prevent errors on definition
type MeterUnitValue = {
unit: 'm'
} & UnitValue;
// Convert whole UnitValues instead of single values
function convertToKm(unitValue: MeterUnitValue): ?UnitValue {
const { unit, value } = unitValue;
const converted = convertUnit(unit, 'km', value);
if (converted == null) {
return null;
}
return {
unit: 'km',
value: converted,
}
}
const value = convertToKm({ unit: 'm', value: 1500 });
assert.deepEqual(value, { unit: 'km', value: 1.5 });
| runtastic/flow-guide | tutorial/00-basics/08-maybe-and-optionals.js | JavaScript | mit | 1,406 |
package main
// Temporary file
import (
"golang.org/x/net/context"
"github.com/bearded-web/bearded/pkg/script"
"github.com/davecgh/go-spew/spew"
"github.com/bearded-web/bearded/pkg/transport/mango"
"github.com/bearded-web/wappalyzer-script/wappalyzer"
)
func run(addr string) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
transp, err := mango.NewServer(addr)
if err != nil {
panic(err)
}
client, err := script.NewRemoteClient(transp)
if err != nil {
panic(err)
}
go func() {
err := transp.Serve(ctx, client)
if err != nil {
panic(err)
}
}()
println("wait for connection")
client.WaitForConnection(ctx)
println("request config")
conf, err := client.GetConfig(ctx)
if err != nil {
panic(err)
}
app := wappalyzer.New()
println("handle with conf", spew.Sdump(conf))
err = app.Handle(ctx, client, conf)
if err != nil {
panic(err)
}
}
func main() {
run("tcp://:9238")
// run(":9238")
}
| bearded-web/wappalyzer-script | main.go | GO | mit | 960 |
$(document).ready(function () {
// add classes to check boxes
$('#id_notify_at_threshold').addClass('form-control');
$('#id_in_live_deal').addClass('form-control');
$('#id_is_subscription').addClass('form-control');
});
| vforgione/dodger | app/static/app/js/sku__create.js | JavaScript | mit | 230 |
<?php
namespace WaddlingCo\StreamPerk\Bundle\ServerBundle;
use WaddlingCo\StreamPerk\Bundle\CoreBundle\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use WaddlingCo\StreamPerk\Bundle\ServerBundle\DependencyInjection\ServerTypePass;
class StreamPerkServerBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ServerTypePass());
}
}
| WaddlingCo/streamperk-bundle | ServerBundle/StreamPerkServerBundle.php | PHP | mit | 473 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Xml.Serialization;
namespace VsAutoDeploy
{
public class ProjectConfiguration
{
[DefaultValue(true)]
public bool IsEnabled { get; set; } = true;
public string ProjectName { get; set; }
public List<string> Files { get; private set; } = new List<string>();
public bool IncludeSubDirectories { get; set; }
public string TargetDirectory { get; set; }
}
} | lennyomg/VsAutoDeploy | src/VsAutoDeploy/VsAutoDeploy/Configuration/ProjectConfiguration.cs | C# | mit | 567 |
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Form\ContactCreateForm;
use Application\Service\ContactService;
use Application\Service\PersonService;
/**
*
* Controller responsible for creation and destruction of contacts.
*
* @author wbondarenko@programmer.net
*
*/
class ContactController
extends ApplicationController
{
private $contactService;
private $personService;
public function __construct (ContactService $contactService, PersonService $personService)
{
$this->contactService = $contactService;
$this->personService = $personService;
}
/**
* Creates new contact on POST.
* Also partly responsible for ensuring that creation is possible.
* Renders appropriate HTML page on GET.
* Redirects to the authentication page is user is not logged in.
*/
public function createAction ()
{
if (!$this->isAuthenticated( ))
{
return $this->redirectToAuthentication( );
}
$form = new ContactCreateForm ("Create contact.");
$source = $this->identity( )->getPerson( );
$persons = array ( );
$request = $this->getRequest();
if ($request->isPost())
{
// TODO Implement input filter for form.
//$form->setInputFilter(new ContactCreateInputFilter ( ));
$form->setData($request->getPost());
if ($form->isValid())
{
$contact = $this->contactService->create($source, $this->params( )->fromPost("id"));
return $this->redirectToPersonalProfile( );
} else {
$this->layout( )->messages = $form->getMessages( );
}
} else if ($request->isGet( )) {
if ($target = $this->personService->retrieve($this->params( )->fromRoute("id")))
{
if (!$this->isMyself($target))
{
return array ('form' => $form, 'target' => $target);
} else {
return $this->redirectToPersonalProfile( );
}
}
}
}
/**
* Destroys a contact on POST.
* Renders appropriate HTML page on GET.
* Redirects to authentication page if user is not logged in.
*/
public function destroyAction ()
{
if (!$this->isAuthenticated( ))
{
return $this->redirectToAuthentication( );
}
$source = $this->identity( )->getPerson( );
$request = $this->getRequest();
if ($request->isPost())
{
$this->contactService->destroy($source, $this->params( )->fromPost('id'));
}
return $this->redirectToPersonalProfile( );
}
}
| Wbondar/Buddies | module/Application/src/Application/Controller/ContactController.php | PHP | mit | 2,817 |
import React, { Component } from 'react';
export default React.createClass({
getInitialState: function () {
return { title: '', body: '' };
},
handleChangeTitle: function (e) {
this.setState({ title: e.target.value });
},
handleChangeBody: function (e) {
this.setState({ body: e.target.value });
},
handleSubmit: function (e) {
e.preventDefault();
this.props.addPost(this.state);
},
render() {
return (
<div>
<h3>New post</h3>
<form onSubmit={this.handleSubmit}>
<input type="text"
placeholder="sdfsd"
value={this.title}
placeholder="title"
onChange={this.handleChangeTitle} />
<br />
<textarea type="text"
placeholder="sdfsd"
placeholder="body"
onChange={this.handleChangeBody} >
{this.body}
</textarea>
<button>Submit</button>
</form>
</div>
);
},
});
| JayMc/react-crud-example | client/components/FormPost.js | JavaScript | mit | 988 |
export default {
'/': {
component: require('./components/NowPlayingView'),
name: 'NowPlaying'
}
}
| SimulatedGREG/Frequency | app/src/routes.js | JavaScript | mit | 110 |
<!DOCTYPE html>
<html>
<head>
<title>404</title>
<link href='https://fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Not Found.</div>
</div>
</div>
</body>
</html>
| arabdigitalexpression/nadmig | resources/views/errors/404.blade.php | PHP | mit | 917 |
package com.simmarith.sqlCon;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class Permission extends DbEntity {
// Properties
private String name = null;
private String description = null;
// Getter and Setter
public String getName() {
if (this.name == null) {
this.name = this.fetchProperty("name");
}
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
if (this.description == null) {
this.description = this.fetchProperty("description");
}
return description;
}
public void setDescription(String description) {
this.description = description;
}
// Methods
public static ArrayList<Permission> getAllPermissions() {
SqlConnection con = SqlConnection.getInstance();
ArrayList<Permission> allPermissions = new ArrayList<>();
ResultSet res = con.sql("Select id from user");
try {
while (res.next()) {
allPermissions
.add(new Permission(Long.toString(res.getLong(1))));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allPermissions;
}
public void persist() {
if (this.getId() == null) {
ResultSet res = this.con.sql(String.format(
"insert into %s (name, description) values ('%s', '%s')", this.tableName,
this.getName(), this.getDescription()));
try {
res.next();
this.setId(Long.toString(res.getLong(1)));
return;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.con.sql(String.format("update %s set name = '%s', description = '%s' where id = %s",
this.tableName, this.getName(), this.getDescription(), this.getId()));
}
// Constructors
public Permission() {
super("permission");
}
public Permission(String id) {
this();
this.setId(id);
}
}
| Simmarith/userMan | src/com/simmarith/sqlCon/Permission.java | Java | mit | 2,289 |
require "spec_helper"
describe "Should define lifecycle callbacks" do
def config_db
MyMongoid.configure do |config|
config.host = "127.0.0.1:27017"
config.database = "my_mongoid_test"
end
end
def clean_db
klass.collection.drop
end
before {
config_db
clean_db
}
let(:base) {
Class.new {
include MyMongoid::Document
def self.to_s
"Event"
end
}
}
describe "all hooks:" do
let(:klass) { base }
[:delete,:save,:create,:update].each do |name|
it "should declare before hook for #{name}" do
expect(klass).to respond_to("before_#{name}")
end
it "should declare around hook for #{name}" do
expect(klass).to respond_to("around_#{name}")
end
it "should declare after hook for #{name}" do
expect(klass).to respond_to("after_#{name}")
end
end
end
describe "only before hooks:" do
let(:klass) { base }
[:find,:initialize].each do |name|
it "should not declare before hook for #{name}" do
expect(klass).to_not respond_to("before_#{name}")
end
it "should not declare around hook for #{name}" do
expect(klass).to_not respond_to("around_#{name}")
end
it "should declare after hook for #{name}" do
expect(klass).to respond_to("after_#{name}")
end
end
end
describe "run create callbacks" do
let(:klass) {
Class.new(base) {
before_create :before_method
}
}
let(:record) {
klass.new({})
}
it "should run callbacks when saving a new record" do
expect(record).to receive(:before_method)
record.save
end
it "should run callbacks when creating a new record" do
expect_any_instance_of(klass).to receive(:before_method)
klass.create({})
end
end
describe "run save callbacks" do
let(:klass) {
Class.new(base) {
before_save :before_method
def before_method
end
}
}
it "should run callbacks when saving a new record" do
record = klass.new({})
expect(record).to receive(:before_method)
record.save
end
it "should run callbacks when saving a persisted record" do
record = klass.create({})
expect(record).to receive(:before_method)
record.save
end
end
end | halida/my_mongoid | spec/lifecycle_spec.rb | Ruby | mit | 2,362 |
import { NgModule } from '@angular/core';
import { SharedModule } from '../../shared/shared.module';
import { AppendPipe } from './appendPipe';
@NgModule({
imports: [ SharedModule ],
declarations: [ AppendPipe ],
exports: [ AppendPipe ]
})
export class PipesModule { }
| nickppa/MyCompents | src/app/Components/Pipes/pipes.module.ts | TypeScript | mit | 291 |
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInite8d4181ab44f138b11e93a232501f3a9
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInite8d4181ab44f138b11e93a232501f3a9', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInite8d4181ab44f138b11e93a232501f3a9', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInite8d4181ab44f138b11e93a232501f3a9::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInite8d4181ab44f138b11e93a232501f3a9::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequiree8d4181ab44f138b11e93a232501f3a9($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequiree8d4181ab44f138b11e93a232501f3a9($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
| nathanjosiah/zf2-autotable | vendor/composer/autoload_real.php | PHP | mit | 2,414 |
/**
Copyright (c) 2007 Bill Orcutt (http://lilyapp.org, http://publicbeta.cx)
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.
*/
/**
* Construct a new color object
* @class
* @constructor
* @extends LilyObjectBase
*/
function $color(arg)
{
var thisPtr=this;
var websafe=arg||false;
this.outlet1 = new this.outletClass("outlet1",this,"random color in hexadecimal");
this.inlet1=new this.inletClass("inlet1",this,"\"bang\" outputs random color");
// getRandomColor()
// Returns a random hex color. Passing true for safe returns a web safe color
//code hijacked from http://www.scottandrew.com/js/js_util.js
function getRandomColor(safe)
{
var vals,r,n;
if (safe)
{
v = "0369CF";
n = 3;
} else
{
v = "0123456789ABCDEF";
n = 6;
}
var c = "#";
for (var i=0;i<n;i++)
{
var ch = v.charAt(Math.round(Math.random() * (v.length-1)));
c += (safe)?ch+ch:ch;
}
return c;
}
function RGBtoHex(R,G,B) {
return toHex(R)+toHex(G)+toHex(B);
}
function toHex(N) {
if (N==null) return "00";
N=parseInt(N); if (N==0 || isNaN(N)) return "00";
N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}
function HSLtoRGB (h,s,l) {
if (s == 0) return [l,l,l] // achromatic
h=h*360/255;s/=255;l/=255;
if (l <= 0.5) rm2 = l + l * s;
else rm2 = l + s - l * s;
rm1 = 2.0 * l - rm2;
return [toRGB1(rm1, rm2, h + 120.0),toRGB1(rm1, rm2, h),toRGB1(rm1, rm2, h - 120.0)];
}
function toRGB1(rm1,rm2,rh) {
if (rh > 360.0) rh -= 360.0;
else if (rh < 0.0) rh += 360.0;
if (rh < 60.0) rm1 = rm1 + (rm2 - rm1) * rh / 60.0;
else if (rh < 180.0) rm1 = rm2;
else if (rh < 240.0) rm1 = rm1 + (rm2 - rm1) * (240.0 - rh) / 60.0;
return Math.round(rm1 * 255);
}
//output random color
this.inlet1["random"]=function() {
thisPtr.outlet1.doOutlet(getRandomColor(websafe));
}
//convert RGB to hex
this.inlet1["RGBtoHEX"]=function(rgb) {
var tmp = rgb.split(" ");
thisPtr.outlet1.doOutlet("#"+RGBtoHex(tmp[0],tmp[1],tmp[2]));
}
//convert HSL to hex
this.inlet1["HSLtoHEX"]=function(hsl) {
var tmp = hsl.split(" ");
var rgb = HSLtoRGB(tmp[0],tmp[1],tmp[2]);
thisPtr.outlet1.doOutlet("#"+RGBtoHex(rgb[0],rgb[1],rgb[2]));
}
return this;
}
var $colorMetaData = {
textName:"color",
htmlName:"color",
objectCategory:"Math",
objectSummary:"Various color related utilities",
objectArguments:"websafe colors only [false]"
} | billorcutt/lily | lily/lily/chrome/content/externals/color.js | JavaScript | mit | 3,506 |
#region Microsoft Public License
/* This code is part of Xipton.Razor v3.0
* (c) Jaap Lamfers, 2013 - jaap.lamfers@xipton.net
* Licensed under the Microsoft Public License (MS-PL) http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
*/
#endregion
namespace Xipton.Razor
{
/// <summary>
/// This interface redefines the Model property making it typed
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
public interface ITemplate<out TModel> : ITemplate
{
new TModel Model { get; }
}
} | PhilipDaniels/Lithogen.proto | Xipton.Razor/ITemplate`1.cs | C# | mit | 560 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->curpage = "JOHNMARKABRIL";
$this->load->model('About_model');
$this->load->model('Projects_model');
date_default_timezone_set("Asia/Manila");
$this->date = date("F d, Y");
$this->time = date("g:i A");
}
public function index()
{
$details = array (
'get_all_projects' => $this->Projects_model->get_all_projects(),
'get_all_about' => $this->About_model->get_all_about()
);
$data['content'] = $this->load->view('home', $details, TRUE);
$data['curpage'] = $this->curpage;
$this->load->view('template', $data);
}
}
| johnmarkabril/johnmarkabril | application/controllers/Home.php | PHP | mit | 764 |
Ext.provide('Phlexible.users.UserWindow');
Ext.require('Ext.ux.TabPanel');
Phlexible.users.UserWindow = Ext.extend(Ext.Window, {
title: Phlexible.users.Strings.user,
strings: Phlexible.users.Strings,
plain: true,
iconCls: 'p-user-user-icon',
width: 530,
minWidth: 530,
height: 400,
minHeight: 400,
layout: 'fit',
border: false,
modal: true,
initComponent: function () {
this.addEvents(
'save'
);
var panels = Phlexible.PluginRegistry.get('userEditPanels');
this.items = [{
xtype: 'uxtabpanel',
tabPosition: 'left',
tabStripWidth: 150,
activeTab: 0,
border: true,
deferredRender: false,
items: panels
}];
this.tbar = new Ext.Toolbar({
hidden: true,
cls: 'p-users-disabled',
items: [
'->',
{
iconCls: 'p-user-user_account-icon',
text: this.strings.account_is_disabled,
handler: function () {
this.getComponent(0).setActiveTab(4);
},
scope: this
}]
});
this.buttons = [
{
text: this.strings.cancel,
handler: this.close,
scope: this
},
{
text: this.strings.save,
iconCls: 'p-user-save-icon',
handler: this.save,
scope: this
}
];
Phlexible.users.UserWindow.superclass.initComponent.call(this);
},
show: function (user) {
this.user = user;
if (user.get('username')) {
this.setTitle(this.strings.user + ' "' + user.get('username') + '"');
} else {
this.setTitle(this.strings.new_user);
}
Phlexible.users.UserWindow.superclass.show.call(this);
this.getComponent(0).items.each(function(p) {
if (typeof p.loadUser === 'function') {
p.loadUser(user);
}
});
if (!user.get('enabled')) {
this.getTopToolbar().show();
}
},
save: function () {
var data = {};
var valid = true;
this.getComponent(0).items.each(function(p) {
if (typeof p.isValid === 'function' && typeof p.getData === 'function') {
if (p.isValid()) {
Ext.apply(data, p.getData());
} else {
valid = false;
}
}
});
if (!valid) {
return;
}
var url, method;
if (this.user.get('uid')) {
url = Phlexible.Router.generate('users_users_update', {userId: this.user.get('uid')});
method = 'PUT';
} else {
url = Phlexible.Router.generate('users_users_create');
method = 'POST';
}
Ext.Ajax.request({
url: url,
method: method,
params: data,
success: this.onSaveSuccess,
scope: this
});
},
onSaveSuccess: function (response) {
var data = Ext.decode(response.responseText);
if (data.success) {
this.uid = data.uid;
Phlexible.success(data.msg);
this.fireEvent('save', this.uid);
this.close();
} else {
Ext.Msg.alert('Failure', data.msg);
}
}
});
| phlexible/phlexible | src/Phlexible/Bundle/UserBundle/Resources/scripts/window/UserWindow.js | JavaScript | mit | 3,587 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-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 "wallet.h"
#include "walletdb.h"
#include "rpcserver.h"
#include "init.h"
#include "base58.h"
#include "txdb.h"
#include "stealth.h"
#include "sigringu.h"
#include "smessage.h"
#include <sstream>
using namespace json_spirit;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
static void accountingDeprecationCheck()
{
if (!GetBoolArg("-enableaccounts", false))
throw std::runtime_error(
"Accounting API is deprecated and will be removed in future.\n"
"It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n"
"If you still want to enable it, add to your config file enableaccounts=1\n");
if (GetBoolArg("-staking", true))
throw std::runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n");
}
std::string HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
entry.push_back(Pair("version", wtx.nVersion));
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
int64_t nTime = 0;
if (nNodeMode == NT_FULL)
{
nTime = mapBlockIndex[wtx.hashBlock]->nTime;
} else
{
std::map<uint256, CBlockThinIndex*>::iterator mi = mapBlockThinIndex.find(wtx.hashBlock);
if (mi != mapBlockThinIndex.end())
nTime = (*mi).second->nTime;
};
entry.push_back(Pair("blocktime", nTime));
};
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(std::string,std::string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
std::string AccountFromValue(const Value& value)
{
std::string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
static const char *help = ""
"getinfo ['env']\n"
"Returns an object containing various state info.";
if (fHelp || params.size() > 1)
throw std::runtime_error(help);
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
if (params.size() > 0)
{
if (params[0].get_str().compare("env") == 0)
{
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("mode", std::string(GetNodeModeName(nNodeMode))));
obj.push_back(Pair("state", nNodeMode == NT_THIN ? std::string(GetNodeStateName(nNodeState)) : "Full Node"));
obj.push_back(Pair("protocolversion", (int)PROTOCOL_VERSION));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("debug", fDebug));
obj.push_back(Pair("debugpos", fDebugPoS));
obj.push_back(Pair("debugringsig", fDebugRingSig));
obj.push_back(Pair("datadir", GetDataDir().string()));
obj.push_back(Pair("walletfile", pwalletMain->strWalletFile));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("walletcrypted", pwalletMain->IsCrypted()));
obj.push_back(Pair("walletlocked", pwalletMain->IsCrypted() ? pwalletMain->IsLocked() ? "Locked" : "Unlocked" : "Uncrypted"));
obj.push_back(Pair("walletunlockedto", pwalletMain->IsCrypted() ? !pwalletMain->IsLocked() ? strprintf("%d", (int64_t)nWalletUnlockTime / 1000).c_str() : "Locked" : "Uncrypted"));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
} else
{
throw std::runtime_error(help);
};
};
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("mode", std::string(GetNodeModeName(nNodeMode))));
obj.push_back(Pair("state", nNodeMode == NT_THIN ? std::string(GetNodeStateName(nNodeState)) : "Full Node"));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("eclipsebalance", ValueFromAmount(pwalletMain->GetEclipseBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
obj.push_back(Pair("reserve", ValueFromAmount(nReserveBalance)));
obj.push_back(Pair("blocks", (int)nBestHeight));
if (nNodeMode == NT_THIN)
obj.push_back(Pair("filteredblocks", (int)nHeightFilteredNeeded));
obj.push_back(Pair("timeoffset", (int64_t)GetTimeOffset()));
if (nNodeMode == NT_FULL)
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("datareceived", bytesReadable(CNode::GetTotalBytesRecv())));
obj.push_back(Pair("datasent", bytesReadable(CNode::GetTotalBytesSent())));
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.ToStringIPPort() : std::string())));
obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP()));
if (nNodeMode == NT_FULL)
{
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
} else
{
diff.push_back(Pair("proof-of-work", GetHeaderDifficulty()));
diff.push_back(Pair("proof-of-stake", GetHeaderDifficulty(GetLastBlockThinIndex(pindexBestHeader, true))));
};
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewpubkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getnewpubkey [account]\n"
"Returns new public key for coinbase generation.");
// Parse the account first so we don't generate a key if there's an error
std::string strAccount;
if (params.size() > 0)
{
strAccount = AccountFromValue(params[0]);
};
if (pwalletMain->IsLocked())
throw std::runtime_error("Wallet is locked.");
// Generate a new key that is added to wallet
CPubKey newKey;
if (0 != pwalletMain->NewKeyFromAccount(newKey))
throw std::runtime_error("NewKeyFromAccount failed.");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount, NULL, true, true);
return HexStr(newKey.begin(), newKey.end());
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getnewaddress [account]\n"
"Returns a new EclipseCrypto address for receiving payments. "
"If [account] is specified, it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
std::string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
// Generate a new key that is added to wallet
CPubKey newKey;
if (0 != pwalletMain->NewKeyFromAccount(newKey))
throw std::runtime_error("NewKeyFromAccount failed.");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount, NULL, true, true);
return CBitcoinAddress(keyID).ToString();
}
Value getnewextaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getnewextaddress [label]\n"
"Returns a new EclipseCrypto ext address for receiving payments."
"If [label] is specified, it is added to the address book. ");
std::string strLabel;
if (params.size() > 0)
strLabel = params[0].get_str();
// Generate a new key that is added to wallet
CStoredExtKey *sek = new CStoredExtKey();
if (0 != pwalletMain->NewExtKeyFromAccount(strLabel, sek))
{
delete sek;
throw std::runtime_error("NewExtKeyFromAccount failed.");
};
pwalletMain->SetAddressBookName(sek->kp, strLabel, NULL, true, true);
// - CBitcoinAddress displays public key only
return CBitcoinAddress(sek->kp).ToString();
}
CBitcoinAddress GetAccountAddress(std::string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
// Generate a new key that is added to wallet
CStoredExtKey *sek = new CStoredExtKey();
if (0 != pwalletMain->NewExtKeyFromAccount(strAccount, sek))
{
delete sek;
throw std::runtime_error("NewExtKeyFromAccount failed.");
};
account.vchPubKey = sek->kp.pubkey;
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getaccountaddress <account>\n"
"Returns the current EclipseCrypto address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
std::string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"setaccount <eclipsecryptoaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid EclipseCrypto address");
std::string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
std::string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
};
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getaccount <eclipsecryptoaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid EclipseCrypto address");
std::string strAccount;
std::map<CTxDestination, std::string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
std::string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, std::string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const std::string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 5)
throw std::runtime_error(
"sendtoaddress <eclipsecryptoaddress> <amount> [comment] [comment-to] [narration]\n" // Exchanges use the comments internally...
"sendtoaddress <eclipsecryptoaddress> <amount> [narration]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
if (params[0].get_str().length() > 75
&& IsStealthAddress(params[0].get_str()))
return sendtostealthaddress(params, false);
std::string sAddrIn = params[0].get_str();
CBitcoinAddress address(sAddrIn);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid EclipseCrypto address");
// Amount
int64_t nAmount = AmountFromValue(params[1]);
CWalletTx wtx;
std::string sNarr;
// Wallet comments
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
sNarr = params[4].get_str();
if (sNarr.length() > 24)
throw std::runtime_error("Narration must be 24 characters or less.");
std::string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, sNarr, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw std::runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
std::map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(std::set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
} // cs_wallet
jsonGrouping.push_back(addressInfo);
};
jsonGroupings.push_back(jsonGrouping);
};
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw std::runtime_error(
"signmessage <eclipsecryptoaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
std::string strAddress = params[0].get_str();
std::string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw std::runtime_error(
"verifymessage <eclipsecryptoaddress> <signature> <message>\n"
"Verify a signed message");
std::string strAddress = params[0].get_str();
std::string strSign = params[1].get_str();
std::string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"getreceivedbyaddress <eclipsecryptoaddress> [minconf=1]\n"
"Returns the total amount received by <eclipsecryptoaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid EclipseCrypto address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64_t nAmount = 0;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(std::string strAccount, std::set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const std::string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
};
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
accountingDeprecationCheck();
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
std::string strAccount = AccountFromValue(params[0]);
std::set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64_t nAmount = 0;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsDestMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
};
};
return (double)nAmount / (double)COIN;
}
int64_t GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth)
{
int64_t nBalance = 0;
// Tally wallet transactions
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal() || wtx.GetDepthInMainChain() < 0)
continue;
int64_t nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64_t GetAccountBalance(const std::string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw std::runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*")
{
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number.
int64_t nBalance = 0;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsTrusted())
continue;
int64_t allFee;
std::string strSentAccount;
std::list<std::pair<CTxDestination, int64_t> > listReceived;
std::list<std::pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
nBalance += r.second;
};
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
};
return ValueFromAmount(nBalance);
};
accountingDeprecationCheck();
std::string strAccount = AccountFromValue(params[0]);
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw std::runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
accountingDeprecationCheck();
std::string strFrom = AccountFromValue(params[0]);
std::string strTo = AccountFromValue(params[1]);
int64_t nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
std::string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 7)
throw std::runtime_error(
"sendfrom <fromaccount> <toeclipsecryptoaddress> <amount> [minconf=1] [comment] [comment-to] [narration] \n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
std::string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid EclipseCrypto address");
int64_t nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
std::string sNarr;
if (params.size() > 6 && params[6].type() != null_type && !params[6].get_str().empty())
sNarr = params[6].get_str();
if (sNarr.length() > 24)
throw std::runtime_error("Narration must be 24 characters or less.");
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
std::string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, sNarr, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw std::runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
std::string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
std::set<CBitcoinAddress> setAddress;
std::vector<std::pair<CScript, int64_t> > vecSend;
int64_t totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid EclipseCrypto address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
};
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
int64_t nFeeRequired = 0;
int nChangePos;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, nFeeRequired, nChangePos);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
/**
* Used by addmultisigaddress / createmultisig:
*/
CScript _createmultisig_redeemScript(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw std::runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw std::runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
if (keys.size() > 16)
throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw std::runtime_error(
strprintf("%s does not refer to a key",ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw std::runtime_error(
strprintf("no full public key for address %s",ks));
if (!vchPubKey.IsFullyValid())
throw std::runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw std::runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw std::runtime_error(" Invalid public key: "+ks);
}
}
CScript result = GetScriptForMultisig(nRequired, pubkeys);
if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
throw std::runtime_error(
strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
std::string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a EclipseCrypto address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw std::runtime_error(msg);
};
std::string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
CBitcoinAddress address(innerID);
if (!pwalletMain->AddCScript(inner))
throw std::runtime_error("AddCScript() failed");
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
std::string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"Returns a json object with the address and redeemScript.\n"
"Each key is a EclipseCrypto address or hex-encoded public key.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) bitcoin address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
;
throw std::runtime_error(msg);
};
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
Value addredeemscript(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
{
std::string msg = "addredeemscript <redeemScript> [account]\n"
"Add a P2SH address with a specified redeemScript to the wallet.\n"
"If [account] is specified, assign address to [account].";
throw std::runtime_error(msg);
};
std::string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Construct using pay-to-script-hash:
std::vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript");
CScript inner(innerData.begin(), innerData.end());
CScriptID innerID = inner.GetID();
if (!pwalletMain->AddCScript(inner))
throw std::runtime_error("AddCScript() failed");
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64_t nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
std::map<CBitcoinAddress, tallyitem> mapTally;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsDestMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = std::min(item.nConf, nDepth);
}
}
// Reply
Array ret;
std::map<std::string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, std::string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const std::string& strAccount = item.second;
std::map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64_t nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = std::min(item.nConf, nConf);
} else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
};
};
if (fByAccounts)
{
for (std::map<std::string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64_t nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
};
};
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw std::runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw std::runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
accountingDeprecationCheck();
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const std::string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64_t nFee;
std::string strSentAccount;
std::list<std::pair<CTxDestination, int64_t> > listReceived;
std::list<std::pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == std::string("*"));
// Sent
if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
};
};
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
bool stop = false;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
{
std::string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else
if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
} else
{
entry.push_back(Pair("category", "receive"));
};
if (!wtx.IsCoinStake())
{
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
} else
{
entry.push_back(Pair("amount", ValueFromAmount(-nFee)));
stop = true; // only one coinstake output
};
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
};
if (stop)
break;
};
};
}
void AcentryToJSON(const CAccountingEntry& acentry, const std::string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == std::string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
};
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 4)
throw std::runtime_error(
"listtransactions [account] [count=10] [from=0] [show_coinstake=1]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
// listtransactions "*" 20 0 0
std::string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
bool fShowCoinstake = true;
if (params.size() > 3)
{
std::string value = params[3].get_str();
if (IsStringBoolNegative(value))
fShowCoinstake = false;
};
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount, fShowCoinstake);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
accountingDeprecationCheck();
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
std::map<std::string, int64_t> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook)
{
if (IsDestMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
};
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64_t nFee;
std::string strSentAccount;
std::list<std::pair<CTxDestination, int64_t> > listReceived;
std::list<std::pair<CTxDestination, int64_t> > listSent;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
};
};
std::list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(std::string, int64_t)& accountBalance, mapAccountBalances)
{
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
};
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw std::runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
};
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
};
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
};
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
} else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
};
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (pwalletMain->mapWallet.count(hash))
{
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
TxToJSON(wtx, 0, entry);
int64_t nCredit = wtx.GetCredit();
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
} else
{
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
TxToJSON(tx, 0, entry);
if (hashBlock == 0)
{
entry.push_back(Pair("confirmations", 0));
} else
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
else
entry.push_back(Pair("confirmations", 0));
};
};
} else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
};
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
std::string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"keypoolrefill [new-size]\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
unsigned int nSize = std::max(GetArg("-keypool", 100), (int64_t)0);
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size");
nSize = (unsigned int) params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(nSize);
if (pwalletMain->GetKeyPoolSize() < nSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
static void LockWallet(CWallet* pWallet)
{
LOCK2(pWallet->cs_wallet, cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw std::runtime_error(
"walletpassphrase <passphrase> <timeout> [stakingonly]\n"
"Stores the wallet decryption key in memory for <timeout> seconds.\n"
"if [stakingonly] is true sending functions are disabled.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
} else
{
throw std::runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
};
pwalletMain->TopUpKeyPool();
int64_t nSleepTime = params[1].get_int64();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
// ppcoin: if user OS account compromised prevent trivial sendmoney commands
if (params.size() > 2)
fWalletUnlockStakingOnly = params[2].get_bool();
else
fWalletUnlockStakingOnly = false;
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw std::runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw std::runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw std::runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw std::runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw std::runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; EclipseCrypto server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
Object operator()(const CStealthAddress &sxAddr) const {
Object obj;
obj.push_back(Pair("todo - stealth address", true));
return obj;
}
Object operator()(const CExtKeyPair &ek) const {
Object obj;
obj.push_back(Pair("todo - bip32 address", true));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"validateaddress <eclipsecryptoaddress>\n"
"Return information about <eclipsecryptoaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
std::string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsDestMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine)
{
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
};
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw std::runtime_error(
"validatepubkey <eclipsecryptopubkey>\n"
"Return information about <eclipsecryptopubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
std::string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsDestMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
ret.push_back(Pair("iscompressed", isCompressed));
if (fMine)
{
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
};
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
};
return ret;
}
// ppcoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw std::runtime_error(
"reservebalance [<reserve> [amount]]\n"
"<reserve> is true or false to turn balance reserve on or off.\n"
"<amount> is a real and rounded to cent.\n"
"Set reserve amount not participating in network protection.\n"
"If no parameters provided current setting is printed.\n");
if (params.size() > 0)
{
bool fReserve = params[0].get_bool();
if (fReserve)
{
if (params.size() == 1)
throw std::runtime_error("must provide amount to reserve balance.\n");
int64_t nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw std::runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
} else
{
if (params.size() > 1)
throw std::runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
Object result;
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// ppcoin: check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw std::runtime_error(
"checkwallet\n"
"Check wallet for integrity.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
Object result;
if (nMismatchSpent == 0)
{
result.push_back(Pair("wallet check passed", true));
} else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
};
return result;
}
// ppcoin: repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw std::runtime_error(
"repairwallet\n"
"Repair wallet if checkwallet reports any problem.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
Object result;
if (nMismatchSpent == 0)
{
result.push_back(Pair("wallet check passed", true));
} else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// NovaCoin: resend unconfirmed wallet transactions
Value resendtx(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"resendtx\n"
"Re-send unconfirmed transactions.\n"
);
ResendWalletTransactions(true);
return Value::null;
}
// ppcoin: make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
std::string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey())));
return result;
}
Value getnewstealthaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getnewstealthaddress [label]\n"
"Returns a new EclipseCrypto stealth address for receiving payments anonymously."
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw std::runtime_error("Failed: Wallet must be unlocked.");
std::string sLabel;
if (params.size() > 0)
sLabel = params[0].get_str();
CEKAStealthKey akStealth;
std::string sError;
if (0 != pwalletMain->NewStealthKeyFromAccount(sLabel, akStealth))
throw std::runtime_error("NewStealthKeyFromAccount failed.");
return akStealth.ToStealthAddress();
}
Value liststealthaddresses(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"liststealthaddresses [show_secrets=0]\n"
"List owned stealth addresses.");
bool fShowSecrets = false;
if (params.size() > 0)
{
std::string str = params[0].get_str();
if (IsStringBoolNegative(str))
fShowSecrets = false;
else
fShowSecrets = true;
};
if (fShowSecrets)
EnsureWalletIsUnlocked();
Object result;
ExtKeyAccountMap::const_iterator mi;
for (mi = pwalletMain->mapExtAccounts.begin(); mi != pwalletMain->mapExtAccounts.end(); ++mi)
{
CExtKeyAccount *ea = mi->second;
if (ea->mapStealthKeys.size() < 1)
continue;
result.push_back(Pair("Account", ea->sLabel));
AccStealthKeyMap::iterator it;
for (it = ea->mapStealthKeys.begin(); it != ea->mapStealthKeys.end(); ++it)
{
const CEKAStealthKey &aks = it->second;
if (fShowSecrets)
{
Object objA;
objA.push_back(Pair("Label ", aks.sLabel));
objA.push_back(Pair("Address ", aks.ToStealthAddress()));
objA.push_back(Pair("Scan Secret ", HexStr(aks.skScan.begin(), aks.skScan.end())));
std::string sSpend;
CStoredExtKey *sekAccount = ea->ChainAccount();
if (sekAccount && !sekAccount->fLocked)
{
CKey skSpend;
if (ea->GetKey(aks.akSpend, skSpend))
sSpend = HexStr(skSpend.begin(), skSpend.end());
else
sSpend = "Extract failed.";
} else
{
sSpend = "Account Locked.";
};
objA.push_back(Pair("Spend Secret ", sSpend));
result.push_back(Pair("Stealth Address", objA));
} else
{
result.push_back(Pair("Stealth Address", aks.ToStealthAddress() + " - " + aks.sLabel));
};
};
};
if (pwalletMain->stealthAddresses.size() > 0)
result.push_back(Pair("Account", "Legacy"));
std::set<CStealthAddress>::iterator it;
for (it = pwalletMain->stealthAddresses.begin(); it != pwalletMain->stealthAddresses.end(); ++it)
{
if (it->scan_secret.size() < 1)
continue; // stealth address is not owned
if (fShowSecrets)
{
Object objA;
objA.push_back(Pair("Label ", it->label));
objA.push_back(Pair("Address ", it->Encoded()));
objA.push_back(Pair("Scan Secret ", HexStr(it->scan_secret.begin(), it->scan_secret.end())));
objA.push_back(Pair("Spend Secret ", HexStr(it->spend_secret.begin(), it->spend_secret.end())));
result.push_back(Pair("Stealth Address", objA));
} else
{
result.push_back(Pair("Stealth Address", it->Encoded() + " - " + it->label));
};
};
return result;
}
Value importstealthaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2)
throw std::runtime_error(
"importstealthaddress <scan_secret> <spend_secret> [label]\n"
"Import an owned stealth addresses."
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw std::runtime_error("Failed: Wallet must be unlocked.");
std::string sScanSecret = params[0].get_str();
std::string sSpendSecret = params[1].get_str();
std::string sLabel;
if (params.size() > 2)
{
sLabel = params[2].get_str();
};
std::vector<uint8_t> vchScanSecret;
std::vector<uint8_t> vchSpendSecret;
if (IsHex(sScanSecret))
{
vchScanSecret = ParseHex(sScanSecret);
} else
{
if (!DecodeBase58(sScanSecret, vchScanSecret))
throw std::runtime_error("Could not decode scan secret as hex or base58.");
};
if (IsHex(sSpendSecret))
{
vchSpendSecret = ParseHex(sSpendSecret);
} else
{
if (!DecodeBase58(sSpendSecret, vchSpendSecret))
throw std::runtime_error("Could not decode spend secret as hex or base58.");
};
if (vchScanSecret.size() != 32)
throw std::runtime_error("Scan secret is not 32 bytes.");
if (vchSpendSecret.size() != 32)
throw std::runtime_error("Spend secret is not 32 bytes.");
ec_secret scan_secret;
ec_secret spend_secret;
memcpy(&scan_secret.e[0], &vchScanSecret[0], 32);
memcpy(&spend_secret.e[0], &vchSpendSecret[0], 32);
ec_point scan_pubkey, spend_pubkey;
if (SecretToPublicKey(scan_secret, scan_pubkey) != 0)
throw std::runtime_error("Could not get scan public key.");
if (SecretToPublicKey(spend_secret, spend_pubkey) != 0)
throw std::runtime_error("Could not get spend public key.");
CStealthAddress sxAddr;
sxAddr.label = sLabel;
sxAddr.scan_pubkey = scan_pubkey;
sxAddr.spend_pubkey = spend_pubkey;
sxAddr.scan_secret = vchScanSecret;
sxAddr.spend_secret = vchSpendSecret;
Object result;
bool fFound = false;
// -- find if address already exists
std::set<CStealthAddress>::iterator it;
for (it = pwalletMain->stealthAddresses.begin(); it != pwalletMain->stealthAddresses.end(); ++it)
{
CStealthAddress &sxAddrIt = const_cast<CStealthAddress&>(*it);
if (sxAddrIt.scan_pubkey == sxAddr.scan_pubkey
&& sxAddrIt.spend_pubkey == sxAddr.spend_pubkey)
{
if (sxAddrIt.scan_secret.size() < 1)
{
sxAddrIt.scan_secret = sxAddr.scan_secret;
sxAddrIt.spend_secret = sxAddr.spend_secret;
fFound = true; // update stealth address with secrets
break;
};
result.push_back(Pair("result", "Import failed - stealth address exists."));
return result;
};
};
if (fFound)
{
result.push_back(Pair("result", "Success, updated " + sxAddr.Encoded()));
} else
{
pwalletMain->stealthAddresses.insert(sxAddr);
result.push_back(Pair("result", "Success, imported " + sxAddr.Encoded()));
};
if (!pwalletMain->AddStealthAddress(sxAddr))
throw std::runtime_error("Could not save to wallet.");
return result;
}
Value sendtostealthaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 5)
throw std::runtime_error(
"sendtostealthaddress <stealth_address> <amount> [comment] [comment-to] [narration]\n"
"sendtostealthaddress <stealth_address> <amount> [narration]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
std::string sEncoded = params[0].get_str();
int64_t nAmount = AmountFromValue(params[1]);
std::string sNarr;
if (params.size() == 3 || params.size() == 5)
{
int nNarr = params.size() - 1;
if(params[nNarr].type() != null_type && !params[nNarr].get_str().empty())
sNarr = params[nNarr].get_str();
}
if (sNarr.length() > 24)
throw std::runtime_error("Narration must be 24 characters or less.");
CStealthAddress sxAddr;
if (!sxAddr.SetEncoded(sEncoded))
throw std::runtime_error("Invalid EclipseCrypto stealth address.");
CWalletTx wtx;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["to"] = params[4].get_str();
std::string sError;
if (!pwalletMain->SendStealthMoneyToDestination(sxAddr, nAmount, sNarr, wtx, sError))
throw JSONRPCError(RPC_WALLET_ERROR, sError);
return wtx.GetHash().GetHex();
}
Value clearwallettransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw std::runtime_error(
"clearwallettransactions \n"
"delete all transactions from wallet - reload with reloadanondata\n"
"Warning: Backup your wallet first!");
Object result;
uint32_t nTransactions = 0;
char cbuf[256];
{
LOCK2(cs_main, pwalletMain->cs_wallet);
CWalletDB walletdb(pwalletMain->strWalletFile);
walletdb.TxnBegin();
Dbc* pcursor = walletdb.GetTxnCursor();
if (!pcursor)
throw std::runtime_error("Cannot get wallet DB cursor");
Dbt datKey;
Dbt datValue;
datKey.set_flags(DB_DBT_USERMEM);
datValue.set_flags(DB_DBT_USERMEM);
std::vector<unsigned char> vchKey;
std::vector<unsigned char> vchType;
std::vector<unsigned char> vchKeyData;
std::vector<unsigned char> vchValueData;
vchKeyData.resize(100);
vchValueData.resize(100);
datKey.set_ulen(vchKeyData.size());
datKey.set_data(&vchKeyData[0]);
datValue.set_ulen(vchValueData.size());
datValue.set_data(&vchValueData[0]);
unsigned int fFlags = DB_NEXT; // same as using DB_FIRST for new cursor
while (true)
{
int ret = pcursor->get(&datKey, &datValue, fFlags);
if (ret == ENOMEM
|| ret == DB_BUFFER_SMALL)
{
if (datKey.get_size() > datKey.get_ulen())
{
vchKeyData.resize(datKey.get_size());
datKey.set_ulen(vchKeyData.size());
datKey.set_data(&vchKeyData[0]);
};
if (datValue.get_size() > datValue.get_ulen())
{
vchValueData.resize(datValue.get_size());
datValue.set_ulen(vchValueData.size());
datValue.set_data(&vchValueData[0]);
};
// -- try once more, when DB_BUFFER_SMALL cursor is not expected to move
ret = pcursor->get(&datKey, &datValue, fFlags);
};
if (ret == DB_NOTFOUND)
break;
else
if (datKey.get_data() == NULL || datValue.get_data() == NULL
|| ret != 0)
{
snprintf(cbuf, sizeof(cbuf), "wallet DB error %d, %s", ret, db_strerror(ret));
throw std::runtime_error(cbuf);
};
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.SetType(SER_DISK);
ssValue.clear();
ssValue.write((char*)datKey.get_data(), datKey.get_size());
ssValue >> vchType;
std::string strType(vchType.begin(), vchType.end());
//LogPrintf("strType %s\n", strType.c_str());
if (strType == "tx")
{
uint256 hash;
ssValue >> hash;
if ((ret = pcursor->del(0)) != 0)
{
LogPrintf("Delete transaction failed %d, %s\n", ret, db_strerror(ret));
continue;
};
pwalletMain->mapWallet.erase(hash);
pwalletMain->NotifyTransactionChanged(pwalletMain, hash, CT_DELETED);
nTransactions++;
};
};
pcursor->close();
walletdb.TxnCommit();
//pwalletMain->mapWallet.clear();
if (nNodeMode == NT_THIN)
{
// reset LastFilteredHeight
walletdb.WriteLastFilteredHeight(0);
}
}
snprintf(cbuf, sizeof(cbuf), "Removed %u transactions.", nTransactions);
result.push_back(Pair("complete", std::string(cbuf)));
result.push_back(Pair("", "Reload with reloadanondata, reindex or re-download blockchain."));
return result;
}
Value scanforalltxns(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"scanforalltxns [fromHeight]\n"
"Scan blockchain for owned transactions.");
if (nNodeMode != NT_FULL)
throw std::runtime_error("Can't run in thin mode.");
Object result;
int32_t nFromHeight = 0;
CBlockIndex *pindex = pindexGenesisBlock;
if (params.size() > 0)
nFromHeight = params[0].get_int();
if (nFromHeight > 0)
{
pindex = mapBlockIndex[hashBestChain];
while (pindex->nHeight > nFromHeight
&& pindex->pprev)
pindex = pindex->pprev;
};
if (pindex == NULL)
throw std::runtime_error("Genesis Block is not set.");
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->ScanForWalletTransactions(pindex, true);
pwalletMain->ReacceptWalletTransactions();
} // cs_main, pwalletMain->cs_wallet
result.push_back(Pair("result", "Scan complete."));
return result;
}
Value scanforstealthtxns(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"scanforstealthtxns [fromHeight]\n"
"Scan blockchain for owned stealth transactions.");
Object result;
uint32_t nBlocks = 0;
uint32_t nTransactions = 0;
int32_t nFromHeight = 0;
CBlockIndex *pindex = pindexGenesisBlock;
if (params.size() > 0)
nFromHeight = params[0].get_int();
if (nFromHeight > 0)
{
pindex = mapBlockIndex[hashBestChain];
while (pindex->nHeight > nFromHeight
&& pindex->pprev)
pindex = pindex->pprev;
};
if (pindex == NULL)
throw std::runtime_error("Genesis Block is not set.");
// -- locks in AddToWalletIfInvolvingMe
bool fUpdate = true; // todo: option?
pwalletMain->nStealth = 0;
pwalletMain->nFoundStealth = 0;
while (pindex)
{
nBlocks++;
CBlock block;
block.ReadFromDisk(pindex, true);
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
if (!tx.IsStandard())
continue; // leave out coinbase and others
nTransactions++;
uint256 hash = tx.GetHash();
pwalletMain->AddToWalletIfInvolvingMe(tx, hash, &block, fUpdate);
};
pindex = pindex->pnext;
};
LogPrintf("Scanned %u blocks, %u transactions\n", nBlocks, nTransactions);
LogPrintf("Found %u stealth transactions in blockchain.\n", pwalletMain->nStealth);
LogPrintf("Found %u new owned stealth transactions.\n", pwalletMain->nFoundStealth);
char cbuf[256];
snprintf(cbuf, sizeof(cbuf), "%u new stealth transactions.", pwalletMain->nFoundStealth);
result.push_back(Pair("result", "Scan complete."));
result.push_back(Pair("found", std::string(cbuf)));
return result;
}
Value sendsdctoanon(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 5)
throw std::runtime_error(
"sendsdctoanon <stealth_address> <amount> [narration] [comment] [comment-to]\n"
"<amount> is a real number and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
std::string sEncoded = params[0].get_str();
int64_t nAmount = AmountFromValue(params[1]);
std::string sNarr;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
sNarr = params[2].get_str();
if (sNarr.length() > 24)
throw std::runtime_error("Narration must be 24 characters or less.");
CStealthAddress sxAddr;
if (!sxAddr.SetEncoded(sEncoded))
throw std::runtime_error("Invalid EclipseCrypto stealth address.");
CWalletTx wtx;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["to"] = params[4].get_str();
std::string sError;
if (!pwalletMain->SendSdcToAnon(sxAddr, nAmount, sNarr, wtx, sError))
{
LogPrintf("SendSdcToAnon failed %s\n", sError.c_str());
throw JSONRPCError(RPC_WALLET_ERROR, sError);
};
return wtx.GetHash().GetHex();
}
Value sendanontoanon(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw std::runtime_error(
"sendanontoanon <stealth_address> <amount> <ring_size> [narration] [comment] [comment-to]\n"
"<amount> is a real number and is rounded to the nearest 0.000001\n"
"<ring_size> is a number of outputs of the same amount to include in the signature"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
std::string sEncoded = params[0].get_str();
int64_t nAmount = AmountFromValue(params[1]);
uint32_t nRingSize = (uint32_t)params[2].get_int();
std::ostringstream ssThrow;
if (nRingSize < MIN_RING_SIZE || nRingSize > MAX_RING_SIZE)
ssThrow << "Ring size must be >= " << MIN_RING_SIZE << " and <= " << MAX_RING_SIZE << ".", throw std::runtime_error(ssThrow.str());
std::string sNarr;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
sNarr = params[3].get_str();
if (sNarr.length() > 24)
throw std::runtime_error("Narration must be 24 characters or less.");
CStealthAddress sxAddr;
if (!sxAddr.SetEncoded(sEncoded))
throw std::runtime_error("Invalid EclipseCrypto stealth address.");
CWalletTx wtx;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
std::string sError;
if (!pwalletMain->SendAnonToAnon(sxAddr, nAmount, nRingSize, sNarr, wtx, sError))
{
LogPrintf("SendAnonToAnon failed %s\n", sError.c_str());
throw JSONRPCError(RPC_WALLET_ERROR, sError);
};
return wtx.GetHash().GetHex();
}
Value sendanontosdc(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw std::runtime_error(
"sendanontosdc <stealth_address> <amount> <ring_size> [narration] [comment] [comment-to]\n"
"<amount> is a real number and is rounded to the nearest 0.000001\n"
"<ring_size> is a number of outputs of the same amount to include in the signature"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
std::string sEncoded = params[0].get_str();
int64_t nAmount = AmountFromValue(params[1]);
uint32_t nRingSize = (uint32_t)params[2].get_int();
std::ostringstream ssThrow;
if (nRingSize < 1 || nRingSize > MAX_RING_SIZE)
ssThrow << "Ring size must be >= 1 and <= " << MAX_RING_SIZE << ".", throw std::runtime_error(ssThrow.str());
std::string sNarr;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
sNarr = params[3].get_str();
if (sNarr.length() > 24)
throw std::runtime_error("Narration must be 24 characters or less.");
CStealthAddress sxAddr;
if (!sxAddr.SetEncoded(sEncoded))
throw std::runtime_error("Invalid EclipseCrypto stealth address.");
CWalletTx wtx;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
std::string sError;
if (!pwalletMain->SendAnonToSdc(sxAddr, nAmount, nRingSize, sNarr, wtx, sError))
{
LogPrintf("SendAnonToSdc failed %s\n", sError.c_str());
throw JSONRPCError(RPC_WALLET_ERROR, sError);
};
return wtx.GetHash().GetHex();
}
Value estimateanonfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw std::runtime_error(
"estimateanonfee <amount> <ring_size> [narration]\n"
"<amount>is a real number and is rounded to the nearest 0.000001\n"
"<ring_size> is a number of outputs of the same amount to include in the signature");
int64_t nAmount = AmountFromValue(params[0]);
uint32_t nRingSize = (uint32_t)params[1].get_int();
std::ostringstream ssThrow;
if (nRingSize < MIN_RING_SIZE || nRingSize > MAX_RING_SIZE)
ssThrow << "Ring size must be >= " << MIN_RING_SIZE << " and <= " << MAX_RING_SIZE << ".", throw std::runtime_error(ssThrow.str());
std::string sNarr;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
sNarr = params[2].get_str();
if (sNarr.length() > 24)
throw std::runtime_error("Narration must be 24 characters or less.");
CWalletTx wtx;
int64_t nFee = 0;
std::string sError;
if (!pwalletMain->EstimateAnonFee(nAmount, nRingSize, sNarr, wtx, nFee, sError))
{
LogPrintf("EstimateAnonFee failed %s\n", sError.c_str());
throw JSONRPCError(RPC_WALLET_ERROR, sError);
};
uint32_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtx, SER_NETWORK, PROTOCOL_VERSION);
Object result;
result.push_back(Pair("Estimated bytes", (int)nBytes));
result.push_back(Pair("Estimated inputs", (int)wtx.vin.size()));
result.push_back(Pair("Estimated outputs", (int)wtx.vout.size()));
result.push_back(Pair("Estimated fee", ValueFromAmount(nFee)));
return result;
}
Value anonoutputs(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw std::runtime_error(
"anonoutputs [systemTotals] [show_immature_outputs]\n"
"[systemTotals] if true displays the total no. of coins in the system.");
if (nNodeMode != NT_FULL)
throw std::runtime_error("Must be in full mode.");
bool fSystemTotals = false;
if (params.size() > 0)
{
std::string value = params[0].get_str();
if (IsStringBoolPositive(value))
fSystemTotals = true;
};
bool fMatureOnly = true;
if (params.size() > 1)
{
std::string value = params[1].get_str();
if (IsStringBoolPositive(value))
fMatureOnly = false;
};
std::list<COwnedAnonOutput> lAvailableCoins;
if (pwalletMain->ListUnspentAnonOutputs(lAvailableCoins, fMatureOnly) != 0)
throw std::runtime_error("ListUnspentAnonOutputs() failed.");
Object result;
if (!fSystemTotals)
{
result.push_back(Pair("No. of coins", "amount"));
// -- mAvailableCoins is ordered by value
char cbuf[256];
int64_t nTotal = 0;
int64_t nLast = 0;
int nCount = 0;
for (std::list<COwnedAnonOutput>::iterator it = lAvailableCoins.begin(); it != lAvailableCoins.end(); ++it)
{
if (nLast > 0 && it->nValue != nLast)
{
snprintf(cbuf, sizeof(cbuf), "%03d", nCount);
result.push_back(Pair(cbuf, ValueFromAmount(nLast)));
nCount = 0;
};
nCount++;
nLast = it->nValue;
nTotal += it->nValue;
};
if (nCount > 0)
{
snprintf(cbuf, sizeof(cbuf), "%03d", nCount);
result.push_back(Pair(cbuf, ValueFromAmount(nLast)));
};
result.push_back(Pair("total", ValueFromAmount(nTotal)));
} else
{
std::map<int64_t, int> mOutputCounts;
for (std::list<COwnedAnonOutput>::iterator it = lAvailableCoins.begin(); it != lAvailableCoins.end(); ++it)
mOutputCounts[it->nValue] = 0;
if (pwalletMain->CountAnonOutputs(mOutputCounts, fMatureOnly) != 0)
throw std::runtime_error("CountAnonOutputs() failed.");
result.push_back(Pair("No. of coins owned, No. of system coins", "amount"));
// -- lAvailableCoins is ordered by value
char cbuf[256];
int64_t nTotal = 0;
int64_t nLast = 0;
int64_t nCount = 0;
int64_t nSystemCount;
for (std::list<COwnedAnonOutput>::iterator it = lAvailableCoins.begin(); it != lAvailableCoins.end(); ++it)
{
if (nLast > 0 && it->nValue != nLast)
{
nSystemCount = mOutputCounts[nLast];
std::string str = strprintf(cbuf, sizeof(cbuf), "%04d, %04d", nCount, nSystemCount);
result.push_back(Pair(str, ValueFromAmount(nLast)));
nCount = 0;
};
nCount++;
nLast = it->nValue;
nTotal += it->nValue;
};
if (nCount > 0)
{
nSystemCount = mOutputCounts[nLast];
std::string str = strprintf(cbuf, sizeof(cbuf), "%04d, %04d", nCount, nSystemCount);
result.push_back(Pair(str, ValueFromAmount(nLast)));
};
result.push_back(Pair("total currency owned", ValueFromAmount(nTotal)));
}
return result;
}
Value anoninfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"anoninfo [recalculate]\n"
"list outputs in system.");
if (nNodeMode != NT_FULL)
throw std::runtime_error("Must be in full mode.");
bool fMatureOnly = false; // TODO: add parameter
bool fRecalculate = false;
if (params.size() > 0)
{
std::string value = params[0].get_str();
if (IsStringBoolPositive(value))
fRecalculate = true;
};
Object result;
std::list<CAnonOutputCount> lOutputCounts;
if (fRecalculate)
{
if (pwalletMain->CountAllAnonOutputs(lOutputCounts, fMatureOnly) != 0)
throw std::runtime_error("CountAllAnonOutputs() failed.");
} else
{
// TODO: make mapAnonOutputStats a vector preinitialised with all possible coin values?
for (std::map<int64_t, CAnonOutputCount>::iterator mi = mapAnonOutputStats.begin(); mi != mapAnonOutputStats.end(); ++mi)
{
bool fProcessed = false;
CAnonOutputCount aoc = mi->second;
if (aoc.nLeastDepth > 0)
aoc.nLeastDepth = nBestHeight - aoc.nLeastDepth;
for (std::list<CAnonOutputCount>::iterator it = lOutputCounts.begin(); it != lOutputCounts.end(); ++it)
{
if (aoc.nValue > it->nValue)
continue;
lOutputCounts.insert(it, aoc);
fProcessed = true;
break;
};
if (!fProcessed)
lOutputCounts.push_back(aoc);
};
};
result.push_back(Pair("No. Exists, No. Spends, Least Depth", "value"));
// -- lOutputCounts is ordered by value
char cbuf[256];
int64_t nTotalIn = 0;
int64_t nTotalOut = 0;
int64_t nTotalCoins = 0;
for (std::list<CAnonOutputCount>::iterator it = lOutputCounts.begin(); it != lOutputCounts.end(); ++it)
{
snprintf(cbuf, sizeof(cbuf), "%05d, %05d, %05d", it->nExists, it->nSpends, it->nLeastDepth);
result.push_back(Pair(cbuf, ValueFromAmount(it->nValue)));
nTotalIn += it->nValue * it->nExists;
nTotalOut += it->nValue * it->nSpends;
nTotalCoins += it->nExists;
};
result.push_back(Pair("total anon value in", ValueFromAmount(nTotalIn)));
result.push_back(Pair("total anon value out", ValueFromAmount(nTotalOut)));
result.push_back(Pair("total anon outputs", nTotalCoins));
return result;
}
Value reloadanondata(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw std::runtime_error(
"reloadanondata \n"
"clears all anon txn data from system, and runs scanforalltxns.\n"
"WARNING: Intended for development use only."
+ HelpRequiringPassphrase());
if (nNodeMode != NT_FULL)
throw std::runtime_error("Must be in full mode.");
CBlockIndex *pindex = pindexGenesisBlock;
// check from 257000, once anon transactions started
while (pindex->nHeight < (fTestNet ? 68000 : 257000) && pindex->pnext)
pindex = pindex->pnext;
Object result;
if (pindex)
{
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!pwalletMain->EraseAllAnonData())
throw std::runtime_error("EraseAllAnonData() failed.");
pwalletMain->MarkDirty();
pwalletMain->ScanForWalletTransactions(pindex, true);
pwalletMain->ReacceptWalletTransactions();
pwalletMain->CacheAnonStats();
result.push_back(Pair("result", "reloadanondata complete."));
} else
{
result.push_back(Pair("result", "reloadanondata failed - !pindex."));
};
return result;
}
static bool compareTxnTime(const CWalletTx* pa, const CWalletTx* pb)
{
return pa->nTime < pb->nTime;
};
Value txnreport(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw std::runtime_error(
"txnreport [collate_amounts] [show_key_images]\n"
"List transactions at output level.\n");
bool fCollateAmounts = false;
bool fShowKeyImage = false;
// TODO: trust CWalletTx::vfSpent?
if (params.size() > 0)
{
std::string value = params[0].get_str();
if (IsStringBoolPositive(value))
fCollateAmounts = true;
};
if (params.size() > 1)
{
std::string value = params[1].get_str();
if (IsStringBoolPositive(value))
fShowKeyImage = true;
};
int64_t nWalletIn = 0; // total inputs from owned addresses
int64_t nWalletOut = 0; // total outputs from owned addresses
Object result;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
std::list<CWalletTx*> listOrdered;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
if (it->second.GetDepthInMainChain() > 0) // exclude txns not in the chain
listOrdered.push_back(&it->second);
};
listOrdered.sort(compareTxnTime);
std::list<CWalletTx*>::iterator it;
Array headings;
headings.push_back("When");
headings.push_back("Txn Hash");
headings.push_back("In/Output Type");
headings.push_back("Txn Type");
headings.push_back("Address");
headings.push_back("Ring Size");
if (fShowKeyImage)
headings.push_back("Key Image");
headings.push_back("Owned");
headings.push_back("Spent");
headings.push_back("Value In");
headings.push_back("Value Out");
if (fCollateAmounts)
{
headings.push_back("Wallet In");
headings.push_back("Wallet Out");
};
result.push_back(Pair("headings", headings));
if (pwalletMain->IsLocked())
{
result.push_back(Pair("warning", "Wallet is locked - owned inputs may not be detected correctly."));
};
Array lines;
CTxDB txdb("r");
CWalletDB walletdb(pwalletMain->strWalletFile, "r");
char cbuf[256];
for (it = listOrdered.begin(); it != listOrdered.end(); ++it)
{
CWalletTx* pwtx = (*it);
Array entryTxn;
entryTxn.push_back(getTimeString(pwtx->nTime, cbuf, sizeof(cbuf)));
entryTxn.push_back(pwtx->GetHash().GetHex());
bool fCoinBase = pwtx->IsCoinBase();
bool fCoinStake = pwtx->IsCoinStake();
for (uint32_t i = 0; i < pwtx->vin.size(); ++i)
{
const CTxIn& txin = pwtx->vin[i];
int64_t nInputValue = 0;
Array entry = entryTxn;
std::string sAddr = "";
std::string sKeyImage = "";
bool fOwnCoin = false;
int nRingSize = 0;
if (pwtx->nVersion == ANON_TXN_VERSION
&& txin.IsAnonInput())
{
entry.push_back("eclipse in");
entry.push_back("");
std::vector<uint8_t> vchImage;
txin.ExtractKeyImage(vchImage);
nRingSize = txin.ExtractRingSize();
sKeyImage = HexStr(vchImage);
CKeyImageSpent ski;
bool fInMemPool;
if (GetKeyImage(&txdb, vchImage, ski, fInMemPool))
nInputValue = ski.nValue;
COwnedAnonOutput oao;
if (walletdb.ReadOwnedAnonOutput(vchImage, oao))
{
fOwnCoin = true;
} else
if (pwalletMain->IsCrypted())
{
// - tokens received with locked wallet won't have oao until wallet unlocked
// No way to tell if locked input is owned
// need vchImage
// TODO, closest would be to tell if it's possible for the input to be owned
sKeyImage = "locked?";
};
} else
{
if (txin.prevout.IsNull()) // coinbase
continue;
entry.push_back("sdc in");
entry.push_back(fCoinBase ? "coinbase" : fCoinStake ? "coinstake" : "");
if (pwalletMain->IsMine(txin))
fOwnCoin = true;
CTransaction prevTx;
if (txdb.ReadDiskTx(txin.prevout.hash, prevTx))
{
if (txin.prevout.n < prevTx.vout.size())
{
const CTxOut &vout = prevTx.vout[txin.prevout.n];
nInputValue = vout.nValue;
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
sAddr = CBitcoinAddress(address).ToString();
} else
{
nInputValue = 0;
};
};
};
if (fOwnCoin)
nWalletIn += nInputValue;
entry.push_back(sAddr);
entry.push_back(nRingSize == 0 ? "" : strprintf("%d", nRingSize));
if (fShowKeyImage)
entry.push_back(sKeyImage);
entry.push_back(fOwnCoin);
entry.push_back(""); // spent
entry.push_back(strprintf("%f", (double)nInputValue / (double)COIN));
entry.push_back(""); // out
if (fCollateAmounts)
{
entry.push_back(strprintf("%f", (double)nWalletIn / (double)COIN));
entry.push_back(strprintf("%f", (double)nWalletOut / (double)COIN));
};
lines.push_back(entry);
};
for (uint32_t i = 0; i < pwtx->vout.size(); i++)
{
const CTxOut& txout = pwtx->vout[i];
if (txout.nValue < 1) // metadata output, narration or stealth
continue;
Array entry = entryTxn;
std::string sAddr = "";
std::string sKeyImage = "";
bool fOwnCoin = false;
bool fSpent = false;
if (pwtx->nVersion == ANON_TXN_VERSION
&& txout.IsAnonOutput())
{
entry.push_back("eclipse out");
entry.push_back("");
CPubKey pkCoin = txout.ExtractAnonPk();
std::vector<uint8_t> vchImage;
COwnedAnonOutput oao;
if (walletdb.ReadOwnedAnonOutputLink(pkCoin, vchImage)
&& walletdb.ReadOwnedAnonOutput(vchImage, oao))
{
sKeyImage = HexStr(vchImage);
fOwnCoin = true;
} else
if (pwalletMain->IsCrypted())
{
// - tokens received with locked wallet won't have oao until wallet unlocked
CKeyID ckCoinId = pkCoin.GetID();
CLockedAnonOutput lockedAo;
if (walletdb.ReadLockedAnonOutput(ckCoinId, lockedAo))
fOwnCoin = true;
sKeyImage = "locked?";
};
} else
{
entry.push_back("sdc out");
entry.push_back(fCoinBase ? "coinbase" : fCoinStake ? "coinstake" : "");
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
sAddr = CBitcoinAddress(address).ToString();
if (pwalletMain->IsMine(txout))
fOwnCoin = true;
};
if (fOwnCoin)
{
nWalletOut += txout.nValue;
fSpent = pwtx->IsSpent(i);
};
entry.push_back(sAddr);
entry.push_back(""); // ring size (only for inputs)
if (fShowKeyImage)
entry.push_back(sKeyImage);
entry.push_back(fOwnCoin);
entry.push_back(fSpent);
entry.push_back(""); // in
entry.push_back(ValueFromAmount(txout.nValue));
if (fCollateAmounts)
{
entry.push_back(strprintf("%f", (double)nWalletIn / (double)COIN));
entry.push_back(strprintf("%f", (double)nWalletOut / (double)COIN));
};
lines.push_back(entry);
};
};
result.push_back(Pair("data", lines));
}
result.push_back(Pair("result", "txnreport complete."));
return result;
}
| EclipseCrypto/eclipse | src/rpcwallet.cpp | C++ | mit | 109,055 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
body {
/*background-color: #fff;*/
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
background-image: url("assets/img/crossword.png");
background-color: blue;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body {
margin: 0 15px 0 15px;
}
p.footer {
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/Welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>
</body>
</html> | trisamsul/ICSITech | application/views/welcome_message.php | PHP | mit | 2,138 |
package com.cccrps.gui;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemColor;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.prefs.Preferences;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import org.apache.commons.io.IOUtils;
import com.cccrps.main.Main;
import com.cccrps.main.SimpleUpdater;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GuiManager {
private JFrame frmCccrps;
/**
* Create the application.
* @throws FileNotFoundException
*/
public GuiManager() throws FileNotFoundException {
}
public JFrame getFrame(){
return frmCccrps;
}
/**
* Initialize the contents of the frame.
* @throws FileNotFoundException
* @throws UnknownHostException
* @wbp.parser.entryPoint
*/
public void initialize() throws FileNotFoundException, UnknownHostException {
frmCccrps = new JFrame();
Image icon = new ImageIcon(this.getClass().getResource("/images/icon.png")).getImage();
frmCccrps.setIconImage(icon);
frmCccrps.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e){
final Preferences prefs;
prefs = Preferences.userNodeForPackage(this.getClass());
boolean isminimized=Boolean.parseBoolean(prefs.get("checkbminimized", ""));
System.out.println(isminimized);
if(isminimized){
System.out.println("Minimizing");
frmCccrps.setExtendedState(Frame.ICONIFIED);
}
System.out.println("WindowOpened");
}
@Override
public void windowClosing(WindowEvent e){
frmCccrps.setVisible(false);
displayTrayIcon();
}
public void windowClosed(WindowEvent e){}
public void windowIconified(WindowEvent e){
frmCccrps.setVisible(false);
displayTrayIcon();
}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){
System.out.println("windowActivated");
}
public void windowDeactivated(WindowEvent e){}
});
final Preferences prefs;
prefs = Preferences.userNodeForPackage(this.getClass());
frmCccrps.setResizable(false);
frmCccrps.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frmCccrps.setTitle("CRP");
frmCccrps.setBounds(100, 100, 240, 310);
JPanel panel = new JPanel();
frmCccrps.getContentPane().add(panel, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("Catalyst Remote Profile Server");
panel.add(lblNewLabel);
JDesktopPane desktopPane = new JDesktopPane();
desktopPane.setBackground(SystemColor.menu);
frmCccrps.getContentPane().add(desktopPane, BorderLayout.CENTER);
final JCheckBox chckbxStartMinimized = new JCheckBox("Start Minimized");
chckbxStartMinimized.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
prefs.put("checkbminimized", String.valueOf(chckbxStartMinimized.isSelected()));
}
});
chckbxStartMinimized.setHorizontalAlignment(SwingConstants.CENTER);
chckbxStartMinimized.setBounds(10, 80, 212, 25);
desktopPane.add(chckbxStartMinimized);
boolean isminimized=Boolean.parseBoolean(prefs.get("checkbminimized", ""));
System.out.println(isminimized);
if(isminimized){
System.out.println("Minimizing");
chckbxStartMinimized.setSelected(true);
frmCccrps.setExtendedState(Frame.ICONIFIED);
}
JButton btnCloseServer = new JButton("Shutdown Server");
btnCloseServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnCloseServer.setBounds(10, 177, 212, 30);
desktopPane.add(btnCloseServer);
JButton btnStartOnWindows = new JButton("Website(Instructions & About)");
btnStartOnWindows.setForeground(new Color(255, 0, 0));
btnStartOnWindows.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
java.awt.Desktop.getDesktop().browse(new URI("http://goo.gl/uihUNy"));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnStartOnWindows.setBounds(10, 28, 212, 43);
desktopPane.add(btnStartOnWindows);
JLabel lblIp = new JLabel("");
lblIp.setText("IP: "+InetAddress.getLocalHost().getHostAddress());
lblIp.setHorizontalAlignment(SwingConstants.CENTER);
lblIp.setBounds(10, 148, 210, 16);
desktopPane.add(lblIp);
final JCheckBox checkBoxAutoStart = new JCheckBox("Autostart");
checkBoxAutoStart.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if(checkBoxAutoStart.isSelected()){
JOptionPane.showMessageDialog(null,"!Warning, if ServerFile(.jar) gets moved , Autostart has to be applied again!");
}
}
});
checkBoxAutoStart.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
prefs.put("autostart", String.valueOf(checkBoxAutoStart.isSelected()));
String targetpath = "C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\CRPServerAutostarter.bat";
if(checkBoxAutoStart.isSelected()){
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(targetpath), "utf-8"));
File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();
writer.write("start /min javaw -jar \""+path+"\\"+f.getName()+"\"");
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}else{
try{
File file = new File(targetpath);
file.delete();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
if(Boolean.parseBoolean(prefs.get("autostart", ""))){
checkBoxAutoStart.setSelected(true);
}else{
checkBoxAutoStart.setSelected(false);
}
checkBoxAutoStart.setHorizontalAlignment(SwingConstants.CENTER);
checkBoxAutoStart.setBounds(10, 110, 212, 25);
desktopPane.add(checkBoxAutoStart);
JLabel lblVersion = new JLabel("Version Undefined");
lblVersion.setHorizontalAlignment(SwingConstants.CENTER);
lblVersion.setBounds(41, 0, 154, 16);
lblVersion.setText("Version: "+Main.getVersion());
desktopPane.add(lblVersion);
JButton btnCheckForUpdates = new JButton("Check For Updates");
btnCheckForUpdates.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int NewVersion=Integer.parseInt(IOUtils.toString(new URL("https://flothinkspi.github.io/Catalyst-PresetSwitcher/version.json")).replace("\n", "").replace("\r", ""));
if(NewVersion>Integer.parseInt(Main.getVersion())){
int dialogResult = JOptionPane.showConfirmDialog (null, "Update found from "+Main.getVersion()+" to "+NewVersion+" ,Update now ?","CRPServer Updater",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
System.out.println(decodedPath);
SimpleUpdater.update(new URL("https://flothinkspi.github.io/Catalyst-PresetSwitcher/download/CRPServer.jar"),new File(decodedPath) , "updated");
System.exit(0);
}
}else{
JOptionPane.showConfirmDialog (null, "No Updates , You have the latest CRPServer(Version:"+Main.getVersion()+")","CRPServer Updater",JOptionPane.PLAIN_MESSAGE);
}
} catch (NumberFormatException | HeadlessException
| IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnCheckForUpdates.setBounds(10, 213, 212, 30);
desktopPane.add(btnCheckForUpdates);
frmCccrps.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
frmCccrps.setExtendedState(Frame.ICONIFIED);
}
});
}
public void displayTrayIcon(){
final TrayIcon trayIcon;
if (SystemTray.isSupported()) {
final SystemTray tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/icon.gif"));
PopupMenu popup = new PopupMenu();
trayIcon = new TrayIcon(image, "CCCRPS", popup);
trayIcon.setImageAutoSize(true);
//trayIcon.addMouseListener(mouseListener);
MenuItem defaultItem = new MenuItem("Stop Server");
defaultItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
popup.add(defaultItem);
trayIcon.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) {
frmCccrps.setVisible(true);
frmCccrps.setState ( Frame.NORMAL );
tray.remove(trayIcon);
}
}
});
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println("TrayIcon could not be added.");
}
} else {
System.err.println("System tray is currently not supported.");
}
}
}
| FloThinksPi/Catalyst-PresetSwitcher | Server/src/com/cccrps/gui/GuiManager.java | Java | mit | 11,468 |
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// @version 0.7.21
"undefined" == typeof WeakMap && !function () {
var e = Object.defineProperty, t = Date.now() % 1e9, n = function () {
this.name = "__st" + (1e9 * Math.random() >>> 0) + (t++ + "__")
};
n.prototype = {
set: function (t, n) {
var r = t[this.name];
return r && r[0] === t ? r[1] = n : e(t, this.name, {value: [t, n], writable: !0}), this
}, get: function (e) {
var t;
return (t = e[this.name]) && t[0] === e ? t[1] : void 0
}, "delete": function (e) {
var t = e[this.name];
return t && t[0] === e ? (t[0] = t[1] = void 0, !0) : !1
}, has: function (e) {
var t = e[this.name];
return t ? t[0] === e : !1
}
}, window.WeakMap = n
}(), window.ShadowDOMPolyfill = {}, function (e) {
"use strict";
function t() {
if ("undefined" != typeof chrome && chrome.app && chrome.app.runtime)return !1;
if (navigator.getDeviceStorage)return !1;
try {
var e = new Function("return true;");
return e()
} catch (t) {
return !1
}
}
function n(e) {
if (!e)throw new Error("Assertion failed")
}
function r(e, t) {
for (var n = k(t), r = 0; r < n.length; r++) {
var o = n[r];
A(e, o, F(t, o))
}
return e
}
function o(e, t) {
for (var n = k(t), r = 0; r < n.length; r++) {
var o = n[r];
switch (o) {
case"arguments":
case"caller":
case"length":
case"name":
case"prototype":
case"toString":
continue
}
A(e, o, F(t, o))
}
return e
}
function i(e, t) {
for (var n = 0; n < t.length; n++)if (t[n] in e)return t[n]
}
function a(e, t, n) {
B.value = n, A(e, t, B)
}
function s(e, t) {
var n = e.__proto__ || Object.getPrototypeOf(e);
if (U)try {
k(n)
} catch (r) {
n = n.__proto__
}
var o = R.get(n);
if (o)return o;
var i = s(n), a = E(i);
return v(n, a, t), a
}
function c(e, t) {
m(e, t, !0)
}
function u(e, t) {
m(t, e, !1)
}
function l(e) {
return /^on[a-z]+$/.test(e)
}
function p(e) {
return /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(e)
}
function d(e) {
return I && p(e) ? new Function("return this.__impl4cf1e782hg__." + e) : function () {
return this.__impl4cf1e782hg__[e]
}
}
function f(e) {
return I && p(e) ? new Function("v", "this.__impl4cf1e782hg__." + e + " = v") : function (t) {
this.__impl4cf1e782hg__[e] = t
}
}
function h(e) {
return I && p(e) ? new Function("return this.__impl4cf1e782hg__." + e + ".apply(this.__impl4cf1e782hg__, arguments)") : function () {
return this.__impl4cf1e782hg__[e].apply(this.__impl4cf1e782hg__, arguments)
}
}
function w(e, t) {
try {
return Object.getOwnPropertyDescriptor(e, t)
} catch (n) {
return q
}
}
function m(t, n, r, o) {
for (var i = k(t), a = 0; a < i.length; a++) {
var s = i[a];
if ("polymerBlackList_" !== s && !(s in n || t.polymerBlackList_ && t.polymerBlackList_[s])) {
U && t.__lookupGetter__(s);
var c, u, p = w(t, s);
if ("function" != typeof p.value) {
var m = l(s);
c = m ? e.getEventHandlerGetter(s) : d(s), (p.writable || p.set || V) && (u = m ? e.getEventHandlerSetter(s) : f(s));
var g = V || p.configurable;
A(n, s, {get: c, set: u, configurable: g, enumerable: p.enumerable})
} else r && (n[s] = h(s))
}
}
}
function g(e, t, n) {
if (null != e) {
var r = e.prototype;
v(r, t, n), o(t, e)
}
}
function v(e, t, r) {
var o = t.prototype;
n(void 0 === R.get(e)), R.set(e, t), P.set(o, e), c(e, o), r && u(o, r), a(o, "constructor", t), t.prototype = o
}
function b(e, t) {
return R.get(t.prototype) === e
}
function y(e) {
var t = Object.getPrototypeOf(e), n = s(t), r = E(n);
return v(t, r, e), r
}
function E(e) {
function t(t) {
e.call(this, t)
}
var n = Object.create(e.prototype);
return n.constructor = t, t.prototype = n, t
}
function S(e) {
return e && e.__impl4cf1e782hg__
}
function M(e) {
return !S(e)
}
function T(e) {
if (null === e)return null;
n(M(e));
var t = e.__wrapper8e3dd93a60__;
return null != t ? t : e.__wrapper8e3dd93a60__ = new (s(e, e))(e)
}
function O(e) {
return null === e ? null : (n(S(e)), e.__impl4cf1e782hg__)
}
function N(e) {
return e.__impl4cf1e782hg__
}
function j(e, t) {
t.__impl4cf1e782hg__ = e, e.__wrapper8e3dd93a60__ = t
}
function L(e) {
return e && S(e) ? O(e) : e
}
function _(e) {
return e && !S(e) ? T(e) : e
}
function D(e, t) {
null !== t && (n(M(e)), n(void 0 === t || S(t)), e.__wrapper8e3dd93a60__ = t)
}
function C(e, t, n) {
G.get = n, A(e.prototype, t, G)
}
function H(e, t) {
C(e, t, function () {
return T(this.__impl4cf1e782hg__[t])
})
}
function x(e, t) {
e.forEach(function (e) {
t.forEach(function (t) {
e.prototype[t] = function () {
var e = _(this);
return e[t].apply(e, arguments)
}
})
})
}
var R = new WeakMap, P = new WeakMap, W = Object.create(null), I = t(), A = Object.defineProperty, k = Object.getOwnPropertyNames, F = Object.getOwnPropertyDescriptor, B = {
value: void 0,
configurable: !0,
enumerable: !1,
writable: !0
};
k(window);
var U = /Firefox/.test(navigator.userAgent), q = {
get: function () {
}, set: function (e) {
}, configurable: !0, enumerable: !0
}, V = function () {
var e = Object.getOwnPropertyDescriptor(Node.prototype, "nodeType");
return e && !e.get && !e.set
}(), G = {get: void 0, configurable: !0, enumerable: !0};
e.addForwardingProperties = c, e.assert = n, e.constructorTable = R, e.defineGetter = C, e.defineWrapGetter = H, e.forwardMethodsToWrapper = x, e.isIdentifierName = p, e.isWrapper = S, e.isWrapperFor = b, e.mixin = r, e.nativePrototypeTable = P, e.oneOf = i, e.registerObject = y, e.registerWrapper = g, e.rewrap = D, e.setWrapper = j, e.unsafeUnwrap = N, e.unwrap = O, e.unwrapIfNeeded = L, e.wrap = T, e.wrapIfNeeded = _, e.wrappers = W
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e, t, n) {
return {index: e, removed: t, addedCount: n}
}
function n() {
}
var r = 0, o = 1, i = 2, a = 3;
n.prototype = {
calcEditDistances: function (e, t, n, r, o, i) {
for (var a = i - o + 1, s = n - t + 1, c = new Array(a), u = 0; a > u; u++)c[u] = new Array(s), c[u][0] = u;
for (var l = 0; s > l; l++)c[0][l] = l;
for (var u = 1; a > u; u++)for (var l = 1; s > l; l++)if (this.equals(e[t + l - 1], r[o + u - 1]))c[u][l] = c[u - 1][l - 1]; else {
var p = c[u - 1][l] + 1, d = c[u][l - 1] + 1;
c[u][l] = d > p ? p : d
}
return c
}, spliceOperationsFromEditDistances: function (e) {
for (var t = e.length - 1, n = e[0].length - 1, s = e[t][n], c = []; t > 0 || n > 0;)if (0 != t)if (0 != n) {
var u, l = e[t - 1][n - 1], p = e[t - 1][n], d = e[t][n - 1];
u = d > p ? l > p ? p : l : l > d ? d : l, u == l ? (l == s ? c.push(r) : (c.push(o), s = l), t--, n--) : u == p ? (c.push(a), t--, s = p) : (c.push(i), n--, s = d)
} else c.push(a), t--; else c.push(i), n--;
return c.reverse(), c
}, calcSplices: function (e, n, s, c, u, l) {
var p = 0, d = 0, f = Math.min(s - n, l - u);
if (0 == n && 0 == u && (p = this.sharedPrefix(e, c, f)), s == e.length && l == c.length && (d = this.sharedSuffix(e, c, f - p)), n += p, u += p, s -= d, l -= d, s - n == 0 && l - u == 0)return [];
if (n == s) {
for (var h = t(n, [], 0); l > u;)h.removed.push(c[u++]);
return [h]
}
if (u == l)return [t(n, [], s - n)];
for (var w = this.spliceOperationsFromEditDistances(this.calcEditDistances(e, n, s, c, u, l)), h = void 0, m = [], g = n, v = u, b = 0; b < w.length; b++)switch (w[b]) {
case r:
h && (m.push(h), h = void 0), g++, v++;
break;
case o:
h || (h = t(g, [], 0)), h.addedCount++, g++, h.removed.push(c[v]), v++;
break;
case i:
h || (h = t(g, [], 0)), h.addedCount++, g++;
break;
case a:
h || (h = t(g, [], 0)), h.removed.push(c[v]), v++
}
return h && m.push(h), m
}, sharedPrefix: function (e, t, n) {
for (var r = 0; n > r; r++)if (!this.equals(e[r], t[r]))return r;
return n
}, sharedSuffix: function (e, t, n) {
for (var r = e.length, o = t.length, i = 0; n > i && this.equals(e[--r], t[--o]);)i++;
return i
}, calculateSplices: function (e, t) {
return this.calcSplices(e, 0, e.length, t, 0, t.length)
}, equals: function (e, t) {
return e === t
}
}, e.ArraySplice = n
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t() {
a = !1;
var e = i.slice(0);
i = [];
for (var t = 0; t < e.length; t++)(0, e[t])()
}
function n(e) {
i.push(e), a || (a = !0, r(t, 0))
}
var r, o = window.MutationObserver, i = [], a = !1;
if (o) {
var s = 1, c = new o(t), u = document.createTextNode(s);
c.observe(u, {characterData: !0}), r = function () {
s = (s + 1) % 2, u.data = s
}
} else r = window.setTimeout;
e.setEndOfMicrotask = n
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
e.scheduled_ || (e.scheduled_ = !0, h.push(e), w || (l(n), w = !0))
}
function n() {
for (w = !1; h.length;) {
var e = h;
h = [], e.sort(function (e, t) {
return e.uid_ - t.uid_
});
for (var t = 0; t < e.length; t++) {
var n = e[t];
n.scheduled_ = !1;
var r = n.takeRecords();
i(n), r.length && n.callback_(r, n)
}
}
}
function r(e, t) {
this.type = e, this.target = t, this.addedNodes = new d.NodeList, this.removedNodes = new d.NodeList, this.previousSibling = null, this.nextSibling = null, this.attributeName = null, this.attributeNamespace = null, this.oldValue = null
}
function o(e, t) {
for (; e; e = e.parentNode) {
var n = f.get(e);
if (n)for (var r = 0; r < n.length; r++) {
var o = n[r];
o.options.subtree && o.addTransientObserver(t)
}
}
}
function i(e) {
for (var t = 0; t < e.nodes_.length; t++) {
var n = e.nodes_[t], r = f.get(n);
if (!r)return;
for (var o = 0; o < r.length; o++) {
var i = r[o];
i.observer === e && i.removeTransientObservers()
}
}
}
function a(e, n, o) {
for (var i = Object.create(null), a = Object.create(null), s = e; s; s = s.parentNode) {
var c = f.get(s);
if (c)for (var u = 0; u < c.length; u++) {
var l = c[u], p = l.options;
if ((s === e || p.subtree) && ("attributes" !== n || p.attributes) && ("attributes" !== n || !p.attributeFilter || null === o.namespace && -1 !== p.attributeFilter.indexOf(o.name)) && ("characterData" !== n || p.characterData) && ("childList" !== n || p.childList)) {
var d = l.observer;
i[d.uid_] = d, ("attributes" === n && p.attributeOldValue || "characterData" === n && p.characterDataOldValue) && (a[d.uid_] = o.oldValue)
}
}
}
for (var h in i) {
var d = i[h], w = new r(n, e);
"name" in o && "namespace" in o && (w.attributeName = o.name, w.attributeNamespace = o.namespace), o.addedNodes && (w.addedNodes = o.addedNodes), o.removedNodes && (w.removedNodes = o.removedNodes), o.previousSibling && (w.previousSibling = o.previousSibling), o.nextSibling && (w.nextSibling = o.nextSibling), void 0 !== a[h] && (w.oldValue = a[h]), t(d), d.records_.push(w)
}
}
function s(e) {
if (this.childList = !!e.childList, this.subtree = !!e.subtree, "attributes" in e || !("attributeOldValue" in e || "attributeFilter" in e) ? this.attributes = !!e.attributes : this.attributes = !0, "characterDataOldValue" in e && !("characterData" in e) ? this.characterData = !0 : this.characterData = !!e.characterData, !this.attributes && (e.attributeOldValue || "attributeFilter" in e) || !this.characterData && e.characterDataOldValue)throw new TypeError;
if (this.characterData = !!e.characterData, this.attributeOldValue = !!e.attributeOldValue, this.characterDataOldValue = !!e.characterDataOldValue, "attributeFilter" in e) {
if (null == e.attributeFilter || "object" != typeof e.attributeFilter)throw new TypeError;
this.attributeFilter = m.call(e.attributeFilter)
} else this.attributeFilter = null
}
function c(e) {
this.callback_ = e, this.nodes_ = [], this.records_ = [], this.uid_ = ++g, this.scheduled_ = !1
}
function u(e, t, n) {
this.observer = e, this.target = t, this.options = n, this.transientObservedNodes = []
}
var l = e.setEndOfMicrotask, p = e.wrapIfNeeded, d = e.wrappers, f = new WeakMap, h = [], w = !1, m = Array.prototype.slice, g = 0;
c.prototype = {
constructor: c, observe: function (e, t) {
e = p(e);
var n, r = new s(t), o = f.get(e);
o || f.set(e, o = []);
for (var i = 0; i < o.length; i++)o[i].observer === this && (n = o[i], n.removeTransientObservers(), n.options = r);
n || (n = new u(this, e, r), o.push(n), this.nodes_.push(e))
}, disconnect: function () {
this.nodes_.forEach(function (e) {
for (var t = f.get(e), n = 0; n < t.length; n++) {
var r = t[n];
if (r.observer === this) {
t.splice(n, 1);
break
}
}
}, this), this.records_ = []
}, takeRecords: function () {
var e = this.records_;
return this.records_ = [], e
}
}, u.prototype = {
addTransientObserver: function (e) {
if (e !== this.target) {
t(this.observer), this.transientObservedNodes.push(e);
var n = f.get(e);
n || f.set(e, n = []), n.push(this)
}
}, removeTransientObservers: function () {
var e = this.transientObservedNodes;
this.transientObservedNodes = [];
for (var t = 0; t < e.length; t++)for (var n = e[t], r = f.get(n), o = 0; o < r.length; o++)if (r[o] === this) {
r.splice(o, 1);
break
}
}
}, e.enqueueMutation = a, e.registerTransientObservers = o, e.wrappers.MutationObserver = c, e.wrappers.MutationRecord = r
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e, t) {
this.root = e, this.parent = t
}
function n(e, t) {
if (e.treeScope_ !== t) {
e.treeScope_ = t;
for (var r = e.shadowRoot; r; r = r.olderShadowRoot)r.treeScope_.parent = t;
for (var o = e.firstChild; o; o = o.nextSibling)n(o, t)
}
}
function r(n) {
if (n instanceof e.wrappers.Window, n.treeScope_)return n.treeScope_;
var o, i = n.parentNode;
return o = i ? r(i) : new t(n, null), n.treeScope_ = o
}
t.prototype = {
get renderer() {
return this.root instanceof e.wrappers.ShadowRoot ? e.getRendererForHost(this.root.host) : null
}, contains: function (e) {
for (; e; e = e.parent)if (e === this)return !0;
return !1
}
}, e.TreeScope = t, e.getTreeScope = r, e.setTreeScope = n
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
return e instanceof G.ShadowRoot
}
function n(e) {
return A(e).root
}
function r(e, r) {
var s = [], c = e;
for (s.push(c); c;) {
var u = a(c);
if (u && u.length > 0) {
for (var l = 0; l < u.length; l++) {
var d = u[l];
if (i(d)) {
var f = n(d), h = f.olderShadowRoot;
h && s.push(h)
}
s.push(d)
}
c = u[u.length - 1]
} else if (t(c)) {
if (p(e, c) && o(r))break;
c = c.host, s.push(c)
} else c = c.parentNode, c && s.push(c)
}
return s
}
function o(e) {
if (!e)return !1;
switch (e.type) {
case"abort":
case"error":
case"select":
case"change":
case"load":
case"reset":
case"resize":
case"scroll":
case"selectstart":
return !0
}
return !1
}
function i(e) {
return e instanceof HTMLShadowElement
}
function a(t) {
return e.getDestinationInsertionPoints(t)
}
function s(e, t) {
if (0 === e.length)return t;
t instanceof G.Window && (t = t.document);
for (var n = A(t), r = e[0], o = A(r), i = u(n, o), a = 0; a < e.length; a++) {
var s = e[a];
if (A(s) === i)return s
}
return e[e.length - 1]
}
function c(e) {
for (var t = []; e; e = e.parent)t.push(e);
return t
}
function u(e, t) {
for (var n = c(e), r = c(t), o = null; n.length > 0 && r.length > 0;) {
var i = n.pop(), a = r.pop();
if (i !== a)break;
o = i
}
return o
}
function l(e, t, n) {
t instanceof G.Window && (t = t.document);
var o, i = A(t), a = A(n), s = r(n, e), o = u(i, a);
o || (o = a.root);
for (var c = o; c; c = c.parent)for (var l = 0; l < s.length; l++) {
var p = s[l];
if (A(p) === c)return p
}
return null
}
function p(e, t) {
return A(e) === A(t)
}
function d(e) {
if (!X.get(e) && (X.set(e, !0), h(V(e), V(e.target)), W)) {
var t = W;
throw W = null, t
}
}
function f(e) {
switch (e.type) {
case"load":
case"beforeunload":
case"unload":
return !0
}
return !1
}
function h(t, n) {
if (K.get(t))throw new Error("InvalidStateError");
K.set(t, !0), e.renderAllPending();
var o, i, a;
if (f(t) && !t.bubbles) {
var s = n;
s instanceof G.Document && (a = s.defaultView) && (i = s, o = [])
}
if (!o)if (n instanceof G.Window)a = n, o = []; else if (o = r(n, t), !f(t)) {
var s = o[o.length - 1];
s instanceof G.Document && (a = s.defaultView)
}
return ne.set(t, o), w(t, o, a, i) && m(t, o, a, i) && g(t, o, a, i), J.set(t, re), $["delete"](t, null), K["delete"](t), t.defaultPrevented
}
function w(e, t, n, r) {
var o = oe;
if (n && !v(n, e, o, t, r))return !1;
for (var i = t.length - 1; i > 0; i--)if (!v(t[i], e, o, t, r))return !1;
return !0
}
function m(e, t, n, r) {
var o = ie, i = t[0] || n;
return v(i, e, o, t, r)
}
function g(e, t, n, r) {
for (var o = ae, i = 1; i < t.length; i++)if (!v(t[i], e, o, t, r))return;
n && t.length > 0 && v(n, e, o, t, r)
}
function v(e, t, n, r, o) {
var i = z.get(e);
if (!i)return !0;
var a = o || s(r, e);
if (a === e) {
if (n === oe)return !0;
n === ae && (n = ie)
} else if (n === ae && !t.bubbles)return !0;
if ("relatedTarget" in t) {
var c = q(t), u = c.relatedTarget;
if (u) {
if (u instanceof Object && u.addEventListener) {
var p = V(u), d = l(t, e, p);
if (d === a)return !0
} else d = null;
Z.set(t, d)
}
}
J.set(t, n);
var f = t.type, h = !1;
Y.set(t, a), $.set(t, e), i.depth++;
for (var w = 0, m = i.length; m > w; w++) {
var g = i[w];
if (g.removed)h = !0; else if (!(g.type !== f || !g.capture && n === oe || g.capture && n === ae))try {
if ("function" == typeof g.handler ? g.handler.call(e, t) : g.handler.handleEvent(t), ee.get(t))return !1
} catch (v) {
W || (W = v)
}
}
if (i.depth--, h && 0 === i.depth) {
var b = i.slice();
i.length = 0;
for (var w = 0; w < b.length; w++)b[w].removed || i.push(b[w])
}
return !Q.get(t)
}
function b(e, t, n) {
this.type = e, this.handler = t, this.capture = Boolean(n)
}
function y(e, t) {
if (!(e instanceof se))return V(T(se, "Event", e, t));
var n = e;
return be || "beforeunload" !== n.type || this instanceof O ? void B(n, this) : new O(n)
}
function E(e) {
return e && e.relatedTarget ? Object.create(e, {relatedTarget: {value: q(e.relatedTarget)}}) : e
}
function S(e, t, n) {
var r = window[e], o = function (t, n) {
return t instanceof r ? void B(t, this) : V(T(r, e, t, n))
};
if (o.prototype = Object.create(t.prototype), n && k(o.prototype, n), r)try {
F(r, o, new r("temp"))
} catch (i) {
F(r, o, document.createEvent(e))
}
return o
}
function M(e, t) {
return function () {
arguments[t] = q(arguments[t]);
var n = q(this);
n[e].apply(n, arguments)
}
}
function T(e, t, n, r) {
if (ge)return new e(n, E(r));
var o = q(document.createEvent(t)), i = me[t], a = [n];
return Object.keys(i).forEach(function (e) {
var t = null != r && e in r ? r[e] : i[e];
"relatedTarget" === e && (t = q(t)), a.push(t)
}), o["init" + t].apply(o, a), o
}
function O(e) {
y.call(this, e)
}
function N(e) {
return "function" == typeof e ? !0 : e && e.handleEvent
}
function j(e) {
switch (e) {
case"DOMAttrModified":
case"DOMAttributeNameChanged":
case"DOMCharacterDataModified":
case"DOMElementNameChanged":
case"DOMNodeInserted":
case"DOMNodeInsertedIntoDocument":
case"DOMNodeRemoved":
case"DOMNodeRemovedFromDocument":
case"DOMSubtreeModified":
return !0
}
return !1
}
function L(e) {
B(e, this)
}
function _(e) {
return e instanceof G.ShadowRoot && (e = e.host), q(e)
}
function D(e, t) {
var n = z.get(e);
if (n)for (var r = 0; r < n.length; r++)if (!n[r].removed && n[r].type === t)return !0;
return !1
}
function C(e, t) {
for (var n = q(e); n; n = n.parentNode)if (D(V(n), t))return !0;
return !1
}
function H(e) {
I(e, Ee)
}
function x(t, n, o, i) {
e.renderAllPending();
var a = V(Se.call(U(n), o, i));
if (!a)return null;
var c = r(a, null), u = c.lastIndexOf(t);
return -1 == u ? null : (c = c.slice(0, u), s(c, t))
}
function R(e) {
return function () {
var t = te.get(this);
return t && t[e] && t[e].value || null
}
}
function P(e) {
var t = e.slice(2);
return function (n) {
var r = te.get(this);
r || (r = Object.create(null), te.set(this, r));
var o = r[e];
if (o && this.removeEventListener(t, o.wrapped, !1), "function" == typeof n) {
var i = function (t) {
var r = n.call(this, t);
r === !1 ? t.preventDefault() : "onbeforeunload" === e && "string" == typeof r && (t.returnValue = r)
};
this.addEventListener(t, i, !1), r[e] = {value: n, wrapped: i}
}
}
}
var W, I = e.forwardMethodsToWrapper, A = e.getTreeScope, k = e.mixin, F = e.registerWrapper, B = e.setWrapper, U = e.unsafeUnwrap, q = e.unwrap, V = e.wrap, G = e.wrappers, z = (new WeakMap, new WeakMap), X = new WeakMap, K = new WeakMap, Y = new WeakMap, $ = new WeakMap, Z = new WeakMap, J = new WeakMap, Q = new WeakMap, ee = new WeakMap, te = new WeakMap, ne = new WeakMap, re = 0, oe = 1, ie = 2, ae = 3;
b.prototype = {
equals: function (e) {
return this.handler === e.handler && this.type === e.type && this.capture === e.capture
}, get removed() {
return null === this.handler
}, remove: function () {
this.handler = null
}
};
var se = window.Event;
se.prototype.polymerBlackList_ = {returnValue: !0, keyLocation: !0}, y.prototype = {
get target() {
return Y.get(this)
}, get currentTarget() {
return $.get(this)
}, get eventPhase() {
return J.get(this)
}, get path() {
var e = ne.get(this);
return e ? e.slice() : []
}, stopPropagation: function () {
Q.set(this, !0)
}, stopImmediatePropagation: function () {
Q.set(this, !0), ee.set(this, !0)
}
};
var ce = function () {
var e = document.createEvent("Event");
return e.initEvent("test", !0, !0), e.preventDefault(), e.defaultPrevented
}();
ce || (y.prototype.preventDefault = function () {
this.cancelable && (U(this).preventDefault(), Object.defineProperty(this, "defaultPrevented", {
get: function () {
return !0
}, configurable: !0
}))
}), F(se, y, document.createEvent("Event"));
var ue = S("UIEvent", y), le = S("CustomEvent", y), pe = {
get relatedTarget() {
var e = Z.get(this);
return void 0 !== e ? e : V(q(this).relatedTarget)
}
}, de = k({initMouseEvent: M("initMouseEvent", 14)}, pe), fe = k({initFocusEvent: M("initFocusEvent", 5)}, pe), he = S("MouseEvent", ue, de), we = S("FocusEvent", ue, fe), me = Object.create(null), ge = function () {
try {
new window.FocusEvent("focus")
} catch (e) {
return !1
}
return !0
}();
if (!ge) {
var ve = function (e, t, n) {
if (n) {
var r = me[n];
t = k(k({}, r), t)
}
me[e] = t
};
ve("Event", {
bubbles: !1,
cancelable: !1
}), ve("CustomEvent", {detail: null}, "Event"), ve("UIEvent", {
view: null,
detail: 0
}, "Event"), ve("MouseEvent", {
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
ctrlKey: !1,
altKey: !1,
shiftKey: !1,
metaKey: !1,
button: 0,
relatedTarget: null
}, "UIEvent"), ve("FocusEvent", {relatedTarget: null}, "UIEvent")
}
var be = window.BeforeUnloadEvent;
O.prototype = Object.create(y.prototype), k(O.prototype, {
get returnValue() {
return U(this).returnValue
}, set returnValue(e) {
U(this).returnValue = e
}
}), be && F(be, O);
var ye = window.EventTarget, Ee = ["addEventListener", "removeEventListener", "dispatchEvent"];
[Node, Window].forEach(function (e) {
var t = e.prototype;
Ee.forEach(function (e) {
Object.defineProperty(t, e + "_", {value: t[e]})
})
}), L.prototype = {
addEventListener: function (e, t, n) {
if (N(t) && !j(e)) {
var r = new b(e, t, n), o = z.get(this);
if (o) {
for (var i = 0; i < o.length; i++)if (r.equals(o[i]))return
} else o = [], o.depth = 0, z.set(this, o);
o.push(r);
var a = _(this);
a.addEventListener_(e, d, !0)
}
}, removeEventListener: function (e, t, n) {
n = Boolean(n);
var r = z.get(this);
if (r) {
for (var o = 0, i = !1, a = 0; a < r.length; a++)r[a].type === e && r[a].capture === n && (o++, r[a].handler === t && (i = !0, r[a].remove()));
if (i && 1 === o) {
var s = _(this);
s.removeEventListener_(e, d, !0)
}
}
}, dispatchEvent: function (t) {
var n = q(t), r = n.type;
X.set(n, !1), e.renderAllPending();
var o;
C(this, r) || (o = function () {
}, this.addEventListener(r, o, !0));
try {
return q(this).dispatchEvent_(n)
} finally {
o && this.removeEventListener(r, o, !0)
}
}
}, ye && F(ye, L);
var Se = document.elementFromPoint;
e.elementFromPoint = x, e.getEventHandlerGetter = R, e.getEventHandlerSetter = P, e.wrapEventTargetMethods = H, e.wrappers.BeforeUnloadEvent = O, e.wrappers.CustomEvent = le, e.wrappers.Event = y, e.wrappers.EventTarget = L, e.wrappers.FocusEvent = we, e.wrappers.MouseEvent = he, e.wrappers.UIEvent = ue
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e, t) {
Object.defineProperty(e, t, w)
}
function n(e) {
u(e, this)
}
function r() {
this.length = 0, t(this, "length")
}
function o(e) {
for (var t = new r, o = 0; o < e.length; o++)t[o] = new n(e[o]);
return t.length = o, t
}
function i(e) {
a.call(this, e)
}
var a = e.wrappers.UIEvent, s = e.mixin, c = e.registerWrapper, u = e.setWrapper, l = e.unsafeUnwrap, p = e.wrap, d = window.TouchEvent;
if (d) {
var f;
try {
f = document.createEvent("TouchEvent")
} catch (h) {
return
}
var w = {enumerable: !1};
n.prototype = {
get target() {
return p(l(this).target)
}
};
var m = {configurable: !0, enumerable: !0, get: null};
["clientX", "clientY", "screenX", "screenY", "pageX", "pageY", "identifier", "webkitRadiusX", "webkitRadiusY", "webkitRotationAngle", "webkitForce"].forEach(function (e) {
m.get = function () {
return l(this)[e]
}, Object.defineProperty(n.prototype, e, m)
}), r.prototype = {
item: function (e) {
return this[e]
}
}, i.prototype = Object.create(a.prototype), s(i.prototype, {
get touches() {
return o(l(this).touches)
}, get targetTouches() {
return o(l(this).targetTouches)
}, get changedTouches() {
return o(l(this).changedTouches)
}, initTouchEvent: function () {
throw new Error("Not implemented")
}
}), c(d, i, f), e.wrappers.Touch = n, e.wrappers.TouchEvent = i, e.wrappers.TouchList = r
}
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e, t) {
Object.defineProperty(e, t, s)
}
function n() {
this.length = 0, t(this, "length")
}
function r(e) {
if (null == e)return e;
for (var t = new n, r = 0, o = e.length; o > r; r++)t[r] = a(e[r]);
return t.length = o, t
}
function o(e, t) {
e.prototype[t] = function () {
return r(i(this)[t].apply(i(this), arguments))
}
}
var i = e.unsafeUnwrap, a = e.wrap, s = {enumerable: !1};
n.prototype = {
item: function (e) {
return this[e]
}
}, t(n.prototype, "item"), e.wrappers.NodeList = n, e.addWrapNodeListMethod = o, e.wrapNodeList = r
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
e.wrapHTMLCollection = e.wrapNodeList, e.wrappers.HTMLCollection = e.wrappers.NodeList
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
N(e instanceof S)
}
function n(e) {
var t = new T;
return t[0] = e, t.length = 1, t
}
function r(e, t, n) {
L(t, "childList", {removedNodes: n, previousSibling: e.previousSibling, nextSibling: e.nextSibling})
}
function o(e, t) {
L(e, "childList", {removedNodes: t})
}
function i(e, t, r, o) {
if (e instanceof DocumentFragment) {
var i = s(e);
B = !0;
for (var a = i.length - 1; a >= 0; a--)e.removeChild(i[a]), i[a].parentNode_ = t;
B = !1;
for (var a = 0; a < i.length; a++)i[a].previousSibling_ = i[a - 1] || r, i[a].nextSibling_ = i[a + 1] || o;
return r && (r.nextSibling_ = i[0]), o && (o.previousSibling_ = i[i.length - 1]), i
}
var i = n(e), c = e.parentNode;
return c && c.removeChild(e), e.parentNode_ = t, e.previousSibling_ = r, e.nextSibling_ = o, r && (r.nextSibling_ = e), o && (o.previousSibling_ = e), i
}
function a(e) {
if (e instanceof DocumentFragment)return s(e);
var t = n(e), o = e.parentNode;
return o && r(e, o, t), t
}
function s(e) {
for (var t = new T, n = 0, r = e.firstChild; r; r = r.nextSibling)t[n++] = r;
return t.length = n, o(e, t), t
}
function c(e) {
return e
}
function u(e, t) {
R(e, t), e.nodeIsInserted_()
}
function l(e, t) {
for (var n = _(t), r = 0; r < e.length; r++)u(e[r], n)
}
function p(e) {
R(e, new O(e, null))
}
function d(e) {
for (var t = 0; t < e.length; t++)p(e[t])
}
function f(e, t) {
var n = e.nodeType === S.DOCUMENT_NODE ? e : e.ownerDocument;
n !== t.ownerDocument && n.adoptNode(t)
}
function h(t, n) {
if (n.length) {
var r = t.ownerDocument;
if (r !== n[0].ownerDocument)for (var o = 0; o < n.length; o++)e.adoptNodeNoRemove(n[o], r)
}
}
function w(e, t) {
h(e, t);
var n = t.length;
if (1 === n)return W(t[0]);
for (var r = W(e.ownerDocument.createDocumentFragment()), o = 0; n > o; o++)r.appendChild(W(t[o]));
return r
}
function m(e) {
if (void 0 !== e.firstChild_)for (var t = e.firstChild_; t;) {
var n = t;
t = t.nextSibling_, n.parentNode_ = n.previousSibling_ = n.nextSibling_ = void 0
}
e.firstChild_ = e.lastChild_ = void 0
}
function g(e) {
if (e.invalidateShadowRenderer()) {
for (var t = e.firstChild; t;) {
N(t.parentNode === e);
var n = t.nextSibling, r = W(t), o = r.parentNode;
o && Y.call(o, r), t.previousSibling_ = t.nextSibling_ = t.parentNode_ = null, t = n
}
e.firstChild_ = e.lastChild_ = null
} else for (var n, i = W(e), a = i.firstChild; a;)n = a.nextSibling, Y.call(i, a), a = n
}
function v(e) {
var t = e.parentNode;
return t && t.invalidateShadowRenderer()
}
function b(e) {
for (var t, n = 0; n < e.length; n++)t = e[n], t.parentNode.removeChild(t)
}
function y(e, t, n) {
var r;
if (r = A(n ? U.call(n, P(e), !1) : q.call(P(e), !1)), t) {
for (var o = e.firstChild; o; o = o.nextSibling)r.appendChild(y(o, !0, n));
if (e instanceof F.HTMLTemplateElement)for (var i = r.content, o = e.content.firstChild; o; o = o.nextSibling)i.appendChild(y(o, !0, n))
}
return r
}
function E(e, t) {
if (!t || _(e) !== _(t))return !1;
for (var n = t; n; n = n.parentNode)if (n === e)return !0;
return !1
}
function S(e) {
N(e instanceof V), M.call(this, e), this.parentNode_ = void 0, this.firstChild_ = void 0, this.lastChild_ = void 0, this.nextSibling_ = void 0, this.previousSibling_ = void 0, this.treeScope_ = void 0
}
var M = e.wrappers.EventTarget, T = e.wrappers.NodeList, O = e.TreeScope, N = e.assert, j = e.defineWrapGetter, L = e.enqueueMutation, _ = e.getTreeScope, D = e.isWrapper, C = e.mixin, H = e.registerTransientObservers, x = e.registerWrapper, R = e.setTreeScope, P = e.unsafeUnwrap, W = e.unwrap, I = e.unwrapIfNeeded, A = e.wrap, k = e.wrapIfNeeded, F = e.wrappers, B = !1, U = document.importNode, q = window.Node.prototype.cloneNode, V = window.Node, G = window.DocumentFragment, z = (V.prototype.appendChild, V.prototype.compareDocumentPosition), X = V.prototype.isEqualNode, K = V.prototype.insertBefore, Y = V.prototype.removeChild, $ = V.prototype.replaceChild, Z = /Trident|Edge/.test(navigator.userAgent), J = Z ? function (e, t) {
try {
Y.call(e, t)
} catch (n) {
if (!(e instanceof G))throw n
}
} : function (e, t) {
Y.call(e, t)
};
S.prototype = Object.create(M.prototype), C(S.prototype, {
appendChild: function (e) {
return this.insertBefore(e, null)
}, insertBefore: function (e, n) {
t(e);
var r;
n ? D(n) ? r = W(n) : (r = n, n = A(r)) : (n = null, r = null), n && N(n.parentNode === this);
var o, s = n ? n.previousSibling : this.lastChild, c = !this.invalidateShadowRenderer() && !v(e);
if (o = c ? a(e) : i(e, this, s, n), c)f(this, e), m(this), K.call(P(this), W(e), r); else {
s || (this.firstChild_ = o[0]), n || (this.lastChild_ = o[o.length - 1], void 0 === this.firstChild_ && (this.firstChild_ = this.firstChild));
var u = r ? r.parentNode : P(this);
u ? K.call(u, w(this, o), r) : h(this, o)
}
return L(this, "childList", {addedNodes: o, nextSibling: n, previousSibling: s}), l(o, this), e
}, removeChild: function (e) {
if (t(e), e.parentNode !== this) {
for (var r = !1, o = (this.childNodes, this.firstChild); o; o = o.nextSibling)if (o === e) {
r = !0;
break
}
if (!r)throw new Error("NotFoundError")
}
var i = W(e), a = e.nextSibling, s = e.previousSibling;
if (this.invalidateShadowRenderer()) {
var c = this.firstChild, u = this.lastChild, l = i.parentNode;
l && J(l, i), c === e && (this.firstChild_ = a), u === e && (this.lastChild_ = s), s && (s.nextSibling_ = a), a && (a.previousSibling_ = s), e.previousSibling_ = e.nextSibling_ = e.parentNode_ = void 0
} else m(this), J(P(this), i);
return B || L(this, "childList", {removedNodes: n(e), nextSibling: a, previousSibling: s}), H(this, e), e
}, replaceChild: function (e, r) {
t(e);
var o;
if (D(r) ? o = W(r) : (o = r, r = A(o)), r.parentNode !== this)throw new Error("NotFoundError");
var s, c = r.nextSibling, u = r.previousSibling, d = !this.invalidateShadowRenderer() && !v(e);
return d ? s = a(e) : (c === e && (c = e.nextSibling), s = i(e, this, u, c)), d ? (f(this, e), m(this), $.call(P(this), W(e), o)) : (this.firstChild === r && (this.firstChild_ = s[0]), this.lastChild === r && (this.lastChild_ = s[s.length - 1]), r.previousSibling_ = r.nextSibling_ = r.parentNode_ = void 0, o.parentNode && $.call(o.parentNode, w(this, s), o)), L(this, "childList", {
addedNodes: s,
removedNodes: n(r),
nextSibling: c,
previousSibling: u
}), p(r), l(s, this), r
}, nodeIsInserted_: function () {
for (var e = this.firstChild; e; e = e.nextSibling)e.nodeIsInserted_()
}, hasChildNodes: function () {
return null !== this.firstChild
}, get parentNode() {
return void 0 !== this.parentNode_ ? this.parentNode_ : A(P(this).parentNode)
}, get firstChild() {
return void 0 !== this.firstChild_ ? this.firstChild_ : A(P(this).firstChild)
}, get lastChild() {
return void 0 !== this.lastChild_ ? this.lastChild_ : A(P(this).lastChild)
}, get nextSibling() {
return void 0 !== this.nextSibling_ ? this.nextSibling_ : A(P(this).nextSibling)
}, get previousSibling() {
return void 0 !== this.previousSibling_ ? this.previousSibling_ : A(P(this).previousSibling)
}, get parentElement() {
for (var e = this.parentNode; e && e.nodeType !== S.ELEMENT_NODE;)e = e.parentNode;
return e
}, get textContent() {
for (var e = "", t = this.firstChild; t; t = t.nextSibling)t.nodeType != S.COMMENT_NODE && (e += t.textContent);
return e
}, set textContent(e) {
null == e && (e = "");
var t = c(this.childNodes);
if (this.invalidateShadowRenderer()) {
if (g(this), "" !== e) {
var n = P(this).ownerDocument.createTextNode(e);
this.appendChild(n)
}
} else m(this), P(this).textContent = e;
var r = c(this.childNodes);
L(this, "childList", {addedNodes: r, removedNodes: t}), d(t), l(r, this)
}, get childNodes() {
for (var e = new T, t = 0, n = this.firstChild; n; n = n.nextSibling)e[t++] = n;
return e.length = t, e
}, cloneNode: function (e) {
return y(this, e)
}, contains: function (e) {
return E(this, k(e))
}, compareDocumentPosition: function (e) {
return z.call(P(this), I(e))
}, isEqualNode: function (e) {
return X.call(P(this), I(e))
}, normalize: function () {
for (var e, t, n = c(this.childNodes), r = [], o = "", i = 0; i < n.length; i++)t = n[i], t.nodeType === S.TEXT_NODE ? e || t.data.length ? e ? (o += t.data, r.push(t)) : e = t : this.removeChild(t) : (e && r.length && (e.data += o, b(r)), r = [], o = "", e = null, t.childNodes.length && t.normalize());
e && r.length && (e.data += o, b(r))
}
}), j(S, "ownerDocument"), x(V, S, document.createDocumentFragment()), delete S.prototype.querySelector, delete S.prototype.querySelectorAll, S.prototype = C(Object.create(M.prototype), S.prototype), e.cloneNode = y, e.nodeWasAdded = u, e.nodeWasRemoved = p, e.nodesWereAdded = l, e.nodesWereRemoved = d, e.originalInsertBefore = K, e.originalRemoveChild = Y, e.snapshotNodeList = c, e.wrappers.Node = S
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(t, n, r, o) {
for (var i = null, a = null, s = 0, c = t.length; c > s; s++)i = b(t[s]), !o && (a = g(i).root) && a instanceof e.wrappers.ShadowRoot || (r[n++] = i);
return n
}
function n(e) {
return String(e).replace(/\/deep\/|::shadow|>>>/g, " ")
}
function r(e) {
return String(e).replace(/:host\(([^\s]+)\)/g, "$1").replace(/([^\s]):host/g, "$1").replace(":host", "*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g, " ")
}
function o(e, t) {
for (var n, r = e.firstElementChild; r;) {
if (r.matches(t))return r;
if (n = o(r, t))return n;
r = r.nextElementSibling
}
return null
}
function i(e, t) {
return e.matches(t)
}
function a(e, t, n) {
var r = e.localName;
return r === t || r === n && e.namespaceURI === D
}
function s() {
return !0
}
function c(e, t, n) {
return e.localName === n
}
function u(e, t) {
return e.namespaceURI === t
}
function l(e, t, n) {
return e.namespaceURI === t && e.localName === n
}
function p(e, t, n, r, o, i) {
for (var a = e.firstElementChild; a;)r(a, o, i) && (n[t++] = a), t = p(a, t, n, r, o, i), a = a.nextElementSibling;
return t
}
function d(n, r, o, i, a) {
var s, c = v(this), u = g(this).root;
if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, null);
if (c instanceof L)s = M.call(c, i); else {
if (!(c instanceof _))return p(this, r, o, n, i, null);
s = S.call(c, i)
}
return t(s, r, o, a)
}
function f(n, r, o, i, a) {
var s, c = v(this), u = g(this).root;
if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, a);
if (c instanceof L)s = O.call(c, i, a); else {
if (!(c instanceof _))return p(this, r, o, n, i, a);
s = T.call(c, i, a)
}
return t(s, r, o, !1)
}
function h(n, r, o, i, a) {
var s, c = v(this), u = g(this).root;
if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, a);
if (c instanceof L)s = j.call(c, i, a); else {
if (!(c instanceof _))return p(this, r, o, n, i, a);
s = N.call(c, i, a)
}
return t(s, r, o, !1)
}
var w = e.wrappers.HTMLCollection, m = e.wrappers.NodeList, g = e.getTreeScope, v = e.unsafeUnwrap, b = e.wrap, y = document.querySelector, E = document.documentElement.querySelector, S = document.querySelectorAll, M = document.documentElement.querySelectorAll, T = document.getElementsByTagName, O = document.documentElement.getElementsByTagName, N = document.getElementsByTagNameNS, j = document.documentElement.getElementsByTagNameNS, L = window.Element, _ = window.HTMLDocument || window.Document, D = "http://www.w3.org/1999/xhtml", C = {
querySelector: function (t) {
var r = n(t), i = r !== t;
t = r;
var a, s = v(this), c = g(this).root;
if (c instanceof e.wrappers.ShadowRoot)return o(this, t);
if (s instanceof L)a = b(E.call(s, t)); else {
if (!(s instanceof _))return o(this, t);
a = b(y.call(s, t))
}
return a && !i && (c = g(a).root) && c instanceof e.wrappers.ShadowRoot ? o(this, t) : a
}, querySelectorAll: function (e) {
var t = n(e), r = t !== e;
e = t;
var o = new m;
return o.length = d.call(this, i, 0, o, e, r), o
}
}, H = {
matches: function (t) {
return t = r(t), e.originalMatches.call(v(this), t)
}
}, x = {
getElementsByTagName: function (e) {
var t = new w, n = "*" === e ? s : a;
return t.length = f.call(this, n, 0, t, e, e.toLowerCase()),
t
}, getElementsByClassName: function (e) {
return this.querySelectorAll("." + e)
}, getElementsByTagNameNS: function (e, t) {
var n = new w, r = null;
return r = "*" === e ? "*" === t ? s : c : "*" === t ? u : l, n.length = h.call(this, r, 0, n, e || null, t), n
}
};
e.GetElementsByInterface = x, e.SelectorsInterface = C, e.MatchesInterface = H
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
for (; e && e.nodeType !== Node.ELEMENT_NODE;)e = e.nextSibling;
return e
}
function n(e) {
for (; e && e.nodeType !== Node.ELEMENT_NODE;)e = e.previousSibling;
return e
}
var r = e.wrappers.NodeList, o = {
get firstElementChild() {
return t(this.firstChild)
}, get lastElementChild() {
return n(this.lastChild)
}, get childElementCount() {
for (var e = 0, t = this.firstElementChild; t; t = t.nextElementSibling)e++;
return e
}, get children() {
for (var e = new r, t = 0, n = this.firstElementChild; n; n = n.nextElementSibling)e[t++] = n;
return e.length = t, e
}, remove: function () {
var e = this.parentNode;
e && e.removeChild(this)
}
}, i = {
get nextElementSibling() {
return t(this.nextSibling)
}, get previousElementSibling() {
return n(this.previousSibling)
}
}, a = {
getElementById: function (e) {
return /[ \t\n\r\f]/.test(e) ? null : this.querySelector('[id="' + e + '"]')
}
};
e.ChildNodeInterface = i, e.NonElementParentNodeInterface = a, e.ParentNodeInterface = o
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
r.call(this, e)
}
var n = e.ChildNodeInterface, r = e.wrappers.Node, o = e.enqueueMutation, i = e.mixin, a = e.registerWrapper, s = e.unsafeUnwrap, c = window.CharacterData;
t.prototype = Object.create(r.prototype), i(t.prototype, {
get nodeValue() {
return this.data
}, set nodeValue(e) {
this.data = e
}, get textContent() {
return this.data
}, set textContent(e) {
this.data = e
}, get data() {
return s(this).data
}, set data(e) {
var t = s(this).data;
o(this, "characterData", {oldValue: t}), s(this).data = e
}
}), i(t.prototype, n), a(c, t, document.createTextNode("")), e.wrappers.CharacterData = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
return e >>> 0
}
function n(e) {
r.call(this, e)
}
var r = e.wrappers.CharacterData, o = (e.enqueueMutation, e.mixin), i = e.registerWrapper, a = window.Text;
n.prototype = Object.create(r.prototype), o(n.prototype, {
splitText: function (e) {
e = t(e);
var n = this.data;
if (e > n.length)throw new Error("IndexSizeError");
var r = n.slice(0, e), o = n.slice(e);
this.data = r;
var i = this.ownerDocument.createTextNode(o);
return this.parentNode && this.parentNode.insertBefore(i, this.nextSibling), i
}
}), i(a, n, document.createTextNode("")), e.wrappers.Text = n
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
return i(e).getAttribute("class")
}
function n(e, t) {
a(e, "attributes", {name: "class", namespace: null, oldValue: t})
}
function r(t) {
e.invalidateRendererBasedOnAttribute(t, "class")
}
function o(e, o, i) {
var a = e.ownerElement_;
if (null == a)return o.apply(e, i);
var s = t(a), c = o.apply(e, i);
return t(a) !== s && (n(a, s), r(a)), c
}
if (!window.DOMTokenList)return void console.warn("Missing DOMTokenList prototype, please include a compatible classList polyfill such as http://goo.gl/uTcepH.");
var i = e.unsafeUnwrap, a = e.enqueueMutation, s = DOMTokenList.prototype.add;
DOMTokenList.prototype.add = function () {
o(this, s, arguments)
};
var c = DOMTokenList.prototype.remove;
DOMTokenList.prototype.remove = function () {
o(this, c, arguments)
};
var u = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function () {
return o(this, u, arguments)
}
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(t, n) {
var r = t.parentNode;
if (r && r.shadowRoot) {
var o = e.getRendererForHost(r);
o.dependsOnAttribute(n) && o.invalidate()
}
}
function n(e, t, n) {
l(e, "attributes", {name: t, namespace: null, oldValue: n})
}
function r(e) {
a.call(this, e)
}
var o = e.ChildNodeInterface, i = e.GetElementsByInterface, a = e.wrappers.Node, s = e.ParentNodeInterface, c = e.SelectorsInterface, u = e.MatchesInterface, l = (e.addWrapNodeListMethod, e.enqueueMutation), p = e.mixin, d = (e.oneOf, e.registerWrapper), f = e.unsafeUnwrap, h = e.wrappers, w = window.Element, m = ["matches", "mozMatchesSelector", "msMatchesSelector", "webkitMatchesSelector"].filter(function (e) {
return w.prototype[e]
}), g = m[0], v = w.prototype[g], b = new WeakMap;
r.prototype = Object.create(a.prototype), p(r.prototype, {
createShadowRoot: function () {
var t = new h.ShadowRoot(this);
f(this).polymerShadowRoot_ = t;
var n = e.getRendererForHost(this);
return n.invalidate(), t
}, get shadowRoot() {
return f(this).polymerShadowRoot_ || null
}, setAttribute: function (e, r) {
var o = f(this).getAttribute(e);
f(this).setAttribute(e, r), n(this, e, o), t(this, e)
}, removeAttribute: function (e) {
var r = f(this).getAttribute(e);
f(this).removeAttribute(e), n(this, e, r), t(this, e)
}, get classList() {
var e = b.get(this);
if (!e) {
if (e = f(this).classList, !e)return;
e.ownerElement_ = this, b.set(this, e)
}
return e
}, get className() {
return f(this).className
}, set className(e) {
this.setAttribute("class", e)
}, get id() {
return f(this).id
}, set id(e) {
this.setAttribute("id", e)
}
}), m.forEach(function (e) {
"matches" !== e && (r.prototype[e] = function (e) {
return this.matches(e)
})
}), w.prototype.webkitCreateShadowRoot && (r.prototype.webkitCreateShadowRoot = r.prototype.createShadowRoot), p(r.prototype, o), p(r.prototype, i), p(r.prototype, s), p(r.prototype, c), p(r.prototype, u), d(w, r, document.createElementNS(null, "x")), e.invalidateRendererBasedOnAttribute = t, e.matchesNames = m, e.originalMatches = v, e.wrappers.Element = r
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
switch (e) {
case"&":
return "&";
case"<":
return "<";
case">":
return ">";
case'"':
return """;
case" ":
return " "
}
}
function n(e) {
return e.replace(j, t)
}
function r(e) {
return e.replace(L, t)
}
function o(e) {
for (var t = {}, n = 0; n < e.length; n++)t[e[n]] = !0;
return t
}
function i(e) {
if (e.namespaceURI !== C)return !0;
var t = e.ownerDocument.doctype;
return t && t.publicId && t.systemId
}
function a(e, t) {
switch (e.nodeType) {
case Node.ELEMENT_NODE:
for (var o, a = e.tagName.toLowerCase(), c = "<" + a, u = e.attributes, l = 0; o = u[l]; l++)c += " " + o.name + '="' + n(o.value) + '"';
return _[a] ? (i(e) && (c += "/"), c + ">") : c + ">" + s(e) + "</" + a + ">";
case Node.TEXT_NODE:
var p = e.data;
return t && D[t.localName] ? p : r(p);
case Node.COMMENT_NODE:
return "<!--" + e.data + "-->";
default:
throw console.error(e), new Error("not implemented")
}
}
function s(e) {
e instanceof N.HTMLTemplateElement && (e = e.content);
for (var t = "", n = e.firstChild; n; n = n.nextSibling)t += a(n, e);
return t
}
function c(e, t, n) {
var r = n || "div";
e.textContent = "";
var o = T(e.ownerDocument.createElement(r));
o.innerHTML = t;
for (var i; i = o.firstChild;)e.appendChild(O(i))
}
function u(e) {
w.call(this, e)
}
function l(e, t) {
var n = T(e.cloneNode(!1));
n.innerHTML = t;
for (var r, o = T(document.createDocumentFragment()); r = n.firstChild;)o.appendChild(r);
return O(o)
}
function p(t) {
return function () {
return e.renderAllPending(), M(this)[t]
}
}
function d(e) {
m(u, e, p(e))
}
function f(t) {
Object.defineProperty(u.prototype, t, {
get: p(t), set: function (n) {
e.renderAllPending(), M(this)[t] = n
}, configurable: !0, enumerable: !0
})
}
function h(t) {
Object.defineProperty(u.prototype, t, {
value: function () {
return e.renderAllPending(), M(this)[t].apply(M(this), arguments)
}, configurable: !0, enumerable: !0
})
}
var w = e.wrappers.Element, m = e.defineGetter, g = e.enqueueMutation, v = e.mixin, b = e.nodesWereAdded, y = e.nodesWereRemoved, E = e.registerWrapper, S = e.snapshotNodeList, M = e.unsafeUnwrap, T = e.unwrap, O = e.wrap, N = e.wrappers, j = /[&\u00A0"]/g, L = /[&\u00A0<>]/g, _ = o(["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]), D = o(["style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript"]), C = "http://www.w3.org/1999/xhtml", H = /MSIE/.test(navigator.userAgent), x = window.HTMLElement, R = window.HTMLTemplateElement;
u.prototype = Object.create(w.prototype), v(u.prototype, {
get innerHTML() {
return s(this)
}, set innerHTML(e) {
if (H && D[this.localName])return void(this.textContent = e);
var t = S(this.childNodes);
this.invalidateShadowRenderer() ? this instanceof N.HTMLTemplateElement ? c(this.content, e) : c(this, e, this.tagName) : !R && this instanceof N.HTMLTemplateElement ? c(this.content, e) : M(this).innerHTML = e;
var n = S(this.childNodes);
g(this, "childList", {addedNodes: n, removedNodes: t}), y(t), b(n, this)
}, get outerHTML() {
return a(this, this.parentNode)
}, set outerHTML(e) {
var t = this.parentNode;
if (t) {
t.invalidateShadowRenderer();
var n = l(t, e);
t.replaceChild(n, this)
}
}, insertAdjacentHTML: function (e, t) {
var n, r;
switch (String(e).toLowerCase()) {
case"beforebegin":
n = this.parentNode, r = this;
break;
case"afterend":
n = this.parentNode, r = this.nextSibling;
break;
case"afterbegin":
n = this, r = this.firstChild;
break;
case"beforeend":
n = this, r = null;
break;
default:
return
}
var o = l(n, t);
n.insertBefore(o, r)
}, get hidden() {
return this.hasAttribute("hidden")
}, set hidden(e) {
e ? this.setAttribute("hidden", "") : this.removeAttribute("hidden")
}
}), ["clientHeight", "clientLeft", "clientTop", "clientWidth", "offsetHeight", "offsetLeft", "offsetTop", "offsetWidth", "scrollHeight", "scrollWidth"].forEach(d), ["scrollLeft", "scrollTop"].forEach(f), ["focus", "getBoundingClientRect", "getClientRects", "scrollIntoView"].forEach(h), E(x, u, document.createElement("b")), e.wrappers.HTMLElement = u, e.getInnerHTML = s, e.setInnerHTML = c
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unsafeUnwrap, a = e.wrap, s = window.HTMLCanvasElement;
t.prototype = Object.create(n.prototype), r(t.prototype, {
getContext: function () {
var e = i(this).getContext.apply(i(this), arguments);
return e && a(e)
}
}), o(s, t, document.createElement("canvas")), e.wrappers.HTMLCanvasElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = window.HTMLContentElement;
t.prototype = Object.create(n.prototype), r(t.prototype, {
constructor: t, get select() {
return this.getAttribute("select")
}, set select(e) {
this.setAttribute("select", e)
}, setAttribute: function (e, t) {
n.prototype.setAttribute.call(this, e, t), "select" === String(e).toLowerCase() && this.invalidateShadowRenderer(!0)
}
}), i && o(i, t), e.wrappers.HTMLContentElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = window.HTMLFormElement;
t.prototype = Object.create(n.prototype), r(t.prototype, {
get elements() {
return i(a(this).elements)
}
}), o(s, t, document.createElement("form")), e.wrappers.HTMLFormElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
r.call(this, e)
}
function n(e, t) {
if (!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");
var o = i(document.createElement("img"));
r.call(this, o), a(o, this), void 0 !== e && (o.width = e), void 0 !== t && (o.height = t)
}
var r = e.wrappers.HTMLElement, o = e.registerWrapper, i = e.unwrap, a = e.rewrap, s = window.HTMLImageElement;
t.prototype = Object.create(r.prototype), o(s, t, document.createElement("img")), n.prototype = t.prototype, e.wrappers.HTMLImageElement = t, e.wrappers.Image = n
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = (e.mixin, e.wrappers.NodeList, e.registerWrapper), o = window.HTMLShadowElement;
t.prototype = Object.create(n.prototype), t.prototype.constructor = t, o && r(o, t), e.wrappers.HTMLShadowElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
if (!e.defaultView)return e;
var t = p.get(e);
if (!t) {
for (t = e.implementation.createHTMLDocument(""); t.lastChild;)t.removeChild(t.lastChild);
p.set(e, t)
}
return t
}
function n(e) {
for (var n, r = t(e.ownerDocument), o = c(r.createDocumentFragment()); n = e.firstChild;)o.appendChild(n);
return o
}
function r(e) {
if (o.call(this, e), !d) {
var t = n(e);
l.set(this, u(t))
}
}
var o = e.wrappers.HTMLElement, i = e.mixin, a = e.registerWrapper, s = e.unsafeUnwrap, c = e.unwrap, u = e.wrap, l = new WeakMap, p = new WeakMap, d = window.HTMLTemplateElement;
r.prototype = Object.create(o.prototype), i(r.prototype, {
constructor: r, get content() {
return d ? u(s(this).content) : l.get(this)
}
}), d && a(d, r), e.wrappers.HTMLTemplateElement = r
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.registerWrapper, o = window.HTMLMediaElement;
o && (t.prototype = Object.create(n.prototype), r(o, t, document.createElement("audio")), e.wrappers.HTMLMediaElement = t)
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
r.call(this, e)
}
function n(e) {
if (!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");
var t = i(document.createElement("audio"));
r.call(this, t), a(t, this), t.setAttribute("preload", "auto"), void 0 !== e && t.setAttribute("src", e)
}
var r = e.wrappers.HTMLMediaElement, o = e.registerWrapper, i = e.unwrap, a = e.rewrap, s = window.HTMLAudioElement;
s && (t.prototype = Object.create(r.prototype), o(s, t, document.createElement("audio")), n.prototype = t.prototype, e.wrappers.HTMLAudioElement = t, e.wrappers.Audio = n)
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
return e.replace(/\s+/g, " ").trim()
}
function n(e) {
o.call(this, e)
}
function r(e, t, n, i) {
if (!(this instanceof r))throw new TypeError("DOM object constructor cannot be called as a function.");
var a = c(document.createElement("option"));
o.call(this, a), s(a, this), void 0 !== e && (a.text = e), void 0 !== t && a.setAttribute("value", t), n === !0 && a.setAttribute("selected", ""), a.selected = i === !0
}
var o = e.wrappers.HTMLElement, i = e.mixin, a = e.registerWrapper, s = e.rewrap, c = e.unwrap, u = e.wrap, l = window.HTMLOptionElement;
n.prototype = Object.create(o.prototype), i(n.prototype, {
get text() {
return t(this.textContent)
}, set text(e) {
this.textContent = t(String(e))
}, get form() {
return u(c(this).form)
}
}), a(l, n, document.createElement("option")), r.prototype = n.prototype, e.wrappers.HTMLOptionElement = n, e.wrappers.Option = r
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unwrap, a = e.wrap, s = window.HTMLSelectElement;
t.prototype = Object.create(n.prototype), r(t.prototype, {
add: function (e, t) {
"object" == typeof t && (t = i(t)), i(this).add(i(e), t)
}, remove: function (e) {
return void 0 === e ? void n.prototype.remove.call(this) : ("object" == typeof e && (e = i(e)), void i(this).remove(e))
}, get form() {
return a(i(this).form)
}
}), o(s, t, document.createElement("select")), e.wrappers.HTMLSelectElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unwrap, a = e.wrap, s = e.wrapHTMLCollection, c = window.HTMLTableElement;
t.prototype = Object.create(n.prototype), r(t.prototype, {
get caption() {
return a(i(this).caption)
}, createCaption: function () {
return a(i(this).createCaption())
}, get tHead() {
return a(i(this).tHead)
}, createTHead: function () {
return a(i(this).createTHead())
}, createTFoot: function () {
return a(i(this).createTFoot())
}, get tFoot() {
return a(i(this).tFoot)
}, get tBodies() {
return s(i(this).tBodies)
}, createTBody: function () {
return a(i(this).createTBody())
}, get rows() {
return s(i(this).rows)
}, insertRow: function (e) {
return a(i(this).insertRow(e))
}
}), o(c, t, document.createElement("table")), e.wrappers.HTMLTableElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = e.wrap, c = window.HTMLTableSectionElement;
t.prototype = Object.create(n.prototype), r(t.prototype, {
constructor: t, get rows() {
return i(a(this).rows)
}, insertRow: function (e) {
return s(a(this).insertRow(e))
}
}), o(c, t, document.createElement("thead")), e.wrappers.HTMLTableSectionElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = e.wrap, c = window.HTMLTableRowElement;
t.prototype = Object.create(n.prototype), r(t.prototype, {
get cells() {
return i(a(this).cells)
}, insertCell: function (e) {
return s(a(this).insertCell(e))
}
}), o(c, t, document.createElement("tr")), e.wrappers.HTMLTableRowElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
switch (e.localName) {
case"content":
return new n(e);
case"shadow":
return new o(e);
case"template":
return new i(e)
}
r.call(this, e)
}
var n = e.wrappers.HTMLContentElement, r = e.wrappers.HTMLElement, o = e.wrappers.HTMLShadowElement, i = e.wrappers.HTMLTemplateElement, a = (e.mixin, e.registerWrapper), s = window.HTMLUnknownElement;
t.prototype = Object.create(r.prototype), a(s, t), e.wrappers.HTMLUnknownElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.Element, r = e.wrappers.HTMLElement, o = e.registerWrapper, i = (e.defineWrapGetter, e.unsafeUnwrap), a = e.wrap, s = e.mixin, c = "http://www.w3.org/2000/svg", u = window.SVGElement, l = document.createElementNS(c, "title");
if (!("classList" in l)) {
var p = Object.getOwnPropertyDescriptor(n.prototype, "classList");
Object.defineProperty(r.prototype, "classList", p), delete n.prototype.classList
}
t.prototype = Object.create(n.prototype), s(t.prototype, {
get ownerSVGElement() {
return a(i(this).ownerSVGElement)
}
}), o(u, t, document.createElementNS(c, "title")), e.wrappers.SVGElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
d.call(this, e)
}
var n = e.mixin, r = e.registerWrapper, o = e.unwrap, i = e.wrap, a = window.SVGUseElement, s = "http://www.w3.org/2000/svg", c = i(document.createElementNS(s, "g")), u = document.createElementNS(s, "use"), l = c.constructor, p = Object.getPrototypeOf(l.prototype), d = p.constructor;
t.prototype = Object.create(p), "instanceRoot" in u && n(t.prototype, {
get instanceRoot() {
return i(o(this).instanceRoot)
}, get animatedInstanceRoot() {
return i(o(this).animatedInstanceRoot)
}
}), r(a, t, u), e.wrappers.SVGUseElement = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.EventTarget, r = e.mixin, o = e.registerWrapper, i = e.unsafeUnwrap, a = e.wrap, s = window.SVGElementInstance;
s && (t.prototype = Object.create(n.prototype), r(t.prototype, {
get correspondingElement() {
return a(i(this).correspondingElement)
}, get correspondingUseElement() {
return a(i(this).correspondingUseElement)
}, get parentNode() {
return a(i(this).parentNode)
}, get childNodes() {
throw new Error("Not implemented")
}, get firstChild() {
return a(i(this).firstChild)
}, get lastChild() {
return a(i(this).lastChild)
}, get previousSibling() {
return a(i(this).previousSibling)
}, get nextSibling() {
return a(i(this).nextSibling)
}
}), o(s, t), e.wrappers.SVGElementInstance = t)
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
o(e, this)
}
var n = e.mixin, r = e.registerWrapper, o = e.setWrapper, i = e.unsafeUnwrap, a = e.unwrap, s = e.unwrapIfNeeded, c = e.wrap, u = window.CanvasRenderingContext2D;
n(t.prototype, {
get canvas() {
return c(i(this).canvas)
}, drawImage: function () {
arguments[0] = s(arguments[0]), i(this).drawImage.apply(i(this), arguments)
}, createPattern: function () {
return arguments[0] = a(arguments[0]), i(this).createPattern.apply(i(this), arguments)
}
}), r(u, t, document.createElement("canvas").getContext("2d")), e.wrappers.CanvasRenderingContext2D = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
i(e, this)
}
var n = e.addForwardingProperties, r = e.mixin, o = e.registerWrapper, i = e.setWrapper, a = e.unsafeUnwrap, s = e.unwrapIfNeeded, c = e.wrap, u = window.WebGLRenderingContext;
if (u) {
r(t.prototype, {
get canvas() {
return c(a(this).canvas)
}, texImage2D: function () {
arguments[5] = s(arguments[5]), a(this).texImage2D.apply(a(this), arguments)
}, texSubImage2D: function () {
arguments[6] = s(arguments[6]), a(this).texSubImage2D.apply(a(this), arguments)
}
});
var l = Object.getPrototypeOf(u.prototype);
l !== Object.prototype && n(l, t.prototype);
var p = /WebKit/.test(navigator.userAgent) ? {drawingBufferHeight: null, drawingBufferWidth: null} : {};
o(u, t, p), e.wrappers.WebGLRenderingContext = t
}
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.Node, r = e.GetElementsByInterface, o = e.NonElementParentNodeInterface, i = e.ParentNodeInterface, a = e.SelectorsInterface, s = e.mixin, c = e.registerObject, u = e.registerWrapper, l = window.DocumentFragment;
t.prototype = Object.create(n.prototype), s(t.prototype, i), s(t.prototype, a), s(t.prototype, r), s(t.prototype, o), u(l, t, document.createDocumentFragment()), e.wrappers.DocumentFragment = t;
var p = c(document.createComment(""));
e.wrappers.Comment = p
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
var t = p(l(e).ownerDocument.createDocumentFragment());
n.call(this, t), c(t, this);
var o = e.shadowRoot;
h.set(this, o), this.treeScope_ = new r(this, a(o || e)), f.set(this, e)
}
var n = e.wrappers.DocumentFragment, r = e.TreeScope, o = e.elementFromPoint, i = e.getInnerHTML, a = e.getTreeScope, s = e.mixin, c = e.rewrap, u = e.setInnerHTML, l = e.unsafeUnwrap, p = e.unwrap, d = e.wrap, f = new WeakMap, h = new WeakMap;
t.prototype = Object.create(n.prototype), s(t.prototype, {
constructor: t, get innerHTML() {
return i(this)
}, set innerHTML(e) {
u(this, e), this.invalidateShadowRenderer()
}, get olderShadowRoot() {
return h.get(this) || null
}, get host() {
return f.get(this) || null
}, invalidateShadowRenderer: function () {
return f.get(this).invalidateShadowRenderer()
}, elementFromPoint: function (e, t) {
return o(this, this.ownerDocument, e, t)
}, getSelection: function () {
return document.getSelection()
}, get activeElement() {
var e = p(this).ownerDocument.activeElement;
if (!e || !e.nodeType)return null;
for (var t = d(e); !this.contains(t);) {
for (; t.parentNode;)t = t.parentNode;
if (!t.host)return null;
t = t.host
}
return t
}
}), e.wrappers.ShadowRoot = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
var t = p(e).root;
return t instanceof f ? t.host : null
}
function n(t, n) {
if (t.shadowRoot) {
n = Math.min(t.childNodes.length - 1, n);
var r = t.childNodes[n];
if (r) {
var o = e.getDestinationInsertionPoints(r);
if (o.length > 0) {
var i = o[0].parentNode;
i.nodeType == Node.ELEMENT_NODE && (t = i)
}
}
}
return t
}
function r(e) {
return e = l(e), t(e) || e
}
function o(e) {
a(e, this)
}
var i = e.registerWrapper, a = e.setWrapper, s = e.unsafeUnwrap, c = e.unwrap, u = e.unwrapIfNeeded, l = e.wrap, p = e.getTreeScope, d = window.Range, f = e.wrappers.ShadowRoot;
o.prototype = {
get startContainer() {
return r(s(this).startContainer)
}, get endContainer() {
return r(s(this).endContainer)
}, get commonAncestorContainer() {
return r(s(this).commonAncestorContainer)
}, setStart: function (e, t) {
e = n(e, t), s(this).setStart(u(e), t)
}, setEnd: function (e, t) {
e = n(e, t), s(this).setEnd(u(e), t)
}, setStartBefore: function (e) {
s(this).setStartBefore(u(e))
}, setStartAfter: function (e) {
s(this).setStartAfter(u(e))
}, setEndBefore: function (e) {
s(this).setEndBefore(u(e))
}, setEndAfter: function (e) {
s(this).setEndAfter(u(e))
}, selectNode: function (e) {
s(this).selectNode(u(e))
}, selectNodeContents: function (e) {
s(this).selectNodeContents(u(e))
}, compareBoundaryPoints: function (e, t) {
return s(this).compareBoundaryPoints(e, c(t))
}, extractContents: function () {
return l(s(this).extractContents())
}, cloneContents: function () {
return l(s(this).cloneContents())
}, insertNode: function (e) {
s(this).insertNode(u(e))
}, surroundContents: function (e) {
s(this).surroundContents(u(e))
}, cloneRange: function () {
return l(s(this).cloneRange())
}, isPointInRange: function (e, t) {
return s(this).isPointInRange(u(e), t)
}, comparePoint: function (e, t) {
return s(this).comparePoint(u(e), t)
}, intersectsNode: function (e) {
return s(this).intersectsNode(u(e))
}, toString: function () {
return s(this).toString()
}
}, d.prototype.createContextualFragment && (o.prototype.createContextualFragment = function (e) {
return l(s(this).createContextualFragment(e))
}), i(window.Range, o, document.createRange()), e.wrappers.Range = o
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
e.previousSibling_ = e.previousSibling, e.nextSibling_ = e.nextSibling, e.parentNode_ = e.parentNode
}
function n(n, o, i) {
var a = x(n), s = x(o), c = i ? x(i) : null;
if (r(o), t(o), i)n.firstChild === i && (n.firstChild_ = i), i.previousSibling_ = i.previousSibling; else {
n.lastChild_ = n.lastChild, n.lastChild === n.firstChild && (n.firstChild_ = n.firstChild);
var u = R(a.lastChild);
u && (u.nextSibling_ = u.nextSibling)
}
e.originalInsertBefore.call(a, s, c)
}
function r(n) {
var r = x(n), o = r.parentNode;
if (o) {
var i = R(o);
t(n), n.previousSibling && (n.previousSibling.nextSibling_ = n), n.nextSibling && (n.nextSibling.previousSibling_ = n), i.lastChild === n && (i.lastChild_ = n), i.firstChild === n && (i.firstChild_ = n), e.originalRemoveChild.call(o, r)
}
}
function o(e) {
W.set(e, [])
}
function i(e) {
var t = W.get(e);
return t || W.set(e, t = []), t
}
function a(e) {
for (var t = [], n = 0, r = e.firstChild; r; r = r.nextSibling)t[n++] = r;
return t
}
function s() {
for (var e = 0; e < F.length; e++) {
var t = F[e], n = t.parentRenderer;
n && n.dirty || t.render()
}
F = []
}
function c() {
T = null, s()
}
function u(e) {
var t = A.get(e);
return t || (t = new f(e), A.set(e, t)), t
}
function l(e) {
var t = D(e).root;
return t instanceof _ ? t : null
}
function p(e) {
return u(e.host)
}
function d(e) {
this.skip = !1, this.node = e, this.childNodes = []
}
function f(e) {
this.host = e, this.dirty = !1, this.invalidateAttributes(), this.associateNode(e)
}
function h(e) {
for (var t = [], n = e.firstChild; n; n = n.nextSibling)E(n) ? t.push.apply(t, i(n)) : t.push(n);
return t
}
function w(e) {
if (e instanceof j)return e;
if (e instanceof N)return null;
for (var t = e.firstChild; t; t = t.nextSibling) {
var n = w(t);
if (n)return n
}
return null
}
function m(e, t) {
i(t).push(e);
var n = I.get(e);
n ? n.push(t) : I.set(e, [t])
}
function g(e) {
return I.get(e)
}
function v(e) {
I.set(e, void 0)
}
function b(e, t) {
var n = t.getAttribute("select");
if (!n)return !0;
if (n = n.trim(), !n)return !0;
if (!(e instanceof O))return !1;
if (!U.test(n))return !1;
try {
return e.matches(n)
} catch (r) {
return !1
}
}
function y(e, t) {
var n = g(t);
return n && n[n.length - 1] === e
}
function E(e) {
return e instanceof N || e instanceof j
}
function S(e) {
return e.shadowRoot
}
function M(e) {
for (var t = [], n = e.shadowRoot; n; n = n.olderShadowRoot)t.push(n);
return t
}
var T, O = e.wrappers.Element, N = e.wrappers.HTMLContentElement, j = e.wrappers.HTMLShadowElement, L = e.wrappers.Node, _ = e.wrappers.ShadowRoot, D = (e.assert, e.getTreeScope), C = (e.mixin, e.oneOf), H = e.unsafeUnwrap, x = e.unwrap, R = e.wrap, P = e.ArraySplice, W = new WeakMap, I = new WeakMap, A = new WeakMap, k = C(window, ["requestAnimationFrame", "mozRequestAnimationFrame", "webkitRequestAnimationFrame", "setTimeout"]), F = [], B = new P;
B.equals = function (e, t) {
return x(e.node) === t
}, d.prototype = {
append: function (e) {
var t = new d(e);
return this.childNodes.push(t), t
}, sync: function (e) {
if (!this.skip) {
for (var t = this.node, o = this.childNodes, i = a(x(t)), s = e || new WeakMap, c = B.calculateSplices(o, i), u = 0, l = 0, p = 0, d = 0; d < c.length; d++) {
for (var f = c[d]; p < f.index; p++)l++, o[u++].sync(s);
for (var h = f.removed.length, w = 0; h > w; w++) {
var m = R(i[l++]);
s.get(m) || r(m)
}
for (var g = f.addedCount, v = i[l] && R(i[l]), w = 0; g > w; w++) {
var b = o[u++], y = b.node;
n(t, y, v), s.set(y, !0), b.sync(s)
}
p += g
}
for (var d = p; d < o.length; d++)o[d].sync(s)
}
}
}, f.prototype = {
render: function (e) {
if (this.dirty) {
this.invalidateAttributes();
var t = this.host;
this.distribution(t);
var n = e || new d(t);
this.buildRenderTree(n, t);
var r = !e;
r && n.sync(), this.dirty = !1
}
}, get parentRenderer() {
return D(this.host).renderer
}, invalidate: function () {
if (!this.dirty) {
this.dirty = !0;
var e = this.parentRenderer;
if (e && e.invalidate(), F.push(this), T)return;
T = window[k](c, 0)
}
}, distribution: function (e) {
this.resetAllSubtrees(e), this.distributionResolution(e)
}, resetAll: function (e) {
E(e) ? o(e) : v(e), this.resetAllSubtrees(e)
}, resetAllSubtrees: function (e) {
for (var t = e.firstChild; t; t = t.nextSibling)this.resetAll(t);
e.shadowRoot && this.resetAll(e.shadowRoot), e.olderShadowRoot && this.resetAll(e.olderShadowRoot)
}, distributionResolution: function (e) {
if (S(e)) {
for (var t = e, n = h(t), r = M(t), o = 0; o < r.length; o++)this.poolDistribution(r[o], n);
for (var o = r.length - 1; o >= 0; o--) {
var i = r[o], a = w(i);
if (a) {
var s = i.olderShadowRoot;
s && (n = h(s));
for (var c = 0; c < n.length; c++)m(n[c], a)
}
this.distributionResolution(i)
}
}
for (var u = e.firstChild; u; u = u.nextSibling)this.distributionResolution(u)
}, poolDistribution: function (e, t) {
if (!(e instanceof j))if (e instanceof N) {
var n = e;
this.updateDependentAttributes(n.getAttribute("select"));
for (var r = !1, o = 0; o < t.length; o++) {
var e = t[o];
e && b(e, n) && (m(e, n), t[o] = void 0, r = !0)
}
if (!r)for (var i = n.firstChild; i; i = i.nextSibling)m(i, n)
} else for (var i = e.firstChild; i; i = i.nextSibling)this.poolDistribution(i, t)
}, buildRenderTree: function (e, t) {
for (var n = this.compose(t), r = 0; r < n.length; r++) {
var o = n[r], i = e.append(o);
this.buildRenderTree(i, o)
}
if (S(t)) {
var a = u(t);
a.dirty = !1
}
}, compose: function (e) {
for (var t = [], n = e.shadowRoot || e, r = n.firstChild; r; r = r.nextSibling)if (E(r)) {
this.associateNode(n);
for (var o = i(r), a = 0; a < o.length; a++) {
var s = o[a];
y(r, s) && t.push(s)
}
} else t.push(r);
return t
}, invalidateAttributes: function () {
this.attributes = Object.create(null)
}, updateDependentAttributes: function (e) {
if (e) {
var t = this.attributes;
/\.\w+/.test(e) && (t["class"] = !0), /#\w+/.test(e) && (t.id = !0), e.replace(/\[\s*([^\s=\|~\]]+)/g, function (e, n) {
t[n] = !0
})
}
}, dependsOnAttribute: function (e) {
return this.attributes[e]
}, associateNode: function (e) {
H(e).polymerShadowRenderer_ = this
}
};
var U = /^(:not\()?[*.#[a-zA-Z_|]/;
L.prototype.invalidateShadowRenderer = function (e) {
var t = H(this).polymerShadowRenderer_;
return t ? (t.invalidate(), !0) : !1
}, N.prototype.getDistributedNodes = j.prototype.getDistributedNodes = function () {
return s(), i(this)
}, O.prototype.getDestinationInsertionPoints = function () {
return s(), g(this) || []
}, N.prototype.nodeIsInserted_ = j.prototype.nodeIsInserted_ = function () {
this.invalidateShadowRenderer();
var e, t = l(this);
t && (e = p(t)), H(this).polymerShadowRenderer_ = e, e && e.invalidate()
}, e.getRendererForHost = u, e.getShadowTrees = M, e.renderAllPending = s, e.getDestinationInsertionPoints = g, e.visual = {
insertBefore: n,
remove: r
}
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(t) {
if (window[t]) {
r(!e.wrappers[t]);
var c = function (e) {
n.call(this, e)
};
c.prototype = Object.create(n.prototype), o(c.prototype, {
get form() {
return s(a(this).form)
}
}), i(window[t], c, document.createElement(t.slice(4, -7))), e.wrappers[t] = c
}
}
var n = e.wrappers.HTMLElement, r = e.assert, o = e.mixin, i = e.registerWrapper, a = e.unwrap, s = e.wrap, c = ["HTMLButtonElement", "HTMLFieldSetElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLObjectElement", "HTMLOutputElement", "HTMLTextAreaElement"];
c.forEach(t)
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
r(e, this)
}
var n = e.registerWrapper, r = e.setWrapper, o = e.unsafeUnwrap, i = e.unwrap, a = e.unwrapIfNeeded, s = e.wrap, c = window.Selection;
t.prototype = {
get anchorNode() {
return s(o(this).anchorNode)
}, get focusNode() {
return s(o(this).focusNode)
}, addRange: function (e) {
o(this).addRange(a(e))
}, collapse: function (e, t) {
o(this).collapse(a(e), t)
}, containsNode: function (e, t) {
return o(this).containsNode(a(e), t)
}, getRangeAt: function (e) {
return s(o(this).getRangeAt(e))
}, removeRange: function (e) {
o(this).removeRange(i(e))
}, selectAllChildren: function (e) {
o(this).selectAllChildren(e instanceof ShadowRoot ? o(e.host) : a(e))
}, toString: function () {
return o(this).toString()
}
}, c.prototype.extend && (t.prototype.extend = function (e, t) {
o(this).extend(a(e), t)
}), n(window.Selection, t, window.getSelection()), e.wrappers.Selection = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
r(e, this)
}
var n = e.registerWrapper, r = e.setWrapper, o = e.unsafeUnwrap, i = e.unwrapIfNeeded, a = e.wrap, s = window.TreeWalker;
t.prototype = {
get root() {
return a(o(this).root)
}, get currentNode() {
return a(o(this).currentNode)
}, set currentNode(e) {
o(this).currentNode = i(e)
}, get filter() {
return o(this).filter
}, parentNode: function () {
return a(o(this).parentNode())
}, firstChild: function () {
return a(o(this).firstChild())
}, lastChild: function () {
return a(o(this).lastChild())
}, previousSibling: function () {
return a(o(this).previousSibling())
}, previousNode: function () {
return a(o(this).previousNode())
}, nextNode: function () {
return a(o(this).nextNode())
}
}, n(s, t), e.wrappers.TreeWalker = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
l.call(this, e), this.treeScope_ = new m(this, null)
}
function n(e) {
var n = document[e];
t.prototype[e] = function () {
return D(n.apply(L(this), arguments))
}
}
function r(e, t) {
x.call(L(t), _(e)), o(e, t)
}
function o(e, t) {
e.shadowRoot && t.adoptNode(e.shadowRoot), e instanceof w && i(e, t);
for (var n = e.firstChild; n; n = n.nextSibling)o(n, t)
}
function i(e, t) {
var n = e.olderShadowRoot;
n && t.adoptNode(n)
}
function a(e) {
j(e, this)
}
function s(e, t) {
var n = document.implementation[t];
e.prototype[t] = function () {
return D(n.apply(L(this), arguments))
}
}
function c(e, t) {
var n = document.implementation[t];
e.prototype[t] = function () {
return n.apply(L(this), arguments)
}
}
var u = e.GetElementsByInterface, l = e.wrappers.Node, p = e.ParentNodeInterface, d = e.NonElementParentNodeInterface, f = e.wrappers.Selection, h = e.SelectorsInterface, w = e.wrappers.ShadowRoot, m = e.TreeScope, g = e.cloneNode, v = e.defineGetter, b = e.defineWrapGetter, y = e.elementFromPoint, E = e.forwardMethodsToWrapper, S = e.matchesNames, M = e.mixin, T = e.registerWrapper, O = e.renderAllPending, N = e.rewrap, j = e.setWrapper, L = e.unsafeUnwrap, _ = e.unwrap, D = e.wrap, C = e.wrapEventTargetMethods, H = (e.wrapNodeList,
new WeakMap);
t.prototype = Object.create(l.prototype), b(t, "documentElement"), b(t, "body"), b(t, "head"), v(t, "activeElement", function () {
var e = _(this).activeElement;
if (!e || !e.nodeType)return null;
for (var t = D(e); !this.contains(t);) {
for (; t.parentNode;)t = t.parentNode;
if (!t.host)return null;
t = t.host
}
return t
}), ["createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode"].forEach(n);
var x = document.adoptNode, R = document.getSelection;
M(t.prototype, {
adoptNode: function (e) {
return e.parentNode && e.parentNode.removeChild(e), r(e, this), e
}, elementFromPoint: function (e, t) {
return y(this, this, e, t)
}, importNode: function (e, t) {
return g(e, t, L(this))
}, getSelection: function () {
return O(), new f(R.call(_(this)))
}, getElementsByName: function (e) {
return h.querySelectorAll.call(this, "[name=" + JSON.stringify(String(e)) + "]")
}
});
var P = document.createTreeWalker, W = e.wrappers.TreeWalker;
if (t.prototype.createTreeWalker = function (e, t, n, r) {
var o = null;
return n && (n.acceptNode && "function" == typeof n.acceptNode ? o = {
acceptNode: function (e) {
return n.acceptNode(D(e))
}
} : "function" == typeof n && (o = function (e) {
return n(D(e))
})), new W(P.call(_(this), _(e), t, o, r))
}, document.registerElement) {
var I = document.registerElement;
t.prototype.registerElement = function (t, n) {
function r(e) {
return e ? void j(e, this) : i ? document.createElement(i, t) : document.createElement(t)
}
var o, i;
if (void 0 !== n && (o = n.prototype, i = n["extends"]), o || (o = Object.create(HTMLElement.prototype)), e.nativePrototypeTable.get(o))throw new Error("NotSupportedError");
for (var a, s = Object.getPrototypeOf(o), c = []; s && !(a = e.nativePrototypeTable.get(s));)c.push(s), s = Object.getPrototypeOf(s);
if (!a)throw new Error("NotSupportedError");
for (var u = Object.create(a), l = c.length - 1; l >= 0; l--)u = Object.create(u);
["createdCallback", "attachedCallback", "detachedCallback", "attributeChangedCallback"].forEach(function (e) {
var t = o[e];
t && (u[e] = function () {
D(this) instanceof r || N(this), t.apply(D(this), arguments)
})
});
var p = {prototype: u};
i && (p["extends"] = i), r.prototype = o, r.prototype.constructor = r, e.constructorTable.set(u, r), e.nativePrototypeTable.set(o, u);
I.call(_(this), t, p);
return r
}, E([window.HTMLDocument || window.Document], ["registerElement"])
}
E([window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement, window.HTMLHtmlElement], ["appendChild", "compareDocumentPosition", "contains", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "insertBefore", "querySelector", "querySelectorAll", "removeChild", "replaceChild"]), E([window.HTMLBodyElement, window.HTMLHeadElement, window.HTMLHtmlElement], S), E([window.HTMLDocument || window.Document], ["adoptNode", "importNode", "contains", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "createTreeWalker", "elementFromPoint", "getElementById", "getElementsByName", "getSelection"]), M(t.prototype, u), M(t.prototype, p), M(t.prototype, h), M(t.prototype, d), M(t.prototype, {
get implementation() {
var e = H.get(this);
return e ? e : (e = new a(_(this).implementation), H.set(this, e), e)
}, get defaultView() {
return D(_(this).defaultView)
}
}), T(window.Document, t, document.implementation.createHTMLDocument("")), window.HTMLDocument && T(window.HTMLDocument, t), C([window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement]);
var A = document.implementation.createDocument;
a.prototype.createDocument = function () {
return arguments[2] = _(arguments[2]), D(A.apply(L(this), arguments))
}, s(a, "createDocumentType"), s(a, "createHTMLDocument"), c(a, "hasFeature"), T(window.DOMImplementation, a), E([window.DOMImplementation], ["createDocument", "createDocumentType", "createHTMLDocument", "hasFeature"]), e.adoptNodeNoRemove = r, e.wrappers.DOMImplementation = a, e.wrappers.Document = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
n.call(this, e)
}
var n = e.wrappers.EventTarget, r = e.wrappers.Selection, o = e.mixin, i = e.registerWrapper, a = e.renderAllPending, s = e.unwrap, c = e.unwrapIfNeeded, u = e.wrap, l = window.Window, p = window.getComputedStyle, d = window.getDefaultComputedStyle, f = window.getSelection;
t.prototype = Object.create(n.prototype), l.prototype.getComputedStyle = function (e, t) {
return u(this || window).getComputedStyle(c(e), t)
}, d && (l.prototype.getDefaultComputedStyle = function (e, t) {
return u(this || window).getDefaultComputedStyle(c(e), t)
}), l.prototype.getSelection = function () {
return u(this || window).getSelection()
}, delete window.getComputedStyle, delete window.getDefaultComputedStyle, delete window.getSelection, ["addEventListener", "removeEventListener", "dispatchEvent"].forEach(function (e) {
l.prototype[e] = function () {
var t = u(this || window);
return t[e].apply(t, arguments)
}, delete window[e]
}), o(t.prototype, {
getComputedStyle: function (e, t) {
return a(), p.call(s(this), c(e), t)
}, getSelection: function () {
return a(), new r(f.call(s(this)))
}, get document() {
return u(s(this).document)
}
}), d && (t.prototype.getDefaultComputedStyle = function (e, t) {
return a(), d.call(s(this), c(e), t)
}), i(l, t, window), e.wrappers.Window = t
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
var t = e.unwrap, n = window.DataTransfer || window.Clipboard, r = n.prototype.setDragImage;
r && (n.prototype.setDragImage = function (e, n, o) {
r.call(this, t(e), n, o)
})
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
var t;
t = e instanceof i ? e : new i(e && o(e)), r(t, this)
}
var n = e.registerWrapper, r = e.setWrapper, o = e.unwrap, i = window.FormData;
i && (n(i, t, new i), e.wrappers.FormData = t)
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
var t = e.unwrapIfNeeded, n = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (e) {
return n.call(this, t(e))
}
}(window.ShadowDOMPolyfill), function (e) {
"use strict";
function t(e) {
var t = n[e], r = window[t];
if (r) {
var o = document.createElement(e), i = o.constructor;
window[t] = i
}
}
var n = (e.isWrapperFor, {
a: "HTMLAnchorElement",
area: "HTMLAreaElement",
audio: "HTMLAudioElement",
base: "HTMLBaseElement",
body: "HTMLBodyElement",
br: "HTMLBRElement",
button: "HTMLButtonElement",
canvas: "HTMLCanvasElement",
caption: "HTMLTableCaptionElement",
col: "HTMLTableColElement",
content: "HTMLContentElement",
data: "HTMLDataElement",
datalist: "HTMLDataListElement",
del: "HTMLModElement",
dir: "HTMLDirectoryElement",
div: "HTMLDivElement",
dl: "HTMLDListElement",
embed: "HTMLEmbedElement",
fieldset: "HTMLFieldSetElement",
font: "HTMLFontElement",
form: "HTMLFormElement",
frame: "HTMLFrameElement",
frameset: "HTMLFrameSetElement",
h1: "HTMLHeadingElement",
head: "HTMLHeadElement",
hr: "HTMLHRElement",
html: "HTMLHtmlElement",
iframe: "HTMLIFrameElement",
img: "HTMLImageElement",
input: "HTMLInputElement",
keygen: "HTMLKeygenElement",
label: "HTMLLabelElement",
legend: "HTMLLegendElement",
li: "HTMLLIElement",
link: "HTMLLinkElement",
map: "HTMLMapElement",
marquee: "HTMLMarqueeElement",
menu: "HTMLMenuElement",
menuitem: "HTMLMenuItemElement",
meta: "HTMLMetaElement",
meter: "HTMLMeterElement",
object: "HTMLObjectElement",
ol: "HTMLOListElement",
optgroup: "HTMLOptGroupElement",
option: "HTMLOptionElement",
output: "HTMLOutputElement",
p: "HTMLParagraphElement",
param: "HTMLParamElement",
pre: "HTMLPreElement",
progress: "HTMLProgressElement",
q: "HTMLQuoteElement",
script: "HTMLScriptElement",
select: "HTMLSelectElement",
shadow: "HTMLShadowElement",
source: "HTMLSourceElement",
span: "HTMLSpanElement",
style: "HTMLStyleElement",
table: "HTMLTableElement",
tbody: "HTMLTableSectionElement",
template: "HTMLTemplateElement",
textarea: "HTMLTextAreaElement",
thead: "HTMLTableSectionElement",
time: "HTMLTimeElement",
title: "HTMLTitleElement",
tr: "HTMLTableRowElement",
track: "HTMLTrackElement",
ul: "HTMLUListElement",
video: "HTMLVideoElement"
});
Object.keys(n).forEach(t), Object.getOwnPropertyNames(e.wrappers).forEach(function (t) {
window[t] = e.wrappers[t]
})
}(window.ShadowDOMPolyfill); | kittuov/go-django | admin/webapp/static/app/bower_components/webcomponentsjs/ShadowDOM.min.js | JavaScript | mit | 104,656 |
#PROJECT
from outcome import Outcome
from odds import Odds
class Bin:
def __init__(
self,
*outcomes
):
self.outcomes = set([outcome for outcome in outcomes])
def add_outcome(
self,
outcome
):
self.outcomes.add(outcome)
def __str__(self):
return ', '.join([str(outcome) for outcome in self.outcomes])
class BinBuilder:
def __init__(
self,
wheel
):
self.wheel = wheel
def build_bins(self):
self.straight_bets()
self.split_bets()
self.street_bets()
self.corner_bets()
self.five_bet()
self.line_bets()
self.dozen_bets()
self.column_bets()
self.even_money_bets()
def straight_bets(self):
outcomes = [
Outcome(str(i), Odds.STRAIGHT_BET)
for i in range(37)
] + [Outcome('00', Odds.STRAIGHT_BET)]
for i, outcome in enumerate(outcomes):
self.wheel.add_outcome(i, outcome)
def split_bets(self):
for row in range(12):
for direction in [1, 2]:
n = 3 * row + direction
bins = [n, n + 1]
outcome = Outcome(
'split {}'.format('-'.join([str(i) for i in bins])),
Odds.SPLIT_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
for n in range(1, 34):
bins = [n, n + 3]
outcome = Outcome(
'split {}'.format('-'.join([str(i) for i in bins])),
Odds.SPLIT_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def street_bets(self):
for row in range(12):
n = 3 * row + 1
bins = [n, n + 1, n + 2]
outcome = Outcome(
'street {}-{}'.format(bins[0], bins[-1]),
Odds.STREET_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def corner_bets(self):
for col in [1, 2]:
for row in range(11):
n = 3 * row + col
bins = [n + i for i in [0, 1, 3, 4]]
outcome = Outcome(
'corner {}'.format('-'.join([str(i) for i in bins])),
Odds.CORNER_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def five_bet(self):
outcome = Outcome(
'five bet 00-0-1-2-3',
Odds.FIVE_BET
)
for bin in [0, 1, 2, 3, 37]:
self.wheel.add_outcome(bin, outcome)
def line_bets(self):
for row in range(11):
n = 3 * row + 1
bins = [n + i for i in range(6)]
outcome = Outcome(
'line {}-{}'.format(bins[0], bins[-1]),
Odds.LINE_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def dozen_bets(self):
#https://pypi.python.org/pypi/inflect/0.2.4
dozen_map = {
1: '1st',
2: '2nd',
3: '3rd'
}
for d in range(3):
outcome = Outcome(
'{} 12'.format(dozen_map[d + 1]),
Odds.DOZEN_BET
)
for m in range(12):
self.wheel.add_outcome(12 * d + m + 1, outcome)
def column_bets(self):
for c in range(3):
outcome = Outcome(
'column {}'.format(c + 1),
Odds.COLUMN_BET
)
for r in range(12):
self.wheel.add_outcome(3 * r + c + 1, outcome)
def even_money_bets(self):
for bin in range(1, 37):
if 1 <= bin < 19:
name = '1 to 18' #low
else:
name = '19 to 36' #high
self.wheel.add_outcome(
bin,
Outcome(name, Odds.EVEN_MONEY_BET)
)
if bin % 2:
name = 'odd'
else:
name = 'even'
self.wheel.add_outcome(
bin,
Outcome(name, Odds.EVEN_MONEY_BET)
)
if bin in (
[1, 3, 5, 7, 9] +
[12, 14, 16, 18] +
[19, 21, 23, 25, 27] +
[30, 32, 34, 36]
):
name = 'red'
else:
name = 'black'
self.wheel.add_outcome(
bin,
Outcome(name, Odds.EVEN_MONEY_BET)
)
| ddenhartog/itmaybeahack-roulette | bin.py | Python | mit | 4,662 |
/*
* Copyright (c) 2013 Algolia
* http://www.algolia.com/
*
* 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.
*/
var ALGOLIA_VERSION = '2.8.5';
/*
* Copyright (c) 2013 Algolia
* http://www.algolia.com/
*
* 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.
*/
/*
* Algolia Search library initialization
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
* @param methodOrOptions the hash of parameters for initialization. It can contains:
* - method (optional) specify if the protocol used is http or https (http by default to make the first search query faster).
* You need to use https is you are doing something else than just search queries.
* - hosts (optional) the list of hosts that you have received for the service
* - dsn (optional) set to true if your account has the Distributed Search Option
* - dsnHost (optional) override the automatic computation of dsn hostname
*/
var AlgoliaSearch = function(applicationID, apiKey, methodOrOptions, resolveDNS, hosts) {
var self = this;
this.applicationID = applicationID;
this.apiKey = apiKey;
this.dsn = true;
this.dsnHost = null;
this.hosts = [];
this.currentHostIndex = 0;
this.requestTimeoutInMs = 2000;
this.extraHeaders = [];
this.jsonp = null;
var method;
var tld = 'net';
if (typeof methodOrOptions === 'string') { // Old initialization
method = methodOrOptions;
} else {
// Take all option from the hash
var options = methodOrOptions || {};
if (!this._isUndefined(options.method)) {
method = options.method;
}
if (!this._isUndefined(options.tld)) {
tld = options.tld;
}
if (!this._isUndefined(options.dsn)) {
this.dsn = options.dsn;
}
if (!this._isUndefined(options.hosts)) {
hosts = options.hosts;
}
if (!this._isUndefined(options.dsnHost)) {
this.dsnHost = options.dsnHost;
}
if (!this._isUndefined(options.requestTimeoutInMs)) {
this.requestTimeoutInMs = +options.requestTimeoutInMs;
}
if (!this._isUndefined(options.jsonp)) {
this.jsonp = options.jsonp;
}
}
// If hosts is undefined, initialize it with applicationID
if (this._isUndefined(hosts)) {
hosts = [
this.applicationID + '-1.algolia.' + tld,
this.applicationID + '-2.algolia.' + tld,
this.applicationID + '-3.algolia.' + tld
];
}
// detect is we use http or https
this.host_protocol = 'http://';
if (this._isUndefined(method) || method === null) {
this.host_protocol = ('https:' == document.location.protocol ? 'https' : 'http') + '://';
} else if (method === 'https' || method === 'HTTPS') {
this.host_protocol = 'https://';
}
// Add hosts in random order
for (var i = 0; i < hosts.length; ++i) {
if (Math.random() > 0.5) {
this.hosts.reverse();
}
this.hosts.push(this.host_protocol + hosts[i]);
}
if (Math.random() > 0.5) {
this.hosts.reverse();
}
// then add Distributed Search Network host if there is one
if (this.dsn || this.dsnHost != null) {
if (this.dsnHost) {
this.hosts.unshift(this.host_protocol + this.dsnHost);
} else {
this.hosts.unshift(this.host_protocol + this.applicationID + '-dsn.algolia.' + tld);
}
}
};
function AlgoliaExplainResults(hit, titleAttribute, otherAttributes) {
function _getHitExplanationForOneAttr_recurse(obj, foundWords) {
var res = [];
if (typeof obj === 'object' && 'matchedWords' in obj && 'value' in obj) {
var match = false;
for (var j = 0; j < obj.matchedWords.length; ++j) {
var word = obj.matchedWords[j];
if (!(word in foundWords)) {
foundWords[word] = 1;
match = true;
}
}
if (match) {
res.push(obj.value);
}
} else if (Object.prototype.toString.call(obj) === '[object Array]') {
for (var i = 0; i < obj.length; ++i) {
var array = _getHitExplanationForOneAttr_recurse(obj[i], foundWords);
res = res.concat(array);
}
} else if (typeof obj === 'object') {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)){
res = res.concat(_getHitExplanationForOneAttr_recurse(obj[prop], foundWords));
}
}
}
return res;
}
function _getHitExplanationForOneAttr(hit, foundWords, attr) {
var base = hit._highlightResult || hit;
if (attr.indexOf('.') === -1) {
if (attr in base) {
return _getHitExplanationForOneAttr_recurse(base[attr], foundWords);
}
return [];
}
var array = attr.split('.');
var obj = base;
for (var i = 0; i < array.length; ++i) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
var res = [];
for (var j = 0; j < obj.length; ++j) {
res = res.concat(_getHitExplanationForOneAttr(obj[j], foundWords, array.slice(i).join('.')));
}
return res;
}
if (array[i] in obj) {
obj = obj[array[i]];
} else {
return [];
}
}
return _getHitExplanationForOneAttr_recurse(obj, foundWords);
}
var res = {};
var foundWords = {};
var title = _getHitExplanationForOneAttr(hit, foundWords, titleAttribute);
res.title = (title.length > 0) ? title[0] : '';
res.subtitles = [];
if (typeof otherAttributes !== 'undefined') {
for (var i = 0; i < otherAttributes.length; ++i) {
var attr = _getHitExplanationForOneAttr(hit, foundWords, otherAttributes[i]);
for (var j = 0; j < attr.length; ++j) {
res.subtitles.push({ attr: otherAttributes[i], value: attr[j] });
}
}
}
return res;
}
window.AlgoliaSearch = AlgoliaSearch;
AlgoliaSearch.prototype = {
/*
* Delete an index
*
* @param indexName the name of index to delete
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
deleteIndex: function(indexName, callback) {
this._jsonRequest({ method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexName),
callback: callback });
},
/**
* Move an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
moveIndex: function(srcIndexName, dstIndexName, callback) {
var postObj = {operation: 'move', destination: dstIndexName};
this._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
callback: callback });
},
/**
* Copy an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
copyIndex: function(srcIndexName, dstIndexName, callback) {
var postObj = {operation: 'copy', destination: dstIndexName};
this._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
callback: callback });
},
/**
* Return last log entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
getLogs: function(callback, offset, length) {
if (this._isUndefined(offset)) {
offset = 0;
}
if (this._isUndefined(length)) {
length = 10;
}
this._jsonRequest({ method: 'GET',
url: '/1/logs?offset=' + offset + '&length=' + length,
callback: callback });
},
/*
* List all existing indexes (paginated)
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with index list or error description if success is false.
* @param page The page to retrieve, starting at 0.
*/
listIndexes: function(callback, page) {
var params = page ? '?page=' + page : '';
this._jsonRequest({ method: 'GET',
url: '/1/indexes' + params,
callback: callback });
},
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
initIndex: function(indexName) {
return new this.Index(this, indexName);
},
/*
* List all existing user keys with their associated ACLs
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
listUserKeys: function(callback) {
this._jsonRequest({ method: 'GET',
url: '/1/keys',
callback: callback });
},
/*
* Get ACL of a user key
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
getUserKeyACL: function(key, callback) {
this._jsonRequest({ method: 'GET',
url: '/1/keys/' + key,
callback: callback });
},
/*
* Delete an existing user key
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
deleteUserKey: function(key, callback) {
this._jsonRequest({ method: 'DELETE',
url: '/1/keys/' + key,
callback: callback });
},
/*
* Add an existing user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
addUserKey: function(acls, callback) {
var aclsObject = {};
aclsObject.acl = acls;
this._jsonRequest({ method: 'POST',
url: '/1/keys',
body: aclsObject,
callback: callback });
},
/*
* Add an existing user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour.
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call.
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
addUserKeyWithValidity: function(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, callback) {
var indexObj = this;
var aclsObject = {};
aclsObject.acl = acls;
aclsObject.validity = validity;
aclsObject.maxQueriesPerIPPerHour = maxQueriesPerIPPerHour;
aclsObject.maxHitsPerQuery = maxHitsPerQuery;
this._jsonRequest({ method: 'POST',
url: '/1/indexes/' + indexObj.indexName + '/keys',
body: aclsObject,
callback: callback });
},
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
setSecurityTags: function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.tagFilters = tags;
},
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
setUserToken: function(userToken) {
this.userToken = userToken;
},
/*
* Initialize a new batch of search queries
*/
startQueriesBatch: function() {
this.batch = [];
},
/*
* Add a search query in the batch
*
* @param query the full text query
* @param args (optional) if set, contains an object with query parameters:
* - attributes: an array of object attribute names to retrieve
* (if not set all attributes are retrieve)
* - attributesToHighlight: an array of object attribute names to highlight
* (if not set indexed attributes are highlighted)
* - minWordSizefor1Typo: the minimum number of characters to accept one typo.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters to accept two typos.
* Defaults to 7.
* - getRankingInfo: if set, the result hits will contain ranking information in
* _rankingInfo attribute
* - page: (pagination parameter) page to retrieve (zero base). Defaults to 0.
* - hitsPerPage: (pagination parameter) number of hits per page. Defaults to 10.
*/
addQueryInBatch: function(indexName, query, args) {
var params = 'query=' + encodeURIComponent(query);
if (!this._isUndefined(args) && args !== null) {
params = this._getSearchParams(args, params);
}
this.batch.push({ indexName: indexName, params: params });
},
/*
* Clear all queries in cache
*/
clearCache: function() {
this.cache = {};
},
/*
* Launch the batch of queries using XMLHttpRequest.
* (Optimized for browser using a POST query to minimize number of OPTIONS queries)
*
* @param callback the function that will receive results
* @param delay (optional) if set, wait for this delay (in ms) and only send the batch if there was no other in the meantime.
*/
sendQueriesBatch: function(callback, delay) {
var as = this;
var params = {requests: []};
for (var i = 0; i < as.batch.length; ++i) {
params.requests.push(as.batch[i]);
}
window.clearTimeout(as.onDelayTrigger);
if (!this._isUndefined(delay) && delay !== null && delay > 0) {
var onDelayTrigger = window.setTimeout( function() {
as._sendQueriesBatch(params, callback);
}, delay);
as.onDelayTrigger = onDelayTrigger;
} else {
this._sendQueriesBatch(params, callback);
}
},
/**
* Set the number of milliseconds a request can take before automatically being terminated.
*
* @param {Number} milliseconds
*/
setRequestTimeout: function(milliseconds)
{
if (milliseconds) {
this.requestTimeoutInMs = parseInt(milliseconds, 10);
}
},
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
Index: function(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
},
/**
* Add an extra field to the HTTP request
*
* @param key the header field name
* @param value the header field value
*/
setExtraHeader: function(key, value) {
this.extraHeaders.push({ key: key, value: value});
},
_sendQueriesBatch: function(params, callback) {
if (this.jsonp === null) {
var self = this;
this._jsonRequest({ cache: this.cache,
method: 'POST',
url: '/1/indexes/*/queries',
body: params,
callback: function(success, content) {
if (!success) {
// retry first with JSONP
self.jsonp = true;
self._sendQueriesBatch(params, callback);
} else {
self.jsonp = false;
callback && callback(success, content);
}
}
});
} else if (this.jsonp) {
var jsonpParams = '';
for (var i = 0; i < params.requests.length; ++i) {
var q = '/1/indexes/' + encodeURIComponent(params.requests[i].indexName) + '?' + params.requests[i].params;
jsonpParams += i + '=' + encodeURIComponent(q) + '&';
}
var pObj = {params: jsonpParams};
this._jsonRequest({ cache: this.cache,
method: 'GET',
url: '/1/indexes/*',
body: pObj,
callback: callback });
} else {
this._jsonRequest({ cache: this.cache,
method: 'POST',
url: '/1/indexes/*/queries',
body: params,
callback: callback});
}
},
/*
* Wrapper that try all hosts to maximize the quality of service
*/
_jsonRequest: function(opts) {
var self = this;
var callback = opts.callback;
var cache = null;
var cacheID = opts.url;
if (!this._isUndefined(opts.body)) {
cacheID = opts.url + '_body_' + JSON.stringify(opts.body);
}
if (!this._isUndefined(opts.cache)) {
cache = opts.cache;
if (!this._isUndefined(cache[cacheID])) {
if (!this._isUndefined(callback)) {
setTimeout(function () { callback(true, cache[cacheID]); }, 1);
}
return;
}
}
opts.successiveRetryCount = 0;
var impl = function() {
if (opts.successiveRetryCount >= self.hosts.length) {
if (!self._isUndefined(callback)) {
opts.successiveRetryCount = 0;
callback(false, { message: 'Cannot connect the Algolia\'s Search API. Please send an email to support@algolia.com to report the issue.' });
}
return;
}
opts.callback = function(retry, success, res, body) {
if (!success && !self._isUndefined(body)) {
window.console && console.log('Error: ' + body.message);
}
if (success && !self._isUndefined(opts.cache)) {
cache[cacheID] = body;
}
if (!success && retry) {
self.currentHostIndex = ++self.currentHostIndex % self.hosts.length;
opts.successiveRetryCount += 1;
impl();
} else {
opts.successiveRetryCount = 0;
if (!self._isUndefined(callback)) {
callback(success, body);
}
}
};
opts.hostname = self.hosts[self.currentHostIndex];
self._jsonRequestByHost(opts);
};
impl();
},
_jsonRequestByHost: function(opts) {
var self = this;
var url = opts.hostname + opts.url;
if (this.jsonp) {
this._makeJsonpRequestByHost(url, opts);
} else {
this._makeXmlHttpRequestByHost(url, opts);
}
},
/**
* Make a JSONP request
*
* @param url request url (includes endpoint and path)
* @param opts all request options
*/
_makeJsonpRequestByHost: function(url, opts) {
//////////////////
//////////////////
/////
///// DISABLED FOR SECURITY PURPOSE
/////
//////////////////
//////////////////
opts.callback(true, false, null, { 'message': 'JSONP not allowed.' });
return;
// if (opts.method !== 'GET') {
// opts.callback(true, false, null, { 'message': 'Method ' + opts.method + ' ' + url + ' is not supported by JSONP.' });
// return;
// }
// this.jsonpCounter = this.jsonpCounter || 0;
// this.jsonpCounter += 1;
// var head = document.getElementsByTagName('head')[0];
// var script = document.createElement('script');
// var cb = 'algoliaJSONP_' + this.jsonpCounter;
// var done = false;
// var ontimeout = null;
// window[cb] = function(data) {
// opts.callback(false, true, null, data);
// try { delete window[cb]; } catch (e) { window[cb] = undefined; }
// };
// script.type = 'text/javascript';
// script.src = url + '?callback=' + cb + '&X-Algolia-Application-Id=' + this.applicationID + '&X-Algolia-API-Key=' + this.apiKey;
// if (this.tagFilters) {
// script.src += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters);
// }
// if (this.userToken) {
// script.src += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken);
// }
// for (var i = 0; i < this.extraHeaders.length; ++i) {
// script.src += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value;
// }
// if (opts.body && opts.body.params) {
// script.src += '&' + opts.body.params;
// }
// ontimeout = setTimeout(function() {
// script.onload = script.onreadystatechange = script.onerror = null;
// window[cb] = function(data) {
// try { delete window[cb]; } catch (e) { window[cb] = undefined; }
// };
// opts.callback(true, false, null, { 'message': 'Timeout - Failed to load JSONP script.' });
// head.removeChild(script);
// clearTimeout(ontimeout);
// ontimeout = null;
// }, this.requestTimeoutInMs);
// script.onload = script.onreadystatechange = function() {
// clearTimeout(ontimeout);
// ontimeout = null;
// if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
// done = true;
// if (typeof window[cb + '_loaded'] === 'undefined') {
// opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' });
// try { delete window[cb]; } catch (e) { window[cb] = undefined; }
// } else {
// try { delete window[cb + '_loaded']; } catch (e) { window[cb + '_loaded'] = undefined; }
// }
// script.onload = script.onreadystatechange = null; // Handle memory leak in IE
// head.removeChild(script);
// }
// };
// script.onerror = function() {
// clearTimeout(ontimeout);
// ontimeout = null;
// opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' });
// head.removeChild(script);
// try { delete window[cb]; } catch (e) { window[cb] = undefined; }
// };
// head.appendChild(script);
},
/**
* Make a XmlHttpRequest
*
* @param url request url (includes endpoint and path)
* @param opts all request opts
*/
_makeXmlHttpRequestByHost: function(url, opts) {
var self = this;
var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : {};
var body = null;
var ontimeout = null;
if (!this._isUndefined(opts.body)) {
body = JSON.stringify(opts.body);
}
url += ((url.indexOf('?') == -1) ? '?' : '&') + 'X-Algolia-API-Key=' + this.apiKey;
url += '&X-Algolia-Application-Id=' + this.applicationID;
if (this.userToken) {
url += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken);
}
if (this.tagFilters) {
url += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters);
}
for (var i = 0; i < this.extraHeaders.length; ++i) {
url += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value;
}
if ('withCredentials' in xmlHttp) {
xmlHttp.open(opts.method, url, true);
xmlHttp.timeout = this.requestTimeoutInMs * (opts.successiveRetryCount + 1);
if (body !== null) {
/* This content type is specified to follow CORS 'simple header' directive */
xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
} else if (typeof XDomainRequest !== 'undefined') {
// Handle IE8/IE9
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xmlHttp = new XDomainRequest();
xmlHttp.open(opts.method, url);
} else {
// very old browser, not supported
opts.callback(false, false, null, { 'message': 'CORS not supported' });
return;
}
ontimeout = setTimeout(function() {
xmlHttp.abort();
// Prevent Internet Explorer 9, JScript Error c00c023f
if (xmlHttp.aborted === true) {
stopLoadAnimation();
return;
}
opts.callback(true, false, null, { 'message': 'Timeout - Could not connect to endpoint ' + url } );
clearTimeout(ontimeout);
ontimeout = null;
}, this.requestTimeoutInMs * (opts.successiveRetryCount + 1));
xmlHttp.onload = function(event) {
clearTimeout(ontimeout);
ontimeout = null;
if (!self._isUndefined(event) && event.target !== null) {
var retry = (event.target.status === 0 || event.target.status === 503);
var success = false;
var response = null;
if (typeof XDomainRequest !== 'undefined') {
// Handle CORS requests IE8/IE9
response = event.target.responseText;
success = (response && response.length > 0);
}
else {
response = event.target.response;
success = (event.target.status === 200 || event.target.status === 201);
}
opts.callback(retry, success, event.target, response ? JSON.parse(response) : null);
} else {
opts.callback(false, true, event, JSON.parse(xmlHttp.responseText));
}
};
xmlHttp.ontimeout = function(event) { // stop the network call but rely on ontimeout to call opt.callback
};
xmlHttp.onerror = function(event) {
clearTimeout(ontimeout);
ontimeout = null;
opts.callback(true, false, null, { 'message': 'Could not connect to host', 'error': event } );
};
xmlHttp.send(body);
},
/*
* Transform search param object in query string
*/
_getSearchParams: function(args, params) {
if (this._isUndefined(args) || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args.hasOwnProperty(key)) {
params += (params.length === 0) ? '?' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? JSON.stringify(args[key]) : args[key]);
}
}
return params;
},
_isUndefined: function(obj) {
return obj === void 0;
},
/// internal attributes
applicationID: null,
apiKey: null,
tagFilters: null,
userToken: null,
hosts: [],
cache: {},
extraHeaders: []
};
/*
* Contains all the functions related to one index
* You should use AlgoliaSearch.initIndex(indexName) to retrieve this object
*/
AlgoliaSearch.prototype.Index.prototype = {
/*
* Clear all queries in cache
*/
clearCache: function() {
this.cache = {};
},
/*
* Add an object in this index
*
* @param content contains the javascript object to add inside the index
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that contains 3 elements: createAt, taskId and objectID
* @param objectID (optional) an objectID you want to attribute to this object
* (if the attribute already exist the old object will be overwrite)
*/
addObject: function(content, callback, objectID) {
var indexObj = this;
if (this.as._isUndefined(objectID)) {
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName),
body: content,
callback: callback });
} else {
this.as._jsonRequest({ method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID),
body: content,
callback: callback });
}
},
/*
* Add several objects
*
* @param objects contains an array of objects to add
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that updateAt and taskID
*/
addObjects: function(objects, callback) {
var indexObj = this;
var postObj = {requests:[]};
for (var i = 0; i < objects.length; ++i) {
var request = { action: 'addObject',
body: objects[i] };
postObj.requests.push(request);
}
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
callback: callback });
},
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param callback (optional) the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the object to retrieve or the error message if a failure occured
* @param attributes (optional) if set, contains the array of attribute names to retrieve
*/
getObject: function(objectID, callback, attributes) {
var indexObj = this;
var params = '';
if (!this.as._isUndefined(attributes)) {
params = '?attributes=';
for (var i = 0; i < attributes.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attributes[i];
}
}
if (this.as.jsonp === null) {
this.as._jsonRequest({ method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
callback: callback });
} else {
var pObj = {params: params};
this.as._jsonRequest({ method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID),
callback: callback,
body: pObj});
}
},
/*
* Update partially an object (only update attributes passed in argument)
*
* @param partialObject contains the javascript attributes to override, the
* object must contains an objectID attribute
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
partialUpdateObject: function(partialObject, callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial',
body: partialObject,
callback: callback });
},
/*
* Partially Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that updateAt and taskID
*/
partialUpdateObjects: function(objects, callback) {
var indexObj = this;
var postObj = {requests:[]};
for (var i = 0; i < objects.length; ++i) {
var request = { action: 'partialUpdateObject',
objectID: objects[i].objectID,
body: objects[i] };
postObj.requests.push(request);
}
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
callback: callback });
},
/*
* Override the content of object
*
* @param object contains the javascript object to save, the object must contains an objectID attribute
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that updateAt and taskID
*/
saveObject: function(object, callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID),
body: object,
callback: callback });
},
/*
* Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that updateAt and taskID
*/
saveObjects: function(objects, callback) {
var indexObj = this;
var postObj = {requests:[]};
for (var i = 0; i < objects.length; ++i) {
var request = { action: 'updateObject',
objectID: objects[i].objectID,
body: objects[i] };
postObj.requests.push(request);
}
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
callback: callback });
},
/*
* Delete an object from the index
*
* @param objectID the unique identifier of object to delete
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
deleteObject: function(objectID, callback) {
if (objectID === null || objectID.length === 0) {
callback(false, { message: 'empty objectID'});
return;
}
var indexObj = this;
this.as._jsonRequest({ method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID),
callback: callback });
},
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the full text query
* @param callback the result callback with two arguments:
* success: boolean set to true if the request was successfull. If false, the content contains the error.
* content: the server answer that contains the list of results.
* @param args (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use a string array encoding (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you want to highlight according to the query.
* Attributes are separated by a comma. You can also use a string array encoding (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes. Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use a string array encoding (Example: attributesToSnippet: ["name:10","content:10"]). By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters) and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`. Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use a string array encoding (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use a string array encoding, for example tagFilters: ["tag1",["tag2","tag3"]] means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use a string array encoding (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Attributes are separated with a comma (for example `"category,author"` ).
* You can also use a JSON string array encoding (for example ["category","author"]).
* Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should be considered as optional when found in the query.
* The list of words is comma separated.
* - distinct: If set to 1, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best
* one is kept and others are removed.
* @param delay (optional) if set, wait for this delay (in ms) and only send the query if there was no other in the meantime.
*/
search: function(query, callback, args, delay) {
var indexObj = this;
var params = 'query=' + encodeURIComponent(query);
if (!this.as._isUndefined(args) && args !== null) {
params = this.as._getSearchParams(args, params);
}
window.clearTimeout(indexObj.onDelayTrigger);
if (!this.as._isUndefined(delay) && delay !== null && delay > 0) {
var onDelayTrigger = window.setTimeout( function() {
indexObj._search(params, callback);
}, delay);
indexObj.onDelayTrigger = onDelayTrigger;
} else {
this._search(params, callback);
}
},
/*
* Browse all index content
*
* @param page Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9
* @param hitsPerPage: Pagination parameter used to select the number of hits per page. Defaults to 1000.
*/
browse: function(page, callback, hitsPerPage) {
var indexObj = this;
var params = '?page=' + page;
if (!this.as._isUndefined(hitsPerPage)) {
params += '&hitsPerPage=' + hitsPerPage;
}
this.as._jsonRequest({ method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse' + params,
callback: callback });
},
/*
* Get a Typeahead.js adapter
* @param searchParams contains an object with query parameters (see search for details)
*/
ttAdapter: function(params) {
var self = this;
return function(query, cb) {
self.search(query, function(success, content) {
if (success) {
cb(content.hits);
}
}, params);
};
},
/*
* Wait the publication of a task on the server.
* All server task are asynchronous and you can check with this method that the task is published.
*
* @param taskID the id of the task returned by server
* @param callback the result callback with with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that contains the list of results
*/
waitTask: function(taskID, callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID,
callback: function(success, body) {
if (success) {
if (body.status === 'published') {
callback(true, body);
} else {
setTimeout(function() { indexObj.waitTask(taskID, callback); }, 100);
}
} else {
callback(false, body);
}
}});
},
/*
* This function deletes the index content. Settings and index specific API keys are kept untouched.
*
* @param callback (optional) the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the settings object or the error message if a failure occured
*/
clearIndex: function(callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear',
callback: callback });
},
/*
* Get settings of this index
*
* @param callback (optional) the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the settings object or the error message if a failure occured
*/
getSettings: function(callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings',
callback: callback });
},
/*
* Set settings for this index
*
* @param settigns the settings object that can contains :
* - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3).
* - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7).
* - hitsPerPage: (integer) the number of hits per page (default = 10).
* - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects.
* If set to null, all attributes are retrieved.
* - attributesToHighlight: (array of strings) default list of attributes to highlight.
* If set to null, all indexed attributes are highlighted.
* - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number of words to return (syntax is attributeName:nbWords).
* By default no snippet is computed. If set to null, no snippet is computed.
* - attributesToIndex: (array of strings) the list of fields you want to index.
* If set to null, all textual and numerical attributes of your objects are indexed, but you should update it to get optimal results.
* This parameter has two important uses:
* - Limit the attributes to index: For example if you store a binary image in base64, you want to store it and be able to
* retrieve it but you don't want to search in the base64 string.
* - Control part of the ranking*: (see the ranking parameter for full explanation) Matches in attributes at the beginning of
* the list will be considered more important than matches in attributes further down the list.
* In one attribute, matching text at the beginning of the attribute will be considered more important than text after, you can disable
* this behavior if you add your attribute inside `unordered(AttributeName)`, for example attributesToIndex: ["title", "unordered(text)"].
* - attributesForFaceting: (array of strings) The list of fields you want to use for faceting.
* All strings in the attribute selected for faceting are extracted and added as a facet. If set to null, no attribute is used for faceting.
* - attributeForDistinct: (string) The attribute name used for the Distinct feature. This feature is similar to the SQL "distinct" keyword: when enabled
* in query with the distinct=1 parameter, all hits containing a duplicate value for this attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best one is kept and others are removed.
* - ranking: (array of strings) controls the way results are sorted.
* We have six available criteria:
* - typo: sort according to number of typos,
* - geo: sort according to decreassing distance when performing a geo-location based search,
* - proximity: sort according to the proximity of query words in hits,
* - attribute: sort according to the order of attributes defined by attributesToIndex,
* - exact:
* - if the user query contains one word: sort objects having an attribute that is exactly the query word before others.
* For example if you search for the "V" TV show, you want to find it with the "V" query and avoid to have all popular TV
* show starting by the v letter before it.
* - if the user query contains multiple words: sort according to the number of words that matched exactly (and not as a prefix).
* - custom: sort according to a user defined formula set in **customRanking** attribute.
* The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"]
* - customRanking: (array of strings) lets you specify part of the ranking.
* The syntax of this condition is an array of strings containing attributes prefixed by asc (ascending order) or desc (descending order) operator.
* For example `"customRanking" => ["desc(population)", "asc(name)"]`
* - queryType: Select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - highlightPreTag: (string) Specify the string that is inserted before the highlighted parts in the query result (default to "<em>").
* - highlightPostTag: (string) Specify the string that is inserted after the highlighted parts in the query result (default to "</em>").
* - optionalWords: (array of strings) Specify a list of words that should be considered as optional when found in the query.
* @param callback (optional) the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer or the error message if a failure occured
*/
setSettings: function(settings, callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings',
body: settings,
callback: callback });
},
/*
* List all existing user keys associated to this index
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
listUserKeys: function(callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys',
callback: callback });
},
/*
* Get ACL of a user key associated to this index
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
getUserKeyACL: function(key, callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
callback: callback });
},
/*
* Delete an existing user key associated to this index
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
deleteUserKey: function(key, callback) {
var indexObj = this;
this.as._jsonRequest({ method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
callback: callback });
},
/*
* Add an existing user key associated to this index
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
addUserKey: function(acls, callback) {
var indexObj = this;
var aclsObject = {};
aclsObject.acl = acls;
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys',
body: aclsObject,
callback: callback });
},
/*
* Add an existing user key associated to this index
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour.
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call.
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
addUserKeyWithValidity: function(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, callback) {
var indexObj = this;
var aclsObject = {};
aclsObject.acl = acls;
aclsObject.validity = validity;
aclsObject.maxQueriesPerIPPerHour = maxQueriesPerIPPerHour;
aclsObject.maxHitsPerQuery = maxHitsPerQuery;
this.as._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys',
body: aclsObject,
callback: callback });
},
///
/// Internal methods only after this line
///
_search: function(params, callback) {
var pObj = {params: params};
if (this.as.jsonp === null) {
var self = this;
this.as._jsonRequest({ cache: this.cache,
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: pObj,
callback: function(success, content) {
if (!success) {
// retry first with JSONP
self.as.jsonp = true;
self._search(params, callback);
} else {
self.as.jsonp = false;
callback && callback(success, content);
}
}
});
} else if (this.as.jsonp) {
this.as._jsonRequest({ cache: this.cache,
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: pObj,
callback: callback });
} else {
this.as._jsonRequest({ cache: this.cache,
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: pObj,
callback: callback});
}
},
// internal attributes
as: null,
indexName: null,
cache: {},
typeAheadArgs: null,
typeAheadValueOption: null,
emptyConstructor: function() {}
};
/*
* Copyright (c) 2014 Algolia
* http://www.algolia.com/
*
* 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.
*/
(function($) {
var extend = function(out) {
out = out || {};
for (var i = 1; i < arguments.length; i++) {
if (!arguments[i]) {
continue;
}
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
out[key] = arguments[i][key];
}
}
}
return out;
};
/**
* Algolia Search Helper providing faceting and disjunctive faceting
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {hash} options an associative array defining the hitsPerPage, list of facets and list of disjunctive facets
*/
window.AlgoliaSearchHelper = function(client, index, options) {
/// Default options
var defaults = {
facets: [], // list of facets to compute
disjunctiveFacets: [], // list of disjunctive facets to compute
hitsPerPage: 20 // number of hits per page
};
this.init(client, index, extend({}, defaults, options));
};
AlgoliaSearchHelper.prototype = {
/**
* Initialize a new AlgoliaSearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {hash} options an associative array defining the hitsPerPage, list of facets and list of disjunctive facets
* @return {AlgoliaSearchHelper}
*/
init: function(client, index, options) {
this.client = client;
this.index = index;
this.options = options;
this.page = 0;
this.refinements = {};
this.disjunctiveRefinements = {};
this.extraQueries = [];
},
/**
* Perform a query
* @param {string} q the user query
* @param {function} searchCallback the result callback called with two arguments:
* success: boolean set to true if the request was successfull
* content: the query answer with an extra 'disjunctiveFacets' attribute
*/
search: function(q, searchCallback, searchParams) {
this.q = q;
this.searchCallback = searchCallback;
this.searchParams = searchParams || {};
this.page = this.page || 0;
this.refinements = this.refinements || {};
this.disjunctiveRefinements = this.disjunctiveRefinements || {};
this._search();
},
/**
* Remove all refinements (disjunctive + conjunctive)
*/
clearRefinements: function() {
this.disjunctiveRefinements = {};
this.refinements = {};
},
/**
* Ensure a facet refinement exists
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
addDisjunctiveRefine: function(facet, value) {
this.disjunctiveRefinements = this.disjunctiveRefinements || {};
this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {};
this.disjunctiveRefinements[facet][value] = true;
},
/**
* Ensure a facet refinement does not exist
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
removeDisjunctiveRefine: function(facet, value) {
this.disjunctiveRefinements = this.disjunctiveRefinements || {};
this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {};
try {
delete this.disjunctiveRefinements[facet][value];
} catch (e) {
this.disjunctiveRefinements[facet][value] = undefined; // IE compat
}
},
/**
* Ensure a facet refinement exists
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
addRefine: function(facet, value) {
var refinement = facet + ':' + value;
this.refinements = this.refinements || {};
this.refinements[refinement] = true;
},
/**
* Ensure a facet refinement does not exist
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
removeRefine: function(facet, value) {
var refinement = facet + ':' + value;
this.refinements = this.refinements || {};
this.refinements[refinement] = false;
},
/**
* Toggle refinement state of a facet
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {boolean} true if the facet has been found
*/
toggleRefine: function(facet, value) {
for (var i = 0; i < this.options.facets.length; ++i) {
if (this.options.facets[i] == facet) {
var refinement = facet + ':' + value;
this.refinements[refinement] = !this.refinements[refinement];
this.page = 0;
this._search();
return true;
}
}
this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {};
for (var j = 0; j < this.options.disjunctiveFacets.length; ++j) {
if (this.options.disjunctiveFacets[j] == facet) {
this.disjunctiveRefinements[facet][value] = !this.disjunctiveRefinements[facet][value];
this.page = 0;
this._search();
return true;
}
}
return false;
},
/**
* Check the refinement state of a facet
* @param {string} facet the facet
* @param {string} value the associated value
* @return {boolean} true if refined
*/
isRefined: function(facet, value) {
var refinement = facet + ':' + value;
if (this.refinements[refinement]) {
return true;
}
if (this.disjunctiveRefinements[facet] && this.disjunctiveRefinements[facet][value]) {
return true;
}
return false;
},
/**
* Go to next page
*/
nextPage: function() {
this._gotoPage(this.page + 1);
},
/**
* Go to previous page
*/
previousPage: function() {
if (this.page > 0) {
this._gotoPage(this.page - 1);
}
},
/**
* Goto a page
* @param {integer} page The page number
*/
gotoPage: function(page) {
this._gotoPage(page);
},
/**
* Configure the page but do not trigger a reload
* @param {integer} page The page number
*/
setPage: function(page) {
this.page = page;
},
/**
* Configure the underlying index name
* @param {string} name the index name
*/
setIndex: function(name) {
this.index = name;
},
/**
* Get the underlying configured index name
*/
getIndex: function() {
return this.index;
},
/**
* Clear the extra queries added to the underlying batch of queries
*/
clearExtraQueries: function() {
this.extraQueries = [];
},
/**
* Add an extra query to the underlying batch of queries. Once you add queries
* to the batch, the 2nd parameter of the searchCallback will be an object with a `results`
* attribute listing all search results.
*/
addExtraQuery: function(index, query, params) {
this.extraQueries.push({ index: index, query: query, params: (params || {}) });
},
///////////// PRIVATE
/**
* Goto a page
* @param {integer} page The page number
*/
_gotoPage: function(page) {
this.page = page;
this._search();
},
/**
* Perform the underlying queries
*/
_search: function() {
this.client.startQueriesBatch();
this.client.addQueryInBatch(this.index, this.q, this._getHitsSearchParams());
var disjunctiveFacets = [];
var unusedDisjunctiveFacets = {};
for (var i = 0; i < this.options.disjunctiveFacets.length; ++i) {
var facet = this.options.disjunctiveFacets[i];
if (this._hasDisjunctiveRefinements(facet)) {
disjunctiveFacets.push(facet);
} else {
unusedDisjunctiveFacets[facet] = true;
}
}
for (var i = 0; i < disjunctiveFacets.length; ++i) {
this.client.addQueryInBatch(this.index, this.q, this._getDisjunctiveFacetSearchParams(disjunctiveFacets[i]));
}
for (var i = 0; i < this.extraQueries.length; ++i) {
this.client.addQueryInBatch(this.extraQueries[i].index, this.extraQueries[i].query, this.extraQueries[i].params);
}
var self = this;
this.client.sendQueriesBatch(function(success, content) {
if (!success) {
self.searchCallback(false, content);
return;
}
var aggregatedAnswer = content.results[0];
aggregatedAnswer.disjunctiveFacets = aggregatedAnswer.disjunctiveFacets || {};
aggregatedAnswer.facetStats = aggregatedAnswer.facetStats || {};
for (var facet in unusedDisjunctiveFacets) {
if (aggregatedAnswer.facets[facet] && !aggregatedAnswer.disjunctiveFacets[facet]) {
aggregatedAnswer.disjunctiveFacets[facet] = aggregatedAnswer.facets[facet];
try {
delete aggregatedAnswer.facets[facet];
} catch (e) {
aggregatedAnswer.facets[facet] = undefined; // IE compat
}
}
}
for (var i = 0; i < disjunctiveFacets.length; ++i) {
for (var facet in content.results[i + 1].facets) {
aggregatedAnswer.disjunctiveFacets[facet] = content.results[i + 1].facets[facet];
if (self.disjunctiveRefinements[facet]) {
for (var value in self.disjunctiveRefinements[facet]) {
if (!aggregatedAnswer.disjunctiveFacets[facet][value] && self.disjunctiveRefinements[facet][value]) {
aggregatedAnswer.disjunctiveFacets[facet][value] = 0;
}
}
}
}
for (var stats in content.results[i + 1].facets_stats) {
aggregatedAnswer.facetStats[stats] = content.results[i + 1].facets_stats[stats];
}
}
if (self.extraQueries.length === 0) {
self.searchCallback(true, aggregatedAnswer);
} else {
var c = { results: [ aggregatedAnswer ] };
for (var i = 0; i < self.extraQueries.length; ++i) {
c.results.push(content.results[1 + disjunctiveFacets.length + i]);
}
self.searchCallback(true, c);
}
});
},
/**
* Build search parameters used to fetch hits
* @return {hash}
*/
_getHitsSearchParams: function() {
var facets = [];
for (var i = 0; i < this.options.facets.length; ++i) {
facets.push(this.options.facets[i]);
}
for (var i = 0; i < this.options.disjunctiveFacets.length; ++i) {
var facet = this.options.disjunctiveFacets[i];
if (!this._hasDisjunctiveRefinements(facet)) {
facets.push(facet);
}
}
return extend({}, {
hitsPerPage: this.options.hitsPerPage,
page: this.page,
facets: facets,
facetFilters: this._getFacetFilters()
}, this.searchParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @param {string} facet the associated facet name
* @return {hash}
*/
_getDisjunctiveFacetSearchParams: function(facet) {
return extend({}, this.searchParams, {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
facets: facet,
facetFilters: this._getFacetFilters(facet)
});
},
/**
* Test if there are some disjunctive refinements on the facet
*/
_hasDisjunctiveRefinements: function(facet) {
for (var value in this.disjunctiveRefinements[facet]) {
if (this.disjunctiveRefinements[facet][value]) {
return true;
}
}
return false;
},
/**
* Build facetFilters parameter based on current refinements
* @param {string} facet if set, the current disjunctive facet
* @return {hash}
*/
_getFacetFilters: function(facet) {
var facetFilters = [];
for (var refinement in this.refinements) {
if (this.refinements[refinement]) {
facetFilters.push(refinement);
}
}
for (var disjunctiveRefinement in this.disjunctiveRefinements) {
if (disjunctiveRefinement != facet) {
var refinements = [];
for (var value in this.disjunctiveRefinements[disjunctiveRefinement]) {
if (this.disjunctiveRefinements[disjunctiveRefinement][value]) {
refinements.push(disjunctiveRefinement + ':' + value);
}
}
if (refinements.length > 0) {
facetFilters.push(refinements);
}
}
}
return facetFilters;
}
};
})();
/*
* Copyright (c) 2014 Algolia
* http://www.algolia.com/
*
* 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.
*/
(function($) {
/**
* Algolia Places API
* @param {string} Your application ID
* @param {string} Your API Key
*/
window.AlgoliaPlaces = function(applicationID, apiKey) {
this.init(applicationID, apiKey);
};
AlgoliaPlaces.prototype = {
/**
* @param {string} Your application ID
* @param {string} Your API Key
*/
init: function(applicationID, apiKey) {
this.client = new AlgoliaSearch(applicationID, apiKey, 'http', true, ['places-1.algolia.io', 'places-2.algolia.io', 'places-3.algolia.io']);
this.cache = {};
},
/**
* Perform a query
* @param {string} q the user query
* @param {function} searchCallback the result callback called with two arguments:
* success: boolean set to true if the request was successfull
* content: the query answer with an extra 'disjunctiveFacets' attribute
* @param {hash} the list of search parameters
*/
search: function(q, searchCallback, searchParams) {
var indexObj = this;
var params = 'query=' + encodeURIComponent(q);
if (!this.client._isUndefined(searchParams) && searchParams != null) {
params = this.client._getSearchParams(searchParams, params);
}
var pObj = {params: params, apiKey: this.client.apiKey, appID: this.client.applicationID};
this.client._jsonRequest({ cache: this.cache,
method: 'POST',
url: '/1/places/query',
body: pObj,
callback: searchCallback,
removeCustomHTTPHeaders: true });
}
};
})();
| algolia/github-awesome-autocomplete | code/js/libs/algoliasearch.js | JavaScript | mit | 83,838 |
<?php
//connect to da database
include('functions.php');
include('../secure/database.php');
$conn = pg_connect(HOST." ".DBNAME." ".USERNAME." ".PASSWORD) or die('Could not connect:' . pg_last_error());
HTTPSCheck();
session_start();
//Once the button is pressed...
if(isset($_POST['submit'])){
//clears out special chars
$username = htmlspecialchars($_POST['username']);
//runs the usernameAvailable function, if it returns 0 then create the user
if(usernameAvailable($username) == 0){
//salt and hash the password
mt_rand();
$salt = sha1(mt_rand());
$salt2 = sha1(mt_rand());
$pw = sha1($salt . htmlspecialchars($_POST['password']));
//create a query for both the username and password
$user = "INSERT INTO DA.user_info(username) VALUES ($1) ";
$auth = "INSERT INTO DA.authentication(username, password_hash, salt) VALUES($1, $2, $3)";
//prepare
pg_prepare($conn, "user", $user);
pg_prepare($conn, "auth", $auth);
//execute
pg_execute($conn, "user", array($username));
pg_execute($conn, "auth", array($username, $pw, $salt));
//creates a session
$_SESSION['username'] = $username;
} else {
echo '<script language="javascript">';
echo 'alert("Username taken, try again")';
echo '</script>';
}
}
if(isset($_SESSION['username'])){
header('Location: ./profile.php');
}
//function for checking username availability
function usernameAvailable($username)
{
global $conn;
$username = pg_escape_string(htmlspecialchars($username));
$password = pg_escape_string(htmlspecialchars($password));
$query = "SELECT * FROM DA.user_info where username LIKE $1";
pg_prepare($conn, "check",$query);
$result = pg_execute($conn,"check",array($username));
if(pg_num_rows($result)==0)
return 0;
else
return 1;
}
?>
<!DOCTYPE html>
<head>
<title>Robert Stovall Final</title>
<link rel="stylesheet" type="text/css" href="/~rcsc77/cs2830/final/include/styles.css">
<script src="/~rcsc77/cs2830/final/include/jquery.js"></script>
<script src="/~rcsc77/cs2830/final/include/jquery-ui.js"></script>
<script src="/~rcsc77/cs2830/final/include/ajax.js"></script>
</head>
<body>
<?php include "nav.php"; ?>
<h1>User Registration</h1>
<div class="center">
<form id='registration' action="<?= $_SERVER['PHP_SELF'] ?>" method='post'>
<label for='username' >Username:</label>
<input type='text' name='username' id='username' maxlength="50" required/>
<br>
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" required/>
<br>
<br>
<input type='submit' name='submit' value='Register' />
<br>
</form>
<br>
<form action="index.php"style="width: 200px">
<input type="submit" value="Cancel">
</form>
<br>
</div>
</body>
| robertastic/Dantes-Adventures | main/register.php | PHP | mit | 2,867 |
namespace DraftSimulator.Web.Areas.HelpPage.ModelDescriptions
{
public class CollectionModelDescription : ModelDescription
{
public ModelDescription ElementDescription { get; set; }
}
} | plaberge/DraftSimulator | DraftSimulator.Web/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs | C# | mit | 205 |
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("Print Part Of The ASCII Table")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Print Part Of The ASCII Table")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b2ad7a6f-e217-42de-b7be-6b3ca8f95891")]
// 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")]
| mitaka00/SoftUni | Programing Fundamentals/11-Data Types and Variables-Exercise/Print Part Of The ASCII Table/Properties/AssemblyInfo.cs | C# | mit | 1,434 |
'use strict';
angular.module('rvplusplus').directive('initFocus', function() {
return {
restrict: 'A', // only activate on element attribute
link: function(scope, element, attrs) {
element.focus();
}
};
});
| theikkila/rvplusplus-client | app/scripts/directives.js | JavaScript | mit | 251 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""The Tornado web framework.
核心模块, 参考示例使用代码:
- 重要模块:
- tornado.web
- tornado.ioloop # 根据示例,可知入口在此.参看: ioloop.py
- tornado.httpserver
The Tornado web framework looks a bit like web.py (http://webpy.org/) or
Google's webapp (http://code.google.com/appengine/docs/python/tools/webapp/),
but with additional tools and optimizations to take advantage of the
Tornado non-blocking web server and tools.
Here is the canonical "Hello, world" example app:
import tornado.httpserver
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
See the Tornado walkthrough on GitHub for more details and a good
getting started guide.
"""
import base64
import binascii
import calendar
import Cookie
import cStringIO
import datetime
import email.utils
import escape
import functools
import gzip
import hashlib
import hmac
import httplib
import locale
import logging
import mimetypes
import os.path
import re
import stat
import sys
import template
import time
import types
import urllib
import urlparse
import uuid
"""
# 模块说明: 核心模块
RequestHandler() 需要处理哪些工作:
- 1. HTTP方法支持(GET,POST, HEAD, DELETE, PUT), 预定义各种接口
- 2. 预定义接口: 配对定义[类似 unittest 的 setUp(), tearDown() 方法]
- prepare() # 运行前, 准备工作
- on_connection_close() # 运行后, 清理工作
- 根据需要, 选择使用
- 3. cookies处理:
- set
- get
- clear
- 4. HTTP头处理:
- set_status() # 状态码
- set_header() # 头信息
- 5. 重定向:
- redirect()
"""
class RequestHandler(object):
"""Subclass this class and define get() or post() to make a handler.
If you want to support more methods than the standard GET/HEAD/POST, you
should override the class variable SUPPORTED_METHODS in your
RequestHandler class.
译:
1. 继承此类,并自定义get(), post()方法,创建 handler
2. 若需要支持更多方法(GET/HEAD/POST), 需要 在 子类中 覆写 类变量 SUPPORTED_METHODS
"""
SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PUT")
def __init__(self, application, request, transforms=None):
self.application = application
self.request = request
self._headers_written = False
self._finished = False
self._auto_finish = True
self._transforms = transforms or []
self.ui = _O((n, self._ui_method(m)) for n, m in
application.ui_methods.iteritems())
self.ui["modules"] = _O((n, self._ui_module(n, m)) for n, m in
application.ui_modules.iteritems())
self.clear()
# Check since connection is not available in WSGI
if hasattr(self.request, "connection"):
self.request.connection.stream.set_close_callback(
self.on_connection_close) # 注意 self.on_connection_close() 调用时机
@property
def settings(self):
return self.application.settings
# 如下这部分, 默认的接口定义, 如果子类没有覆写这些方法,就直接抛出异常.
# 也就是说: 这些接口, 必须要 覆写,才可以用
def head(self, *args, **kwargs):
raise HTTPError(405)
def get(self, *args, **kwargs):
raise HTTPError(405)
def post(self, *args, **kwargs):
raise HTTPError(405)
def delete(self, *args, **kwargs):
raise HTTPError(405)
def put(self, *args, **kwargs):
raise HTTPError(405)
# 预定义接口: 准备工作函数, 给需要 个性化配置用
# 注意调用时机: self._execute()
def prepare(self):
"""Called before the actual handler method.
Useful to override in a handler if you want a common bottleneck for
all of your requests.
"""
pass
# 预定义接口2: 执行完后, 附带清理工作.(根据需要自行修改)
# 注意调用时机: __init__()
def on_connection_close(self):
"""Called in async handlers if the client closed the connection.
You may override this to clean up resources associated with
long-lived connections.
Note that the select()-based implementation of IOLoop does not detect
closed connections and so this method will not be called until
you try (and fail) to produce some output. The epoll- and kqueue-
based implementations should detect closed connections even while
the request is idle.
"""
pass
def clear(self):
"""Resets all headers and content for this response."""
self._headers = {
"Server": "TornadoServer/1.0",
"Content-Type": "text/html; charset=UTF-8",
}
if not self.request.supports_http_1_1():
if self.request.headers.get("Connection") == "Keep-Alive":
self.set_header("Connection", "Keep-Alive")
self._write_buffer = []
self._status_code = 200
# 设置 HTTP状态码
def set_status(self, status_code):
"""Sets the status code for our response."""
assert status_code in httplib.responses # 使用 assert 方式 作条件判断, 出错时,直接抛出
self._status_code = status_code
# 设置 HTTP头信息
# 根据 value 类型, 作 格式转换处理
def set_header(self, name, value):
"""Sets the given response header name and value.
If a datetime is given, we automatically format it according to the
HTTP specification. If the value is not a string, we convert it to
a string. All header values are then encoded as UTF-8.
"""
if isinstance(value, datetime.datetime):
t = calendar.timegm(value.utctimetuple())
value = email.utils.formatdate(t, localtime=False, usegmt=True)
elif isinstance(value, int) or isinstance(value, long):
value = str(value)
else:
value = _utf8(value)
# If \n is allowed into the header, it is possible to inject
# additional headers or split the request. Also cap length to
# prevent obviously erroneous values.
safe_value = re.sub(r"[\x00-\x1f]", " ", value)[:4000] # 正则过滤 + 截取4000长度字符串
if safe_value != value:
raise ValueError("Unsafe header value %r", value)
self._headers[name] = value
_ARG_DEFAULT = []
def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we throw an HTTP 404 exception if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
"""
args = self.get_arguments(name, strip=strip)
if not args:
if default is self._ARG_DEFAULT:
raise HTTPError(404, "Missing argument %s" % name)
return default
return args[-1]
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
values = self.request.arguments.get(name, [])
# Get rid of any weird control chars
values = [re.sub(r"[\x00-\x08\x0e-\x1f]", " ", x) for x in values]
values = [_unicode(x) for x in values]
if strip:
values = [x.strip() for x in values]
return values
@property
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
# 如果不存在,定义cookies
# 如果存在, 返回之
if not hasattr(self, "_cookies"):
self._cookies = Cookie.BaseCookie() # 定义
if "Cookie" in self.request.headers:
try:
self._cookies.load(self.request.headers["Cookie"]) # 赋值
except:
self.clear_all_cookies() # 异常时,调用 自定义清理函数
return self._cookies
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if name in self.cookies: # 注意, 因为 cookies() 被定义成 property, 可以直接这样调用
return self.cookies[name].value
return default
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
name = _utf8(name)
value = _utf8(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
new_cookie = Cookie.BaseCookie()
self._new_cookies.append(new_cookie)
new_cookie[name] = value
if domain:
new_cookie[name]["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
new_cookie[name]["expires"] = email.utils.formatdate(
timestamp, localtime=False, usegmt=True)
if path:
new_cookie[name]["path"] = path
for k, v in kwargs.iteritems():
new_cookie[name][k] = v
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
# 赋空值, 清掉 cookie, 多个web框架,标准实现写法
self.set_cookie(name, value="", path=path, expires=expires,
domain=domain)
def clear_all_cookies(self):
"""Deletes all the cookies the user sent with this request."""
# 注: 注意如上2个相关函数 命名特征
# - 单个操作: clear_cookie()
# - 批量操作: clear_all_cookies()
for name in self.cookies.iterkeys():
self.clear_cookie(name)
def set_secure_cookie(self, name, value, expires_days=30, **kwargs):
"""Signs and timestamps a cookie so it cannot be forged.
You must specify the 'cookie_secret' setting in your Application
to use this method. It should be a long, random sequence of bytes
to be used as the HMAC secret for the signature.
To read a cookie set with this method, use get_secure_cookie().
"""
# 如下几步, 构造 "安全的cookie", 加 时间戳, 防伪造
timestamp = str(int(time.time()))
value = base64.b64encode(value)
signature = self._cookie_signature(name, value, timestamp) # 加时间戳
value = "|".join([value, timestamp, signature])
self.set_cookie(name, value, expires_days=expires_days, **kwargs)
def get_secure_cookie(self, name, include_name=True, value=None):
"""Returns the given signed cookie if it validates, or None.
In older versions of Tornado (0.1 and 0.2), we did not include the
name of the cookie in the cookie signature. To read these old-style
cookies, pass include_name=False to this method. Otherwise, all
attempts to read old-style cookies will fail (and you may log all
your users out whose cookies were written with a previous Tornado
version).
"""
if value is None:
value = self.get_cookie(name)
if not value:
return None
parts = value.split("|")
if len(parts) != 3:
return None
if include_name:
signature = self._cookie_signature(name, parts[0], parts[1])
else:
signature = self._cookie_signature(parts[0], parts[1])
if not _time_independent_equals(parts[2], signature):
logging.warning("Invalid cookie signature %r", value)
return None
timestamp = int(parts[1])
if timestamp < time.time() - 31 * 86400:
logging.warning("Expired cookie %r", value)
return None
# 尝试返回
try:
return base64.b64decode(parts[0])
except:
return None
def _cookie_signature(self, *parts):
self.require_setting("cookie_secret", "secure cookies")
hash = hmac.new(self.application.settings["cookie_secret"],
digestmod=hashlib.sha1)
for part in parts:
hash.update(part)
return hash.hexdigest()
# 关键代码: 重定向
#
def redirect(self, url, permanent=False):
"""Sends a redirect to the given (optionally relative) URL."""
if self._headers_written:
raise Exception("Cannot redirect after headers have been written")
self.set_status(301 if permanent else 302)
# Remove whitespace
url = re.sub(r"[\x00-\x20]+", "", _utf8(url))
self.set_header("Location", urlparse.urljoin(self.request.uri, url))
self.finish() # 调用处理
# 关键代码: 准备 渲染页面的 数据, 常用接口函数
# 特别说明:
# - 这里 write() 方法, 并没有直接 渲染页面, 而是在 准备 渲染数据
# - 实际的 渲染HTML页面操作, 在 finish() 中
def write(self, chunk):
"""Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be text/javascript.
"""
assert not self._finished
if isinstance(chunk, dict):
chunk = escape.json_encode(chunk)
self.set_header("Content-Type", "text/javascript; charset=UTF-8")
chunk = _utf8(chunk)
self._write_buffer.append(chunk) # 准备 待渲染的 HTML数据
# 关键代码: 渲染页面
#
def render(self, template_name, **kwargs):
"""Renders the template with the given arguments as the response."""
html = self.render_string(template_name, **kwargs)
# Insert the additional JS and CSS added by the modules on the page
js_embed = []
js_files = []
css_embed = []
css_files = []
html_heads = []
html_bodies = []
for module in getattr(self, "_active_modules", {}).itervalues():
# JS 部分
embed_part = module.embedded_javascript()
if embed_part:
js_embed.append(_utf8(embed_part))
file_part = module.javascript_files()
if file_part:
if isinstance(file_part, basestring):
js_files.append(file_part)
else:
js_files.extend(file_part)
# CSS 部分
embed_part = module.embedded_css()
if embed_part:
css_embed.append(_utf8(embed_part))
file_part = module.css_files()
if file_part:
if isinstance(file_part, basestring):
css_files.append(file_part)
else:
css_files.extend(file_part)
# Header 部分
head_part = module.html_head()
if head_part:
html_heads.append(_utf8(head_part))
body_part = module.html_body()
if body_part:
html_bodies.append(_utf8(body_part))
# ----------------------------------------------------------
# 如下是 分块处理部分:
# - 本质工作: 在 拼接一个 长 HTML 字符串(包含 HTML,CSS,JS)
# ----------------------------------------------------------
if js_files:
# Maintain order of JavaScript files given by modules
paths = []
unique_paths = set()
for path in js_files:
if not path.startswith("/") and not path.startswith("http:"):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
js = ''.join('<script src="' + escape.xhtml_escape(p) +
'" type="text/javascript"></script>'
for p in paths)
sloc = html.rindex('</body>')
html = html[:sloc] + js + '\n' + html[sloc:]
if js_embed:
js = '<script type="text/javascript">\n//<![CDATA[\n' + \
'\n'.join(js_embed) + '\n//]]>\n</script>'
sloc = html.rindex('</body>')
html = html[:sloc] + js + '\n' + html[sloc:]
if css_files:
paths = set()
for path in css_files:
if not path.startswith("/") and not path.startswith("http:"):
paths.add(self.static_url(path))
else:
paths.add(path)
css = ''.join('<link href="' + escape.xhtml_escape(p) + '" '
'type="text/css" rel="stylesheet"/>'
for p in paths)
hloc = html.index('</head>')
html = html[:hloc] + css + '\n' + html[hloc:]
if css_embed:
css = '<style type="text/css">\n' + '\n'.join(css_embed) + \
'\n</style>'
hloc = html.index('</head>')
html = html[:hloc] + css + '\n' + html[hloc:]
if html_heads:
hloc = html.index('</head>')
html = html[:hloc] + ''.join(html_heads) + '\n' + html[hloc:]
if html_bodies:
hloc = html.index('</body>')
html = html[:hloc] + ''.join(html_bodies) + '\n' + html[hloc:]
# 注意
self.finish(html) # 关键调用
def render_string(self, template_name, **kwargs):
"""Generate the given template with the given arguments.
We return the generated string. To generate and write a template
as a response, use render() above.
"""
# If no template_path is specified, use the path of the calling file
template_path = self.get_template_path()
if not template_path:
frame = sys._getframe(0)
web_file = frame.f_code.co_filename
while frame.f_code.co_filename == web_file:
frame = frame.f_back
template_path = os.path.dirname(frame.f_code.co_filename)
if not getattr(RequestHandler, "_templates", None):
RequestHandler._templates = {}
if template_path not in RequestHandler._templates:
loader = self.application.settings.get("template_loader") or\
template.Loader(template_path)
RequestHandler._templates[template_path] = loader # 注意
t = RequestHandler._templates[template_path].load(template_name)
args = dict(
handler=self,
request=self.request,
current_user=self.current_user,
locale=self.locale,
_=self.locale.translate,
static_url=self.static_url,
xsrf_form_html=self.xsrf_form_html,
reverse_url=self.application.reverse_url
)
args.update(self.ui)
args.update(kwargs)
return t.generate(**args)
def flush(self, include_footers=False):
"""Flushes the current output buffer to the nextwork."""
if self.application._wsgi:
raise Exception("WSGI applications do not support flush()")
chunk = "".join(self._write_buffer)
self._write_buffer = []
if not self._headers_written:
self._headers_written = True
for transform in self._transforms:
self._headers, chunk = transform.transform_first_chunk(
self._headers, chunk, include_footers)
headers = self._generate_headers()
else:
for transform in self._transforms:
chunk = transform.transform_chunk(chunk, include_footers)
headers = ""
# Ignore the chunk and only write the headers for HEAD requests
if self.request.method == "HEAD":
if headers:
self.request.write(headers) # 特别注意 self.request.write() 方法
return
if headers or chunk:
self.request.write(headers + chunk)
# 超级关键代码: 写HTML页面
#
#
def finish(self, chunk=None):
"""Finishes this response, ending the HTTP request."""
assert not self._finished
if chunk is not None:
self.write(chunk) # 特别注意, 这里的关键调用
# Automatically support ETags and add the Content-Length header if
# we have not flushed any content yet.
if not self._headers_written:
if (self._status_code == 200 and self.request.method == "GET" and
"Etag" not in self._headers):
hasher = hashlib.sha1()
for part in self._write_buffer:
hasher.update(part)
etag = '"%s"' % hasher.hexdigest()
inm = self.request.headers.get("If-None-Match")
if inm and inm.find(etag) != -1:
self._write_buffer = []
self.set_status(304)
else:
self.set_header("Etag", etag)
if "Content-Length" not in self._headers:
content_length = sum(len(part) for part in self._write_buffer)
self.set_header("Content-Length", content_length)
if hasattr(self.request, "connection"):
# Now that the request is finished, clear the callback we
# set on the IOStream (which would otherwise prevent the
# garbage collection of the RequestHandler when there
# are keepalive connections)
self.request.connection.stream.set_close_callback(None)
if not self.application._wsgi:
self.flush(include_footers=True)
self.request.finish() # 注意调用
self._log()
self._finished = True
# 给浏览器,返回 内部错误
def send_error(self, status_code=500, **kwargs):
"""Sends the given HTTP error code to the browser.
We also send the error HTML for the given error code as returned by
get_error_html. Override that method if you want custom error pages
for your application.
"""
if self._headers_written:
logging.error("Cannot send error response after headers written")
if not self._finished:
self.finish()
return
self.clear()
self.set_status(status_code)
message = self.get_error_html(status_code, **kwargs)
self.finish(message) # 写出信息
def get_error_html(self, status_code, **kwargs):
"""Override to implement custom error pages.
If this error was caused by an uncaught exception, the
exception object can be found in kwargs e.g. kwargs['exception']
"""
return "<html><title>%(code)d: %(message)s</title>" \
"<body>%(code)d: %(message)s</body></html>" % {
"code": status_code,
"message": httplib.responses[status_code],
}
# 本地配置: 通常用于设置 国际化-语言 (浏览器语言)
#
@property
def locale(self):
"""The local for the current session.
Determined by either get_user_locale, which you can override to
set the locale based on, e.g., a user preference stored in a
database, or get_browser_locale, which uses the Accept-Language
header.
"""
if not hasattr(self, "_locale"):
self._locale = self.get_user_locale() # 配置为 用户设置
if not self._locale:
self._locale = self.get_browser_locale() # 配置为 浏览器默认设置
assert self._locale
return self._locale
# 预定义接口 - 用户配置
# - 使用前, 需覆写该函数
def get_user_locale(self):
"""Override to determine the locale from the authenticated user.
If None is returned, we use the Accept-Language header.
"""
return None
# 默认浏览器设置语言环境
def get_browser_locale(self, default="en_US"):
"""Determines the user's locale from Accept-Language header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
"""
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].startswith("q="):
try:
score = float(parts[1][2:])
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
locales.append((parts[0], score))
if locales:
locales.sort(key=lambda (l, s): s, reverse=True)
codes = [l[0] for l in locales]
return locale.get(*codes)
return locale.get(default)
# 获取当前用户
@property
def current_user(self):
"""The authenticated user for this request.
Determined by either get_current_user, which you can override to
set the user based on, e.g., a cookie. If that method is not
overridden, this method always returns None.
We lazy-load the current user the first time this method is called
and cache the result after that.
"""
if not hasattr(self, "_current_user"):
self._current_user = self.get_current_user()
return self._current_user
# 预定义接口 - 获取当前用户
# - 使用前, 需覆写
# - 特别说明: 通常都需要用到该接口, 基本上一定是需要 覆写的
def get_current_user(self):
"""Override to determine the current user from, e.g., a cookie."""
return None
# ----------------------------------------------------
# 如下2个函数, 用于获取 默认配置参数
# - 登录 URL
# - 模板路径
# - 支持
# ----------------------------------------------------
def get_login_url(self):
"""Override to customize the login URL based on the request.
By default, we use the 'login_url' application setting.
"""
self.require_setting("login_url", "@tornado.web.authenticated")
return self.application.settings["login_url"]
def get_template_path(self):
"""Override to customize template path for each handler.
By default, we use the 'template_path' application setting.
Return None to load templates relative to the calling file.
"""
return self.application.settings.get("template_path")
# 预防 跨站攻击
#
# - 默认先判断是否记录了 token
# - 若已记录, 直接返回
# - 若未记录, 尝试从 cookie 中 获取
# - 若 cookie 中 存在, 从 cookie 中获取,并返回
# - 若 cookie 中 不存在, 主动生成 token, 并同步写入 cookie. (目的是,无需重复生成)
#
@property
def xsrf_token(self):
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
"""
if not hasattr(self, "_xsrf_token"):
token = self.get_cookie("_xsrf") # cookie 中获取
if not token:
token = binascii.b2a_hex(uuid.uuid4().bytes) # token 生成方法
expires_days = 30 if self.current_user else None # token 有效期
self.set_cookie("_xsrf", token, expires_days=expires_days) # 更新 cookie
self._xsrf_token = token # 更新 token
return self._xsrf_token
def check_xsrf_cookie(self):
"""Verifies that the '_xsrf' cookie matches the '_xsrf' argument.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
"""
if self.request.headers.get("X-Requested-With") == "XMLHttpRequest":
return
token = self.get_argument("_xsrf", None)
if not token:
raise HTTPError(403, "'_xsrf' argument missing from POST")
if self.xsrf_token != token:
raise HTTPError(403, "XSRF cookie does not match POST argument")
# 提交表单 - 预防 xsrf 攻击方法
def xsrf_form_html(self):
"""An HTML <input/> element to be included with all POST forms.
It defines the _xsrf input value, which we check on all POST
requests to prevent cross-site request forgery.
If you have set the 'xsrf_cookies' application setting, you must include this
HTML within all of your HTML forms.
See check_xsrf_cookie() above for more information.
"""
# 特别注意: 该 <表单提交> HTML字符串, 要含有 (name="_xsrf") 字段
return '<input type="hidden" name="_xsrf" value="' + \
escape.xhtml_escape(self.xsrf_token) + '"/>'
# 静态资源路径
def static_url(self, path):
"""Returns a static URL for the given relative static file path.
This method requires you set the 'static_path' setting in your
application (which specifies the root directory of your static
files).
We append ?v=<signature> to the returned URL, which makes our
static file handler set an infinite expiration header on the
returned content. The signature is based on the content of the
file.
If this handler has a "include_host" attribute, we include the
full host for every static URL, including the "http://". Set
this attribute for handlers whose output needs non-relative static
path names.
"""
self.require_setting("static_path", "static_url")
if not hasattr(RequestHandler, "_static_hashes"):
RequestHandler._static_hashes = {}
hashes = RequestHandler._static_hashes
if path not in hashes:
try:
f = open(os.path.join(
self.application.settings["static_path"], path))
hashes[path] = hashlib.md5(f.read()).hexdigest()
f.close()
except:
logging.error("Could not open static file %r", path)
hashes[path] = None
base = self.request.protocol + "://" + self.request.host \
if getattr(self, "include_host", False) else ""
static_url_prefix = self.settings.get('static_url_prefix', '/static/')
if hashes.get(path):
return base + static_url_prefix + path + "?v=" + hashes[path][:5]
else:
return base + static_url_prefix + path
# 异步回调
def async_callback(self, callback, *args, **kwargs):
"""Wrap callbacks with this if they are used on asynchronous requests.
Catches exceptions and properly finishes the request.
"""
if callback is None:
return None
if args or kwargs:
callback = functools.partial(callback, *args, **kwargs)
def wrapper(*args, **kwargs):
try:
return callback(*args, **kwargs)
except Exception, e:
if self._headers_written:
logging.error("Exception after headers written",
exc_info=True)
else:
self._handle_request_exception(e)
return wrapper
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if not self.application.settings.get(name):
raise Exception("You must define the '%s' setting in your "
"application to use %s" % (name, feature))
def reverse_url(self, name, *args):
return self.application.reverse_url(name, *args)
# 关键代码:
#
def _execute(self, transforms, *args, **kwargs):
"""Executes this request with the given output transforms."""
self._transforms = transforms
try:
if self.request.method not in self.SUPPORTED_METHODS:
raise HTTPError(405)
# If XSRF cookies are turned on, reject form submissions without
# the proper cookie
if self.request.method == "POST" and \
self.application.settings.get("xsrf_cookies"):
self.check_xsrf_cookie() # 检查
self.prepare() # 注意调用时机
if not self._finished:
getattr(self, self.request.method.lower())(*args, **kwargs)
if self._auto_finish and not self._finished:
self.finish() # 关键调用
except Exception, e:
self._handle_request_exception(e)
def _generate_headers(self):
lines = [self.request.version + " " + str(self._status_code) + " " +
httplib.responses[self._status_code]]
lines.extend(["%s: %s" % (n, v) for n, v in self._headers.iteritems()])
for cookie_dict in getattr(self, "_new_cookies", []):
for cookie in cookie_dict.values():
lines.append("Set-Cookie: " + cookie.OutputString(None))
return "\r\n".join(lines) + "\r\n\r\n"
# 打印出错日志
def _log(self):
if self._status_code < 400:
log_method = logging.info
elif self._status_code < 500:
log_method = logging.warning
else:
log_method = logging.error
request_time = 1000.0 * self.request.request_time()
# 日志打印
log_method("%d %s %.2fms", self._status_code,
self._request_summary(), request_time)
def _request_summary(self):
return self.request.method + " " + self.request.uri + " (" + \
self.request.remote_ip + ")"
def _handle_request_exception(self, e):
if isinstance(e, HTTPError):
if e.log_message:
format = "%d %s: " + e.log_message
args = [e.status_code, self._request_summary()] + list(e.args)
logging.warning(format, *args)
if e.status_code not in httplib.responses:
logging.error("Bad HTTP status code: %d", e.status_code)
self.send_error(500, exception=e)
else:
self.send_error(e.status_code, exception=e)
else:
logging.error("Uncaught exception %s\n%r", self._request_summary(),
self.request, exc_info=e)
self.send_error(500, exception=e)
def _ui_module(self, name, module):
def render(*args, **kwargs):
if not hasattr(self, "_active_modules"):
self._active_modules = {}
if name not in self._active_modules:
self._active_modules[name] = module(self)
rendered = self._active_modules[name].render(*args, **kwargs)
return rendered
return render
def _ui_method(self, method):
return lambda *args, **kwargs: method(self, *args, **kwargs)
# 装饰器定义: 异步处理
def asynchronous(method):
"""Wrap request handler methods with this if they are asynchronous.
If this decorator is given, the response is not finished when the
method returns. It is up to the request handler to call self.finish()
to finish the HTTP request. Without this decorator, the request is
automatically finished when the get() or post() method returns.
class MyRequestHandler(web.RequestHandler):
@web.asynchronous
def get(self):
http = httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed.com/", self._on_download)
def _on_download(self, response):
self.write("Downloaded!")
self.finish()
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.application._wsgi:
raise Exception("@asynchronous is not supported for WSGI apps")
self._auto_finish = False
return method(self, *args, **kwargs)
return wrapper
# 装饰器定义: 去 斜杠(/)
def removeslash(method):
"""Use this decorator to remove trailing slashes from the request path.
For example, a request to '/foo/' would redirect to '/foo' with this
decorator. Your request handler mapping should use a regular expression
like r'/foo/*' in conjunction with using the decorator.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.request.path.endswith("/"): # 结尾含 /
if self.request.method == "GET":
uri = self.request.path.rstrip("/") # 过滤掉 /
if self.request.query:
uri += "?" + self.request.query
self.redirect(uri) # 重定向
return
raise HTTPError(404)
return method(self, *args, **kwargs)
return wrapper
# 装饰器定义: 添加 斜杠(/)
def addslash(method):
"""Use this decorator to add a missing trailing slash to the request path.
For example, a request to '/foo' would redirect to '/foo/' with this
decorator. Your request handler mapping should use a regular expression
like r'/foo/?' in conjunction with using the decorator.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.request.path.endswith("/"):
if self.request.method == "GET":
uri = self.request.path + "/"
if self.request.query:
uri += "?" + self.request.query
self.redirect(uri) # 重定向
return
raise HTTPError(404)
return method(self, *args, **kwargs)
return wrapper
# ----------------------------------------------------------------
# 入口:
#
#
# ----------------------------------------------------------------
class Application(object):
"""A collection of request handlers that make up a web application.
Instances of this class are callable and can be passed directly to
HTTPServer to serve the application:
application = web.Application([
(r"/", MainPageHandler),
])
http_server = httpserver.HTTPServer(application)
http_server.listen(8080)
ioloop.IOLoop.instance().start()
The constructor for this class takes in a list of URLSpec objects
or (regexp, request_class) tuples. When we receive requests, we
iterate over the list in order and instantiate an instance of the
first request class whose regexp matches the request path.
Each tuple can contain an optional third element, which should be a
dictionary if it is present. That dictionary is passed as keyword
arguments to the contructor of the handler. This pattern is used
for the StaticFileHandler below:
application = web.Application([
(r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
])
We support virtual hosts with the add_handlers method, which takes in
a host regular expression as the first argument:
application.add_handlers(r"www\.myhost\.com", [
(r"/article/([0-9]+)", ArticleHandler),
])
You can serve static files by sending the static_path setting as a
keyword argument. We will serve those files from the /static/ URI
(this is configurable with the static_url_prefix setting),
and we will serve /favicon.ico and /robots.txt from the same directory.
"""
def __init__(self, handlers=None, default_host="", transforms=None,
wsgi=False, **settings):
"""
:param handlers:
:param default_host:
:param transforms:
:param wsgi:
:param settings:
- gzip : 压缩
- static_path : 静态资源路径
- debug : 调试开关
:return:
"""
if transforms is None:
self.transforms = []
if settings.get("gzip"): # 配置选项
self.transforms.append(GZipContentEncoding)
self.transforms.append(ChunkedTransferEncoding)
else:
self.transforms = transforms
self.handlers = []
self.named_handlers = {}
self.default_host = default_host
self.settings = settings # 自定义配置项
self.ui_modules = {}
self.ui_methods = {}
self._wsgi = wsgi
self._load_ui_modules(settings.get("ui_modules", {}))
self._load_ui_methods(settings.get("ui_methods", {}))
if self.settings.get("static_path"): # 配置项中含: 静态资源路径
path = self.settings["static_path"]
handlers = list(handlers or [])
static_url_prefix = settings.get("static_url_prefix",
"/static/")
handlers = [
(re.escape(static_url_prefix) + r"(.*)", StaticFileHandler,
dict(path=path)),
(r"/(favicon\.ico)", StaticFileHandler, dict(path=path)),
(r"/(robots\.txt)", StaticFileHandler, dict(path=path)),
] + handlers
if handlers:
self.add_handlers(".*$", handlers) # 关键调用
# Automatically reload modified modules
if self.settings.get("debug") and not wsgi: # 调试模式时, 自动监测,并重启项目
import autoreload # tornado 自定义模块
autoreload.start()
def add_handlers(self, host_pattern, host_handlers):
"""Appends the given handlers to our handler list."""
if not host_pattern.endswith("$"):
host_pattern += "$"
handlers = []
# The handlers with the wildcard host_pattern are a special
# case - they're added in the constructor but should have lower
# precedence than the more-precise handlers added later.
# If a wildcard handler group exists, it should always be last
# in the list, so insert new groups just before it.
if self.handlers and self.handlers[-1][0].pattern == '.*$':
self.handlers.insert(-1, (re.compile(host_pattern), handlers)) # 正则匹配
else:
self.handlers.append((re.compile(host_pattern), handlers)) # 正则匹配
for spec in host_handlers:
if type(spec) is type(()): # 元组
assert len(spec) in (2, 3)
pattern = spec[0]
handler = spec[1]
if len(spec) == 3:
kwargs = spec[2]
else:
kwargs = {}
spec = URLSpec(pattern, handler, kwargs) # 关键调用
handlers.append(spec)
if spec.name:
if spec.name in self.named_handlers:
logging.warning(
"Multiple handlers named %s; replacing previous value",
spec.name)
self.named_handlers[spec.name] = spec
def add_transform(self, transform_class):
"""Adds the given OutputTransform to our transform list."""
self.transforms.append(transform_class)
def _get_host_handlers(self, request):
host = request.host.lower().split(':')[0]
for pattern, handlers in self.handlers:
if pattern.match(host):
return handlers
# Look for default host if not behind load balancer (for debugging)
if "X-Real-Ip" not in request.headers:
for pattern, handlers in self.handlers:
if pattern.match(self.default_host):
return handlers
return None
def _load_ui_methods(self, methods):
if type(methods) is types.ModuleType:
self._load_ui_methods(dict((n, getattr(methods, n))
for n in dir(methods)))
elif isinstance(methods, list):
for m in methods:
self._load_ui_methods(m)
else:
for name, fn in methods.iteritems():
if not name.startswith("_") and hasattr(fn, "__call__") \
and name[0].lower() == name[0]:
self.ui_methods[name] = fn
def _load_ui_modules(self, modules):
if type(modules) is types.ModuleType:
self._load_ui_modules(dict((n, getattr(modules, n))
for n in dir(modules)))
elif isinstance(modules, list):
for m in modules:
self._load_ui_modules(m)
else:
assert isinstance(modules, dict)
for name, cls in modules.iteritems():
try:
if issubclass(cls, UIModule):
self.ui_modules[name] = cls
except TypeError:
pass
# 关键定义: 类对象 --> 可调用对象
#
# 注意: 被调用时机
# - wsgi.py
# - WSGIApplication()
# - self.__call__() 方法
#
def __call__(self, request):
"""Called by HTTPServer to execute the request."""
transforms = [t(request) for t in self.transforms]
handler = None
args = []
kwargs = {}
handlers = self._get_host_handlers(request)
if not handlers:
handler = RedirectHandler(
request, "http://" + self.default_host + "/")
else:
for spec in handlers:
match = spec.regex.match(request.path)
if match:
# None-safe wrapper around urllib.unquote to handle
# unmatched optional groups correctly
def unquote(s):
if s is None: return s
return urllib.unquote(s)
handler = spec.handler_class(self, request, **spec.kwargs)
# Pass matched groups to the handler. Since
# match.groups() includes both named and unnamed groups,
# we want to use either groups or groupdict but not both.
kwargs = dict((k, unquote(v))
for (k, v) in match.groupdict().iteritems())
if kwargs:
args = []
else:
args = [unquote(s) for s in match.groups()]
break
if not handler:
handler = ErrorHandler(self, request, 404)
# In debug mode, re-compile templates and reload static files on every
# request so you don't need to restart to see changes
if self.settings.get("debug"):
if getattr(RequestHandler, "_templates", None):
map(lambda loader: loader.reset(),
RequestHandler._templates.values())
RequestHandler._static_hashes = {}
# 关键代码调用时机:
handler._execute(transforms, *args, **kwargs)
return handler
def reverse_url(self, name, *args):
"""Returns a URL path for handler named `name`
The handler must be added to the application as a named URLSpec
"""
if name in self.named_handlers:
return self.named_handlers[name].reverse(*args)
raise KeyError("%s not found in named urls" % name)
# ----------------------------------------------------
# 异常基类
# ----------------------------------------------------
class HTTPError(Exception):
"""An exception that will turn into an HTTP error response."""
def __init__(self, status_code, log_message=None, *args):
self.status_code = status_code
self.log_message = log_message
self.args = args
def __str__(self):
message = "HTTP %d: %s" % (
self.status_code, httplib.responses[self.status_code])
if self.log_message:
return message + " (" + (self.log_message % self.args) + ")"
else:
return message
# ----------------------------------------------------
# 扩展子类: 出错处理
# ----------------------------------------------------
class ErrorHandler(RequestHandler):
"""Generates an error response with status_code for all requests."""
def __init__(self, application, request, status_code):
RequestHandler.__init__(self, application, request)
self.set_status(status_code)
def prepare(self):
raise HTTPError(self._status_code)
# ----------------------------------------------------
# 扩展子类: 重定向处理
# ----------------------------------------------------
class RedirectHandler(RequestHandler):
"""Redirects the client to the given URL for all GET requests.
You should provide the keyword argument "url" to the handler, e.g.:
application = web.Application([
(r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
])
"""
def __init__(self, application, request, url, permanent=True):
RequestHandler.__init__(self, application, request)
self._url = url
self._permanent = permanent
# GET 请求,变成 重定向调用
def get(self):
self.redirect(self._url, permanent=self._permanent)
# ----------------------------------------------------
# 扩展子类: 静态资源处理
# 说明:
# - 覆写 get(), head() 方法
# ----------------------------------------------------
class StaticFileHandler(RequestHandler):
"""A simple handler that can serve static content from a directory.
To map a path to this handler for a static data directory /var/www,
you would add a line to your application like:
application = web.Application([
(r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
])
The local root directory of the content should be passed as the "path"
argument to the handler.
To support aggressive browser caching, if the argument "v" is given
with the path, we set an infinite HTTP expiration header. So, if you
want browsers to cache a file indefinitely, send them to, e.g.,
/static/images/myimage.png?v=xxx.
"""
def __init__(self, application, request, path):
RequestHandler.__init__(self, application, request)
self.root = os.path.abspath(path) + os.path.sep
def head(self, path):
self.get(path, include_body=False)
def get(self, path, include_body=True):
abspath = os.path.abspath(os.path.join(self.root, path))
if not abspath.startswith(self.root):
raise HTTPError(403, "%s is not in root static directory", path)
if not os.path.exists(abspath):
raise HTTPError(404)
if not os.path.isfile(abspath):
raise HTTPError(403, "%s is not a file", path)
stat_result = os.stat(abspath)
modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
self.set_header("Last-Modified", modified)
if "v" in self.request.arguments:
self.set_header("Expires", datetime.datetime.utcnow() + \
datetime.timedelta(days=365*10))
self.set_header("Cache-Control", "max-age=" + str(86400*365*10))
else:
self.set_header("Cache-Control", "public")
mime_type, encoding = mimetypes.guess_type(abspath)
if mime_type:
self.set_header("Content-Type", mime_type)
self.set_extra_headers(path)
# Check the If-Modified-Since, and don't send the result if the
# content has not been modified
ims_value = self.request.headers.get("If-Modified-Since")
if ims_value is not None:
date_tuple = email.utils.parsedate(ims_value)
if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
if if_since >= modified:
self.set_status(304)
return
if not include_body:
return
self.set_header("Content-Length", stat_result[stat.ST_SIZE])
file = open(abspath, "rb") # 读文件
try:
self.write(file.read()) # 写出
finally:
file.close()
def set_extra_headers(self, path):
"""For subclass to add extra headers to the response"""
pass
# ----------------------------------------------------
# 扩展子类: 包裹 另外一个 回调
# 说明:
# - 覆写 prepare() 预定义接口
# ----------------------------------------------------
class FallbackHandler(RequestHandler):
"""A RequestHandler that wraps another HTTP server callback.
The fallback is a callable object that accepts an HTTPRequest,
such as an Application or tornado.wsgi.WSGIContainer. This is most
useful to use both tornado RequestHandlers and WSGI in the same server.
Typical usage:
wsgi_app = tornado.wsgi.WSGIContainer(
django.core.handlers.wsgi.WSGIHandler())
application = tornado.web.Application([
(r"/foo", FooHandler),
(r".*", FallbackHandler, dict(fallback=wsgi_app),
])
"""
def __init__(self, app, request, fallback):
RequestHandler.__init__(self, app, request)
self.fallback = fallback
# 覆写接口
def prepare(self):
self.fallback(self.request)
self._finished = True
# ----------------------------------------------------
# 自定义基类: 输出转换
# 说明:
# - 2个子类
# - GZipContentEncoding()
# - ChunkedTransferEncoding()
# ----------------------------------------------------
class OutputTransform(object):
"""A transform modifies the result of an HTTP request (e.g., GZip encoding)
A new transform instance is created for every request. See the
ChunkedTransferEncoding example below if you want to implement a
new Transform.
"""
def __init__(self, request):
pass
def transform_first_chunk(self, headers, chunk, finishing):
return headers, chunk
def transform_chunk(self, chunk, finishing):
return chunk
class GZipContentEncoding(OutputTransform):
"""Applies the gzip content encoding to the response.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
"""
CONTENT_TYPES = set([
"text/plain", "text/html", "text/css", "text/xml",
"application/x-javascript", "application/xml", "application/atom+xml",
"text/javascript", "application/json", "application/xhtml+xml"])
MIN_LENGTH = 5
def __init__(self, request):
self._gzipping = request.supports_http_1_1() and \
"gzip" in request.headers.get("Accept-Encoding", "")
def transform_first_chunk(self, headers, chunk, finishing):
if self._gzipping:
ctype = headers.get("Content-Type", "").split(";")[0]
self._gzipping = (ctype in self.CONTENT_TYPES) and \
(not finishing or len(chunk) >= self.MIN_LENGTH) and \
(finishing or "Content-Length" not in headers) and \
("Content-Encoding" not in headers)
if self._gzipping:
headers["Content-Encoding"] = "gzip"
self._gzip_value = cStringIO.StringIO()
self._gzip_file = gzip.GzipFile(mode="w", fileobj=self._gzip_value)
self._gzip_pos = 0
chunk = self.transform_chunk(chunk, finishing) # 关键调用
if "Content-Length" in headers:
headers["Content-Length"] = str(len(chunk))
return headers, chunk
def transform_chunk(self, chunk, finishing):
if self._gzipping:
self._gzip_file.write(chunk)
if finishing:
self._gzip_file.close()
else:
self._gzip_file.flush()
chunk = self._gzip_value.getvalue()
if self._gzip_pos > 0:
chunk = chunk[self._gzip_pos:]
self._gzip_pos += len(chunk)
return chunk
class ChunkedTransferEncoding(OutputTransform):
"""Applies the chunked transfer encoding to the response.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
"""
def __init__(self, request):
self._chunking = request.supports_http_1_1()
def transform_first_chunk(self, headers, chunk, finishing):
if self._chunking:
# No need to chunk the output if a Content-Length is specified
if "Content-Length" in headers or "Transfer-Encoding" in headers:
self._chunking = False
else:
headers["Transfer-Encoding"] = "chunked"
chunk = self.transform_chunk(chunk, finishing)
return headers, chunk
def transform_chunk(self, block, finishing):
if self._chunking:
# Don't write out empty chunks because that means END-OF-STREAM
# with chunked encoding
if block:
block = ("%x" % len(block)) + "\r\n" + block + "\r\n"
if finishing:
block += "0\r\n\r\n"
return block
# ----------------------------------------------------
# 装饰器定义: 权限认证
# 代码功能逻辑:
# - 若当前用户已登录, 正常调用
# - 若当前用户未登录
# - 若是 GET 请求,
# - 先获取 login(网站登录页面) URL
# - URL中, 记录 next 字段参数, 记录 未登录前 访问的页面
# - 重定向到 login 页面
# - 正确登录后, 会根据 next 参数, 自动跳转到 登录前的页面
# - 其他请求, 直接抛出 403 错误页面
# 批注:
# - 权限验证的典型实现, 值得学习
# - 代码很精简, 并不复杂
# ----------------------------------------------------
def authenticated(method):
"""Decorate methods with this to require that the user be logged in."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user: # 用户未登录
if self.request.method == "GET": # GET 请求 处理
url = self.get_login_url() # 获取登录页面的 URL
if "?" not in url:
# 关键处理:
# - 在 URL 中,添加 <next>字段 [格式: ?next=/xxxx.html]
# - 目的: 当用户成功登录后,返回到登录前,访问的页面
url += "?" + urllib.urlencode(dict(next=self.request.uri))
self.redirect(url) # 重定向
return
raise HTTPError(403) # 其他请求, 抛出 403 错误
return method(self, *args, **kwargs) # 用户已登录时, 正常调用
return wrapper
# ----------------------------------------------------
# 预定义接口类: UI模块 (处理 CSS,JS)
# 说明:
# - 预定义了一些接口方法,需要 子类化, 并覆写后,才可使用
# ----------------------------------------------------
class UIModule(object):
"""A UI re-usable, modular unit on a page.
UI modules often execute additional queries, and they can include
additional CSS and JavaScript that will be included in the output
page, which is automatically inserted on page render.
"""
def __init__(self, handler):
self.handler = handler
self.request = handler.request
self.ui = handler.ui
self.current_user = handler.current_user
self.locale = handler.locale
# 预定义接口: 必须要 覆写,才能用
def render(self, *args, **kwargs):
raise NotImplementedError()
def embedded_javascript(self):
"""Returns a JavaScript string that will be embedded in the page."""
return None
def javascript_files(self):
"""Returns a list of JavaScript files required by this module."""
return None
def embedded_css(self):
"""Returns a CSS string that will be embedded in the page."""
return None
def css_files(self):
"""Returns a list of CSS files required by this module."""
return None
def html_head(self):
"""Returns a CSS string that will be put in the <head/> element"""
return None
def html_body(self):
"""Returns an HTML string that will be put in the <body/> element"""
return None
def render_string(self, path, **kwargs):
return self.handler.render_string(path, **kwargs)
# ----------------------------------------------------
# 预定义接口类: URL 匹配
# 说明:
# - URL 与 handler 映射
# ----------------------------------------------------
class URLSpec(object):
"""Specifies mappings between URLs and handlers."""
def __init__(self, pattern, handler_class, kwargs={}, name=None):
"""Creates a URLSpec.
Parameters:
pattern: Regular expression to be matched. Any groups in the regex
will be passed in to the handler's get/post/etc methods as
arguments.
handler_class: RequestHandler subclass to be invoked.
kwargs (optional): A dictionary of additional arguments to be passed
to the handler's constructor.
name (optional): A name for this handler. Used by
Application.reverse_url.
"""
if not pattern.endswith('$'):
pattern += '$'
self.regex = re.compile(pattern) # 正则匹配
self.handler_class = handler_class
self.kwargs = kwargs
self.name = name
self._path, self._group_count = self._find_groups()
def _find_groups(self):
"""Returns a tuple (reverse string, group count) for a url.
For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
would return ('/%s/%s/', 2).
"""
pattern = self.regex.pattern
if pattern.startswith('^'):
pattern = pattern[1:]
if pattern.endswith('$'):
pattern = pattern[:-1]
if self.regex.groups != pattern.count('('):
# The pattern is too complicated for our simplistic matching,
# so we can't support reversing it.
return (None, None)
pieces = []
for fragment in pattern.split('('):
if ')' in fragment:
paren_loc = fragment.index(')')
if paren_loc >= 0:
pieces.append('%s' + fragment[paren_loc + 1:])
else:
pieces.append(fragment)
return (''.join(pieces), self.regex.groups)
def reverse(self, *args):
assert self._path is not None, \
"Cannot reverse url regex " + self.regex.pattern
assert len(args) == self._group_count, "required number of arguments "\
"not found"
if not len(args):
return self._path
return self._path % tuple([str(a) for a in args])
url = URLSpec
# ----------------------------------------------------
# UTF8 编码处理: 编码检查
# 代码逻辑:
# - 若 s 是 unicode 字符串
# - 使用 UTF8编码,并返回
# - 若 s 不是 字符串类型, 直接报错
# - 若 s 是 ASCII 字符串, 直接返回
# ----------------------------------------------------
def _utf8(s):
if isinstance(s, unicode):
return s.encode("utf-8")
assert isinstance(s, str)
return s
# ----------------------------------------------------
# unicode 编码处理: 编码检查
# 代码逻辑:
# - 基本类似 _utf8() 函数
# ----------------------------------------------------
def _unicode(s):
if isinstance(s, str):
try:
return s.decode("utf-8")
except UnicodeDecodeError:
raise HTTPError(400, "Non-utf8 argument")
assert isinstance(s, unicode)
return s
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
class _O(dict):
"""Makes a dictionary behave like an object."""
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
| hhstore/tornado-annotated | src/tornado-1.0.0/tornado/web.py | Python | mit | 66,814 |
package finalir;
public class CoreLabel{
String word;
String lemma;
int position;
public CoreLabel setWord(String s){
word = s;
return this;
}
public String word(){
return word;
}
public CoreLabel setBeginPosition(int t){
position = t;
return this;
}
public int beginPosition(){
return position;
}
public CoreLabel setLemma(String s){
lemma = s;
return this;
}
public String lemma(){
return lemma;
}
public CoreLabel(){}
public CoreLabel(String w,String l,int p){
word = w;
lemma = l;
position = p;
}
} | bhlshrf/IR | src/finalir/DataStructure/CoreLabel.java | Java | mit | 726 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* CSVReader Class
*
* Allows to retrieve a CSV file content as a two dimensional array.
* Optionally, the first text line may contains the column names to
* be used to retrieve fields values (default).
*/
class CSVReader
{
var $fields; // columns names retrieved after parsing
var $separator = ','; // separator used to explode each line
var $enclosure = '"'; // enclosure used to decorate each field
var $max_row_size = 4096; // maximum row size to be used for decoding
/**
* Parse a file containing CSV formatted data.
*
* @access public
* @param string
* @param boolean
* @return array
*/
function parse_file($p_Filepath, $p_NamedFields = true)
{
$content = false;
$file = fopen($p_Filepath, 'r');
if ($p_NamedFields) {
$this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
}
while ( ($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false ) {
if ( $row[0] != null ) { // skip empty lines
if ( !$content ) {
$content = array();
}
if ( $p_NamedFields ) {
$items = array();
foreach ( $this->fields as $id => $field ) {
if ( isset($row[$id]) ) {
$items[$field] = $row[$id];
}
}
$content[] = $items;
} else {
$content[] = $row;
}
}
}
fclose($file);
return $content;
}
}
/* End of file CSVReader.php */
/* Location: ./application/helpers/CSVReader.php */ | HugoMontes/si_maestras | application/libraries/CSVReader.php | PHP | mit | 1,876 |
"""
This script exposes a class used to read the Shapefile Index format
used in conjunction with a shapefile. The Index file gives the record
number and content length for every record stored in the main shapefile.
This is useful if you need to extract specific features from a shapefile
without reading the entire file.
How to use:
from ShapefileIndexReader import ShapefileIndex
shx = ShapefileIndex(Path/To/index.shx)
shx.read()
The 'shx' object will expose three properties
1) Path - the path given to the shapefile, if it exists
2) Offsets - an array of byte offsets for each record in the main shapefile
3) Lengths - an array of 16-bit word lengths for each record in the main shapefile
"""
import os
__author__ = 'Sean Taylor Hutchison'
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = 'Sean Taylor Hutchison'
__email__ = 'seanthutchison@gmail.com'
__status__ = 'Development'
class ShapefileIndex:
Records = []
def __bytes_to_index_records(self,file_bytes):
file_length = len(file_bytes)
num_records = int((file_length - 100) / 8)
for record_counter in range(0,num_records):
byte_position = 100 + (record_counter * 8)
offset = int.from_bytes(file_bytes[byte_position:byte_position+4], byteorder='big')
length = int.from_bytes(file_bytes[byte_position+4:byte_position+8], byteorder='big')
self.Records.append([offset,length])
def read(self):
with open(self.Path, 'rb') as shpindex:
self.__bytes_to_index_records(shpindex.read())
def __init__(self, path=None):
if path and os.path.exists(path) and os.path.splitext(path)[1] == '.shx':
self.Path = path
else:
raise FileNotFoundError | taylorhutchison/ShapefileReaderPy | ShapefileIndexReader.py | Python | mit | 1,778 |
import external from '../../../externalModules.js';
import getNumberValues from './getNumberValues.js';
import parseImageId from '../parseImageId.js';
import dataSetCacheManager from '../dataSetCacheManager.js';
import getImagePixelModule from './getImagePixelModule.js';
import getOverlayPlaneModule from './getOverlayPlaneModule.js';
import getLUTs from './getLUTs.js';
import getModalityLUTOutputPixelRepresentation from './getModalityLUTOutputPixelRepresentation.js';
function metaDataProvider(type, imageId) {
const { dicomParser } = external;
const parsedImageId = parseImageId(imageId);
const dataSet = dataSetCacheManager.get(parsedImageId.url);
if (!dataSet) {
return;
}
if (type === 'generalSeriesModule') {
return {
modality: dataSet.string('x00080060'),
seriesInstanceUID: dataSet.string('x0020000e'),
seriesNumber: dataSet.intString('x00200011'),
studyInstanceUID: dataSet.string('x0020000d'),
seriesDate: dicomParser.parseDA(dataSet.string('x00080021')),
seriesTime: dicomParser.parseTM(dataSet.string('x00080031') || ''),
};
}
if (type === 'patientStudyModule') {
return {
patientAge: dataSet.intString('x00101010'),
patientSize: dataSet.floatString('x00101020'),
patientWeight: dataSet.floatString('x00101030'),
};
}
if (type === 'imagePlaneModule') {
const imageOrientationPatient = getNumberValues(dataSet, 'x00200037', 6);
const imagePositionPatient = getNumberValues(dataSet, 'x00200032', 3);
const pixelSpacing = getNumberValues(dataSet, 'x00280030', 2);
let columnPixelSpacing = null;
let rowPixelSpacing = null;
if (pixelSpacing) {
rowPixelSpacing = pixelSpacing[0];
columnPixelSpacing = pixelSpacing[1];
}
let rowCosines = null;
let columnCosines = null;
if (imageOrientationPatient) {
rowCosines = [
parseFloat(imageOrientationPatient[0]),
parseFloat(imageOrientationPatient[1]),
parseFloat(imageOrientationPatient[2]),
];
columnCosines = [
parseFloat(imageOrientationPatient[3]),
parseFloat(imageOrientationPatient[4]),
parseFloat(imageOrientationPatient[5]),
];
}
return {
frameOfReferenceUID: dataSet.string('x00200052'),
rows: dataSet.uint16('x00280010'),
columns: dataSet.uint16('x00280011'),
imageOrientationPatient,
rowCosines,
columnCosines,
imagePositionPatient,
sliceThickness: dataSet.floatString('x00180050'),
sliceLocation: dataSet.floatString('x00201041'),
pixelSpacing,
rowPixelSpacing,
columnPixelSpacing,
};
}
if (type === 'imagePixelModule') {
return getImagePixelModule(dataSet);
}
if (type === 'modalityLutModule') {
return {
rescaleIntercept: dataSet.floatString('x00281052'),
rescaleSlope: dataSet.floatString('x00281053'),
rescaleType: dataSet.string('x00281054'),
modalityLUTSequence: getLUTs(
dataSet.uint16('x00280103'),
dataSet.elements.x00283000
),
};
}
if (type === 'voiLutModule') {
const modalityLUTOutputPixelRepresentation = getModalityLUTOutputPixelRepresentation(
dataSet
);
return {
windowCenter: getNumberValues(dataSet, 'x00281050', 1),
windowWidth: getNumberValues(dataSet, 'x00281051', 1),
voiLUTSequence: getLUTs(
modalityLUTOutputPixelRepresentation,
dataSet.elements.x00283010
),
};
}
if (type === 'sopCommonModule') {
return {
sopClassUID: dataSet.string('x00080016'),
sopInstanceUID: dataSet.string('x00080018'),
};
}
if (type === 'petIsotopeModule') {
const radiopharmaceuticalInfo = dataSet.elements.x00540016;
if (radiopharmaceuticalInfo === undefined) {
return;
}
const firstRadiopharmaceuticalInfoDataSet =
radiopharmaceuticalInfo.items[0].dataSet;
return {
radiopharmaceuticalInfo: {
radiopharmaceuticalStartTime: dicomParser.parseTM(
firstRadiopharmaceuticalInfoDataSet.string('x00181072') || ''
),
radionuclideTotalDose: firstRadiopharmaceuticalInfoDataSet.floatString(
'x00181074'
),
radionuclideHalfLife: firstRadiopharmaceuticalInfoDataSet.floatString(
'x00181075'
),
},
};
}
if (type === 'overlayPlaneModule') {
return getOverlayPlaneModule(dataSet);
}
}
export default metaDataProvider;
| chafey/cornerstoneWADOImageLoader | src/imageLoader/wadouri/metaData/metaDataProvider.js | JavaScript | mit | 4,492 |
// Template Source: BaseEntityCollectionResponse.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.termstore.requests;
import com.microsoft.graph.termstore.models.Store;
import com.microsoft.graph.http.BaseCollectionResponse;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Store Collection Response.
*/
public class StoreCollectionResponse extends BaseCollectionResponse<Store> {
}
| microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/termstore/requests/StoreCollectionResponse.java | Java | mit | 752 |
<?php
namespace NRtworks\BusinessDimensionBundle\Model;
use Doctrine\ORM\EntityManager;
use NRtworks\GlobalUtilsFunctionsBundle\Services\arrayFunctions;
use NRtworks\GlobalUtilsFunctionsBundle\Services\APIGetData;
class setUpForDimension extends \Symfony\Component\DependencyInjection\ContainerAware{
protected $em;
protected $arrayFunctions;
protected $possible;
protected $remotePossible;
protected $noexist;
protected $API;
public function __construct(EntityManager $em, arrayFunctions $arrayFunctions, APIGetData $API)
{
$this->em = $em;
$this->arrayFunctions = $arrayFunctions;
$this->API = $API;
$this->possible = array("ChartOfAccounts","Account","BusinessUnit","FiscalYear","Period","Version","Cycle","Currency","CurrencyValuation","Campaign");
$this->remotePossible = array("ChartOfAccounts","Account","BusinessUnit","FiscalYear","Period","Version","Cycle","Currency","Campaign","icousers","Usertype");
$this->noexist = "Unauthorized dimension";
}
// the following function returns the address used to create the object of a related $dimension
public function getAddress($dimension){
if(in_array($dimension,$this->possible))
{
$base = "\NRtworks\BusinessDimensionBundle\Entity\\";
$result = $base . $dimension;
return $result;
}
else
{;
return $this->noexist;
}
}
// the following function returns the address used to get the repository of a related $dimension
public function getRepositoryAddress($dimension){
if(in_array($dimension,$this->possible))
{
$base = "NRtworksBusinessDimensionBundle:";
$result = $base . $dimension;
return $result;
}
else
{
return $this->noexist;
}
}
//the following function returns an object of the entity related to the dimension
public function getObject($dimension)
{
$address = $this->getAddress($dimension);
$element = new $address();
return $element;
}
//the following functions returns an array with parameters of the field to edit (name,editable,type of edit)
public function getDefaultObject($dimension,$highestID = null)
{
$address = $this->getAddress($dimension);
$element = new $address($highestID);
$result = $element->getDefaultObject();
return $result;
}
//the following function returns an object of the given dimension
public function getDefaultTrueObject($dimension,$highestID = null, $number = null)
{
$address = $this->getAddress($dimension);
if($highestID != null && $number != null)
{
$element = new $address($highestID,$number);
}
elseif($highestID != null)
{
$element = new $address($highestID);
}
else
{
$element = new $address();
}
return $element;
}
//the following functions returns an array with parameters of the field to edit (name,editable,type of edit)
public function getFieldsNameToEdit($dimension)
{
$address = $this->getAddress($dimension);
$element = new $address();
$result = $element->fieldsToEditinTreeEdit();
return $result;
}
//the following functions gives the "mandatory" selector for a dimension
public function getBasicDiscriminant($dimension)
{
if(in_array($dimension,$this->possible) || in_array($dimension,$this->remotePossible))
{
$discrim = [];
if($dimension == "Account")
{
$discrim["toSelect"] = ["ChartOfAccount"];
$discrim["howToSelect"] = "UserSelection";
}
elseif($dimension == "CurrencyValuation")
{
$discrim["toSelect"] = ["Campaign"];
$discrim["howToSelect"] = "UserSelection";
}
elseif($dimension == "Cycle" || $dimension == "Version" || $dimension == "Period" || $dimension == "FiscalYear" || $dimension == "Currency")
{
$discrim["toSelect"] = "none";
}
else
{
$discrim["toSelect"]= ["customer"];
}
return $discrim;
}
else
{
return $this->noexist;
}
}
//the following function is building an array for a "select" element to be passed to the front
public function buildSelectElements($dimension,$fieldParameters,$param1)
{
foreach($fieldParameters as &$field)
{
if($field["toDo"] == "edit" && $field["editType"] == "select")
{
//if we are here it means the field is to be edited and is a select, so let's check the options
if(isset($field["options"]["remote"]) && $field["options"]["remote"] != "no")
{
$remoteDimension = $field["options"]["remote"];
//here means that the field is remote so we need to request the data given some parameters
if(in_array($remoteDimension,$this->remotePossible))
{
if($remoteDimension == "Account")
{
$whereArray["chartofaccount"] = 1;
}
elseif($remoteDimension == "Cycle" || $remoteDimension == "Version" || $remoteDimension == "Period" || $remoteDimension == "FiscalYear" || $remoteDimension == "Currency")
{
// no need for generic selector here
}
else
{
$whereArray["customer"] = $param1;
}
if(is_array($field["options"]["fieldFilter"]))
{
foreach($field["options"]["fieldFilter"] as $key=>$value)
{
$whereArray[$key] = $value;
}
}
//\Doctrine\Common\Util\Debug::dump($whereArray);
if(isset($whereArray))
{
$elementList = $this->API->requestQuery($this->API->whichBundle($remoteDimension),$remoteDimension,$whereArray);
}
else
{
$elementList = $this->API->requestAll($this->API->whichBundle($remoteDimension),$remoteDimension);
}
unset($whereArray);
//\Doctrine\Common\Util\Debug::dump($elementList);
$elementsAsArray = $this->arrayFunctions->rebuildObjectsAsArrays($elementList);
//\Doctrine\Common\Util\Debug::dump($elementsAsArray);
//ok we got all we need so let's build the array used to build the HTML select element
$arrayHTML = [];
foreach($elementsAsArray as $element)
{
$subarray = array("value"=>$element[$field["options"]["selectFields"][0]],"text"=>$element[$field["options"]["selectFields"][1]]);
array_push($arrayHTML,$subarray);
}
$field["options"] = $arrayHTML;
}
else
{
return $this->noexist;
}
}
else
{
//here means that the field must have a "local" parameter, set up below
switch($dimension)
{
case "Campaign":
if($field["fieldName"] == "fiscalYear")
{
$field["options"] = $this->getFiscalYearList("selectArray");
}
elseif($field["fieldName"] == "version")
{
$field["options"] = $this->getVersionList("selectArray");
}
elseif($field["fieldName"] == "status")
{
$field["options"] = array(0=>["value"=>"not started","text"=>"not started"],1=>["value"=>"in progress","text"=>"in progress"],2=>["value"=>"closed","text"=>"closed"]);
}
else
{
$field["options"] = array("value"=>"throwError","text"=>"an error has occured");
}
break;
case "Account":
if($field["fieldName"] == "sense")
{
$field["options"] = array(0=>array("value"=>"DR","text"=>"Debit"),1=>array("value"=>"CR","text"=>"Credit"));
}
else
{
$field["options"] = array("value"=>"throwError","text"=>"an error has occured");
}
break;
case "BusinessUnit":
if($field["fieldName"] == "country")
{
$field["options"] = array(0=>array("value"=>"FR","text"=>"France"));
}
else
{
$field["options"] = array("value"=>"throwError","text"=>"an error has occured");
}
break;
default:
$field["options"] = array("value"=>"throwError","text"=>"an error has occured");
break;
}
}
}
}
return $fieldParameters;
}
//the following function returns a list of the fiscal years, however you want it
public function getFiscalYearList($how)
{
switch($how)
{
case "simpleArray":
return array(2012,2013,2014,2015,2016,2017,2018,2019,2020);
break;
case "associativeArray":
return array(2012=>2012,2013=>2013,2014=>2014,2015=>2015,2016=>2016,2017=>2017,2018=>2018,2019=>2019,2020=>2020);
break;
case "selectArray":
$result = [];
$i = 0;
foreach($this->getFiscalYearList("simpleArray") as $year)
{
$result[$i] = array("value"=>$year,"text"=>$year);
$i++;
}
return $result;
break;
default:
return "unknown case";
break;
}
}
//the following function returns a list of the versions, however you want it
public function getVersionList($how)
{
switch($how)
{
case "simpleArray":
return array(1,2,3,4,5);
break;
case "associativeArray":
return array(1=>1,2=>2,3=>3,4=>4,5=>5);
break;
case "selectArray":
$result = [];
$i = 0;
foreach($this->getVersionList("simpleArray") as $version)
{
$result[$i] = array("value"=>$version,"text"=>$version);
$i++;
}
return $result;
break;
default:
return "unknown case";
break;
}
}
//the following function returns a list of elements from an entity given some conditions
public function getFlatList($dimension,$customer = 0,$chartOfAccounts = 0)
{
$address = $this->getRepositoryAddress($dimension);
$repo = $this->em->getRepository($address);
if(in_array($dimension,$this->possible))
{
if($dimension == "Account")
{
return $allaccounts = $repo->findByChartofaccount(1);
}
elseif($dimension == "BusinessUnit")
{
return $allaccounts = $repo->findByCustomer($customer);
}
}
else
{
return $this->noexist;
}
}
//the following function creates a new object with values passed to the function
public function createAnObject($customer,$dimension,$element,$parent = null)
{
if(in_array($dimension,$this->possible))
{
if($dimension == "Account")
{
$newObject = $this->getObject($dimension);
$newObject->fillWithArray($element);
$newObject->setChartOfAccount($parent->getChartOfAccount());
$newObject->setParent($parent);
return $newObject;
}
if($dimension == "BusinessUnit")
{
$newObject = $this->getObject($dimension);
$newObject->setParent($parent);
$newObject->setCustomer($customer);
$newObject->setName($element["name"]);
$newObject->setCode($element["code"]);
$newObject->setCountry($element["country"]);
$newObject->setManager($this->API->requestById($this->API->whichBundle("icousers"),"icousers",$element["manager"]));
$newObject->setSubstitute($this->API->requestById($this->API->whichBundle("icousers"),"icousers",$element["substitute"]));
$newObject->setController($this->API->requestById($this->API->whichBundle("icousers"),"icousers",$element["controller"]));
$newObject->setBusinessCurrency($this->API->requestById($this->API->whichBundle("Currency"),"Currency",$element["businessCurrency"]));
return $newObject;
}
if($dimension == "ChartOfAccounts")
{
$address = $this->getAddress($dimension);
$newObject = new $address();
$newObject->setCustomer($customer);
$newObject->setName($element[1]);
$newObject->setDescription($element[2]);
return $newObject;
}
if($dimension == "Campaign")
{
$address = $this->getAddress($dimension);
$newObject = new $address();
$newObject->setCustomer($customer);
$newObject->setNumber($element[1]);
$newObject->setName($element[2]);
$newObject->setStatus($element[3]);
$newObject->setFiscalYear($element[4]);
$newObject->setVersion($element[5]);
$newObject->setCycle($this->API->requestById($this->API->whichBundle("Cycle"),"Cycle",$element[6]));
$newObject->setPeriod($this->API->requestById($this->API->whichBundle("Period"),"Period",$element[7]));
return $newObject;
}
}
else
{
return $this->noexist;
}
}
//the following function updates an object with values passed to the function
public function updateAnObject($object,$element,$dimension)
{
if(in_array($dimension,$this->possible))
{
if($dimension == "Account")
{
$object->setName($element["name"]);
$object->setCode($element["code"]);
$object->setSense($element["sense"]);
return $object;
}
if($dimension == "ChartOfAccounts")
{
$object->setName($element[1]);
$object->setDescription($element[2]);
return $object;
}
if($dimension == "Campaign")
{
$object->setNumber($element[1]);
$object->setName($element[2]);
$object->setStatus($element[3]);
$object->setFiscalYear($element[4]);
$object->setVersion($element[5]);
$object->setCycle($this->API->requestById($this->API->whichBundle("Cycle"),"Cycle",$element[6]));
$object->setPeriod($this->API->requestById($this->API->whichBundle("Period"),"Period",$element[7]));
return $object;
}
if($dimension == "BusinessUnit")
{
$object->setName($element["name"]);
$object->setCode($element["code"]);
$object->setCountry($element["country"]);
$object->setManager($this->API->requestById($this->API->whichBundle("icousers"),"icousers",$element["manager"]));
$object->setSubstitute($this->API->requestById($this->API->whichBundle("icousers"),"icousers",$element["substitute"]));
$object->setController($this->API->requestById($this->API->whichBundle("icousers"),"icousers",$element["controller"]));
$object->setBusinessCurrency($this->API->requestById($this->API->whichBundle("Currency"),"Currency",$element["businessCurrency"]));
return $object;
}
}
else
{
return $this->noexist;
}
}
//the following function is the model that saves data modified by the user in flat view
public function saveResultsFromFlatView($result,$elementList,$dimension,$nbFields,$customer)
{
$failedLines = [];
$updatedLines = [];
foreach($result as $element)
{
//var_dump($element);
if(isset($element[$nbFields]) && $element[$nbFields] == "NRtworks_FlatView_T0Cr3at3")
{
//a new element
try
{
$newElement = $this->createAnObject($customer,$dimension,$element);
$this->em->persist($newElement);
array_push($updatedLines,$element);
}
catch(Exception $e)
{
array_push($failedLines,$element);
}
}
elseif(isset($element[$nbFields+1]) && $element[$nbFields+1] == "NRtworks_FlatView_ToD3l3t3")
{
//to delete
try
{
$object = $elementList[$this->arrayFunctions->findIndexOfAPropertyByIdInArrayOfObject($elementList,$element[0])];
$this->em->remove($object);
array_push($updatedLines,$element);
}
catch (Exception $e)
{
array_push($failedLines,$element);
}
}
else
{
// element modified or not
try
{
$object = $elementList[$this->arrayFunctions->findIndexOfAPropertyByIdInArrayOfObject($elementList,$element[0])];
$updatedObject = $this->updateAnObject($object,$element,$dimension);
//\Doctrine\Common\Util\Debug::dump($updatedObject);
if($object != $updatedObject)
{
$this->em->merge($updatedObject);
array_push($updatedLines,$element);
}
}
catch (Exception $e)
{
array_push($failedLines,$element);
}
}
}
$this->em->flush();
$result = array(0=>$failedLines,1=>$updatedLines);
return $result;
}
}
?>
| Morgorth/ICORECON | src/NRtworks/BusinessDimensionBundle/Model/setUpForDimension.php | PHP | mit | 21,059 |
import Tablesaw from '../../dist/tablesaw';
console.log( "this should be the tablesaw object: ", Tablesaw );
| filamentgroup/tablesaw | demo/webpack/app.js | JavaScript | mit | 111 |
/**
* Copyright (C) 2017 Cristian Gomez Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.iyubinest.bonzai;
import android.app.Application;
import android.support.annotation.VisibleForTesting;
import com.facebook.stetho.Stetho;
public class App extends Application {
private AppComponent component;
@Override
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
component = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
}
public AppComponent component() {
return component;
}
@VisibleForTesting
public void setComponent(AppComponent component) {
this.component = component;
}
}
| iyubinest/Bonzai | app/src/main/java/co/iyubinest/bonzai/App.java | Java | mit | 1,212 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace XForms.Utils.Samples.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| wcoder/XForms.Utils | samples/XForms.Utils.Samples/XForms.Utils.Samples.UWP/App.xaml.cs | C# | mit | 3,502 |
#! /usr/bin/env python3
import asyncio
import subprocess
import numpy as np
import time
comm = None
class Camera:
def __init__(self, notify):
self._process = None
self._now_pos = np.array([0., 0., 0.])
self._running = False
self._notify = notify
@asyncio.coroutine
def connect(self):
self._process = yield from asyncio.create_subprocess_exec(
'python2', 'camera.py',
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE
)
self._running = True
@asyncio.coroutine
def run(self):
while self._running:
data = yield from self._process.stdout.readline()
print(data)
self._now_pos = np.array(list(map(float, data.split())))
yield from self._notify(time.time(), self._now_pos)
def stop(self):
self._running = False
self._process.terminate()
| AlphaLambdaMuPi/CamDrone | camera3.py | Python | mit | 937 |
<?php
include_once 'vendor/swiftmailer/swiftmailer/lib/swift_required.php';
require_once 'lib/includes/utilities.inc.php';
include 'lib/functions/functions.inc.php';
$submit = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($submit) && $submit === 'enter') {
$result = login($pdo);
header('Location: addTrivia.php');
exit();
}
?>
<!DOCTYPE html>
<!--
Trivia Game Version 3.0 beta with XML;
by John Pepp
Started: January 31, 2017
Revised: February 27, 2017
-->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<title>Login</title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" href="lib/css/stylesheet.css">
<link rel="stylesheet" href="lib/css/register_stylesheet.css">
</head>
<body>
<div id="shadow">
<div class="textBox">
<h2>Data Successfully Saved!</h2>
</div>
</div>
<div id="container" >
<div id="heading">
<h1>Trivia<span id="toxic">IntoXication</span></h1>
<h2 id="subheading">Don't Drive Drunk! Play this Game Instead!</h2>
</div>
<nav class="nav-bar">
<ul class="topnav" id="myTopnav">
<li><a class="top-link" href="#" > </a></li>
<li><a href="index.php">Home</a></li>
<?php
if (isset($_SESSION['user']->id) && ( $_SESSION['user']->security === 'member' || $_SESSION['user']->security === 'admin' )) {
echo '<li><a href="addTrivia.php">Add Trivia</a></li>';
}
?>
<li><a href="register.php">Register</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li class="icon">
<a href='#'>☰</a>
</li>
</ul>
</nav>
<div class="mainContent">
<form id="login" action="login.php" method="post">
<fieldset>
<legend>Login Form</legend>
<input type="hidden" name="action" value="enter">
<label for="email">Email</label>
<input id="email" type="email" name="email" value="" tabindex="1" autofocus>
<label for="password">Password</label>
<input id="password" type="password" name="password" tabindex="2">
<input type="submit" name="submit" value="enter" tabindex="3">
</fieldset>
</form>
</div>
</div>
<div id="myFooter">
<p class="footer-text">©<?php echo date("Y"); ?> John R. Pepp <span>Dedicated to my mom 11-29-1928 / 02-26-2017</span></p>
</div>
</body>
</html>
| Strider64/Trivia-Game-with-vanilla-javascript-and-PHP | login.php | PHP | mit | 3,077 |
<?php
return array (
'id' => 'samsung_sth_a255_ver1',
'fallback' => 'uptext_generic',
'capabilities' =>
array (
'model_name' => 'STH A255',
'brand_name' => 'Samsung',
'streaming_real_media' => 'none',
),
);
| cuckata23/wurfl-data | data/samsung_sth_a255_ver1.php | PHP | mit | 230 |
<?php
return array (
'id' => 'lg_l1150_ver1_sub6232',
'fallback' => 'lg_l1150_ver1',
'capabilities' =>
array (
'max_data_rate' => '9',
),
);
| cuckata23/wurfl-data | data/lg_l1150_ver1_sub6232.php | PHP | mit | 156 |
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require "active_support"
require "test/unit"
require "turn"
require "nokogiri"
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
| cloverinteractive/sexy_bookmarks | test/test_helper.rb | Ruby | mit | 343 |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: javax.security.cert.CertificateException
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVAX_SECURITY_CERT_CERTIFICATEEXCEPTION_HPP_DECL
#define J2CPP_JAVAX_SECURITY_CERT_CERTIFICATEEXCEPTION_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Exception; } } }
#include <java/lang/Exception.hpp>
#include <java/lang/String.hpp>
namespace j2cpp {
namespace javax { namespace security { namespace cert {
class CertificateException;
class CertificateException
: public object<CertificateException>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
explicit CertificateException(jobject jobj)
: object<CertificateException>(jobj)
{
}
operator local_ref<java::lang::Exception>() const;
CertificateException(local_ref< java::lang::String > const&);
CertificateException();
}; //class CertificateException
} //namespace cert
} //namespace security
} //namespace javax
} //namespace j2cpp
#endif //J2CPP_JAVAX_SECURITY_CERT_CERTIFICATEEXCEPTION_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVAX_SECURITY_CERT_CERTIFICATEEXCEPTION_HPP_IMPL
#define J2CPP_JAVAX_SECURITY_CERT_CERTIFICATEEXCEPTION_HPP_IMPL
namespace j2cpp {
javax::security::cert::CertificateException::operator local_ref<java::lang::Exception>() const
{
return local_ref<java::lang::Exception>(get_jobject());
}
javax::security::cert::CertificateException::CertificateException(local_ref< java::lang::String > const &a0)
: object<javax::security::cert::CertificateException>(
call_new_object<
javax::security::cert::CertificateException::J2CPP_CLASS_NAME,
javax::security::cert::CertificateException::J2CPP_METHOD_NAME(0),
javax::security::cert::CertificateException::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
javax::security::cert::CertificateException::CertificateException()
: object<javax::security::cert::CertificateException>(
call_new_object<
javax::security::cert::CertificateException::J2CPP_CLASS_NAME,
javax::security::cert::CertificateException::J2CPP_METHOD_NAME(1),
javax::security::cert::CertificateException::J2CPP_METHOD_SIGNATURE(1)
>()
)
{
}
J2CPP_DEFINE_CLASS(javax::security::cert::CertificateException,"javax/security/cert/CertificateException")
J2CPP_DEFINE_METHOD(javax::security::cert::CertificateException,0,"<init>","(Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(javax::security::cert::CertificateException,1,"<init>","()V")
} //namespace j2cpp
#endif //J2CPP_JAVAX_SECURITY_CERT_CERTIFICATEEXCEPTION_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| kakashidinho/HQEngine | ThirdParty-mod/java2cpp/javax/security/cert/CertificateException.hpp | C++ | mit | 3,005 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from django.core.files import File
from six import with_metaclass
from django.utils.module_loading import import_string
from rest_framework_tus import signals
from .settings import TUS_SAVE_HANDLER_CLASS
class AbstractUploadSaveHandler(with_metaclass(ABCMeta, object)):
def __init__(self, upload):
self.upload = upload
@abstractmethod
def handle_save(self):
pass
def run(self):
# Trigger state change
self.upload.start_saving()
self.upload.save()
# Initialize saving
self.handle_save()
def finish(self):
# Trigger signal
signals.saved.send(sender=self.__class__, instance=self)
# Finish
self.upload.finish()
self.upload.save()
class DefaultSaveHandler(AbstractUploadSaveHandler):
destination_file_field = 'uploaded_file'
def handle_save(self):
# Save temporary field to file field
file_field = getattr(self.upload, self.destination_file_field)
file_field.save(self.upload.filename, File(open(self.upload.temporary_file_path)))
# Finish upload
self.finish()
def get_save_handler(import_path=None):
return import_string(import_path or TUS_SAVE_HANDLER_CLASS)
| dirkmoors/drf-tus | rest_framework_tus/storage.py | Python | mit | 1,346 |