repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
m1ome/kahlan
src/Matcher/ToContainKey.php
1540
<?php namespace Kahlan\Matcher; use Traversable; use ArrayAccess; class ToContainKey { /** * Expect that `$actual` array contain the `$expected` key. * * @param collection $actual The actual array. * @param mixed $expected The expected key. * @return boolean */ public static function match($actual, $expected) { $params = func_get_args(); $expected = count($params) > 2 ? array_slice($params, 1) : $expected; $expected = (array) $expected; if (is_array($actual)) { foreach($expected as $key) { if (!array_key_exists($key, $actual)) { return false; } } return true; } elseif ($actual instanceof ArrayAccess) { foreach($expected as $key) { if (!isset($actual[$key])) { return false; } } return true; } elseif ($actual instanceof Traversable) { foreach ($expected as $key) { foreach ($actual as $k => $v) { if ($key === $k) { continue 2; } } return false; } return true; } return false; } /** * Returns the description message. * * @return string The description message. */ public static function description() { return "contain expected key."; } }
mit
studieresan/overlord
src/mongodb/ContactRequest.ts
478
import * as mongoose from 'mongoose' import * as models from '../models' export type ContactRequestDocument = mongoose.Document & models.ContactRequest const ContactRequestSchema: mongoose.Schema = new mongoose.Schema({ email: { type: String, unique: true }, resolved: { type: Boolean, default: false }, priority: { type: Number }, }, { timestamps: true }) export const ContactRequest = mongoose.model<ContactRequestDocument>( 'ContactRequest', ContactRequestSchema)
mit
tcsiwula/java_code
classes/cs212/LectureCode/src/anonymous_classe/HelloWorldAnonymousClasses.java
1281
package anonymous_classe; public class HelloWorldAnonymousClasses { interface HelloWorld { public void greet(); public void greetSomeone(String someone); } public void sayHello() { class EnglishGreeting implements HelloWorld { String name = "world"; public void greet() { greetSomeone("world"); } public void greetSomeone(String someone) { name = someone; System.out.println("Hello " + name); } } HelloWorld englishGreeting = new EnglishGreeting(); HelloWorld frenchGreeting = new HelloWorld() { String name = "tout le monde"; public void greet() { greetSomeone("tout le monde"); } public void greetSomeone(String someone) { name = someone; System.out.println("Salut " + name); } }; HelloWorld spanishGreeting = new HelloWorld() { String name = "mundo"; public void greet() { greetSomeone("mundo"); } public void greetSomeone(String someone) { name = someone; System.out.println("Hola, " + name); } }; englishGreeting.greet(); frenchGreeting.greetSomeone("Fred"); spanishGreeting.greet(); } public static void main(String... args) { HelloWorldAnonymousClasses myApp = new HelloWorldAnonymousClasses(); myApp.sayHello(); } }
mit
plotly/python-api
packages/python/plotly/plotly/validators/sankey/node/_hovertemplate.py
528
import _plotly_utils.basevalidators class HovertemplateValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="hovertemplate", parent_name="sankey.node", **kwargs ): super(HovertemplateValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), **kwargs )
mit
mauretto78/mamba-base
tests/Command/FormCreateAndDeleteCommandTest.php
3221
<?php namespace Mamba\Command\Tests; use Mamba\Command\FormCreateCommand; use Mamba\Command\FormDeleteCommand; use Mamba\Tests\MambaTest; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Tester\CommandTester; class FormCreateAndDeleteCommandTest extends MambaTest { public function testDeletingNotWritableForm() { $this->markTestIncomplete( 'This test has not been implemented yet.' ); } public function testDeletingNotExistingForm() { $this->setCommand(new FormDeleteCommand($this->app)); $commandTester = new CommandTester($this->command); /** @var QuestionHelper $helper */ $helper = $this->command->getHelper('question'); // Try to delete a not existing Form $helper->setInputStream($this->getInputStream('NotExistingForm')); $commandTester->execute([ ]); $output = $commandTester->getDisplay(); $this->assertContains('NotExistingForm does not exists.', $output); } public function testExecute() { // 1. Create Entity $this->setCommand(new FormCreateCommand($this->app)); $commandTester = new CommandTester($this->command); /** @var QuestionHelper $helper */ $helper = $this->command->getHelper('question'); $helper->setInputStream($this->getInputStream( "Acme\n" ."first name\n" ."0\n" ."y\n" ."email\n" ."1\n" ."y\n" ."select\n" ."2\n" ."y\n" ."number\n" ."3\n" ."y\n" ."note\n" ."4\n" ."n\n" )); $commandTester->execute([]); $output = $commandTester->getDisplay(); $this->assertContains('Form AcmeType was successfully created.', $output); // 2. Says Form exists $this->setCommand(new FormCreateCommand($this->app)); $commandTester = new CommandTester($this->command); /** @var QuestionHelper $helper */ $helper = $this->command->getHelper('question'); $helper->setInputStream($this->getInputStream( "Acme\n" ."first name\n" ."0\n" ."y\n" ."email\n" ."1\n" ."y\n" ."select\n" ."2\n" ."y\n" ."number\n" ."3\n" ."y\n" ."note\n" ."4\n" ."n\n" )); $commandTester->execute([]); $output = $commandTester->getDisplay(); $this->assertContains('File src/Type/AcmeType.php already exists.', $output); // 3. Delete Form $this->setCommand(new FormDeleteCommand($this->app)); $commandTester = new CommandTester($this->command); /** @var QuestionHelper $helper */ $helper = $this->command->getHelper('question'); $helper->setInputStream($this->getInputStream('AcmeType')); $commandTester->execute([]); $output = $commandTester->getDisplay(); $this->assertContains('Form AcmeType was successfully deleted.', $output); } }
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/monitoringofficer/viewmodel/MonitoringOfficerDashboardDocumentSectionViewModel.java
1231
package org.innovateuk.ifs.project.monitoringofficer.viewmodel; /** * Monitoring officer dashboard view model for Documents section */ public class MonitoringOfficerDashboardDocumentSectionViewModel { private final String documentSectionStatus; private final boolean hasDocumentSection; private final long projectId; private final boolean hasDocumentForReview; public MonitoringOfficerDashboardDocumentSectionViewModel(String documentSectionStatus, boolean hasDocumentSection, long projectId, boolean hasDocumentForReview) { this.documentSectionStatus = documentSectionStatus; this.hasDocumentSection = hasDocumentSection; this.projectId = projectId; this.hasDocumentForReview = hasDocumentForReview; } public String getDocumentSectionStatus() { return documentSectionStatus; } public boolean isHasDocumentSection() { return hasDocumentSection; } public long getProjectId() { return projectId; } public boolean isHasDocumentForReview() { return hasDocumentForReview; } public String getDocumentLinkUrl() { return String.format("/project-setup/project/%s/document/all", projectId); } }
mit
selvasingh/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/fluent/models/RedisLinkedServerWithPropertiesInner.java
4002
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.redis.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.management.ProxyResource; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.redis.models.ReplicationRole; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Response to put/get linked server (with properties) for Redis cache. */ @JsonFlatten @Fluent public class RedisLinkedServerWithPropertiesInner extends ProxyResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(RedisLinkedServerWithPropertiesInner.class); /* * Fully qualified resourceId of the linked redis cache. */ @JsonProperty(value = "properties.linkedRedisCacheId") private String linkedRedisCacheId; /* * Location of the linked redis cache. */ @JsonProperty(value = "properties.linkedRedisCacheLocation") private String linkedRedisCacheLocation; /* * Role of the linked server. */ @JsonProperty(value = "properties.serverRole") private ReplicationRole serverRole; /* * Terminal state of the link between primary and secondary redis cache. */ @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) private String provisioningState; /** * Get the linkedRedisCacheId property: Fully qualified resourceId of the linked redis cache. * * @return the linkedRedisCacheId value. */ public String linkedRedisCacheId() { return this.linkedRedisCacheId; } /** * Set the linkedRedisCacheId property: Fully qualified resourceId of the linked redis cache. * * @param linkedRedisCacheId the linkedRedisCacheId value to set. * @return the RedisLinkedServerWithPropertiesInner object itself. */ public RedisLinkedServerWithPropertiesInner withLinkedRedisCacheId(String linkedRedisCacheId) { this.linkedRedisCacheId = linkedRedisCacheId; return this; } /** * Get the linkedRedisCacheLocation property: Location of the linked redis cache. * * @return the linkedRedisCacheLocation value. */ public String linkedRedisCacheLocation() { return this.linkedRedisCacheLocation; } /** * Set the linkedRedisCacheLocation property: Location of the linked redis cache. * * @param linkedRedisCacheLocation the linkedRedisCacheLocation value to set. * @return the RedisLinkedServerWithPropertiesInner object itself. */ public RedisLinkedServerWithPropertiesInner withLinkedRedisCacheLocation(String linkedRedisCacheLocation) { this.linkedRedisCacheLocation = linkedRedisCacheLocation; return this; } /** * Get the serverRole property: Role of the linked server. * * @return the serverRole value. */ public ReplicationRole serverRole() { return this.serverRole; } /** * Set the serverRole property: Role of the linked server. * * @param serverRole the serverRole value to set. * @return the RedisLinkedServerWithPropertiesInner object itself. */ public RedisLinkedServerWithPropertiesInner withServerRole(ReplicationRole serverRole) { this.serverRole = serverRole; return this; } /** * Get the provisioningState property: Terminal state of the link between primary and secondary redis cache. * * @return the provisioningState value. */ public String provisioningState() { return this.provisioningState; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
mit
gigantlabmaster/lundbergsab.github.io
cache/twig/d0/d0a0b58e8219085b4f80c629440ce9c35a525809ba01f1e23cfa97e6d15c4fca.php
17956
<?php /* partials/base.html.twig */ class __TwigTemplate_cc43f5ef3a1230e7564d05d3ed3a58eb85ee7cde251317024c1cf9c334e2fe24 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'head' => array($this, 'block_head'), 'stylesheets' => array($this, 'block_stylesheets'), 'javascripts' => array($this, 'block_javascripts'), 'header' => array($this, 'block_header'), 'header_extra' => array($this, 'block_header_extra'), 'header_navigation' => array($this, 'block_header_navigation'), 'showcase' => array($this, 'block_showcase'), 'body' => array($this, 'block_body'), 'content' => array($this, 'block_content'), 'footer' => array($this, 'block_footer'), 'bottom' => array($this, 'block_bottom'), ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 $context["theme_config"] = $this->getAttribute($this->getAttribute((isset($context["config"]) ? $context["config"] : null), "themes", array()), $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["config"]) ? $context["config"] : null), "system", array()), "pages", array()), "theme", array())); // line 2 echo "<!DOCTYPE html> <html lang=\""; // line 3 echo (($this->getAttribute($this->getAttribute((isset($context["grav"]) ? $context["grav"] : null), "language", array()), "getLanguage", array())) ? ($this->getAttribute($this->getAttribute((isset($context["grav"]) ? $context["grav"] : null), "language", array()), "getLanguage", array())) : ("en")); echo "\"> <head> "; // line 5 $this->displayBlock('head', $context, $blocks); // line 40 echo "</head> <body id=\"top\" class=\""; // line 41 echo $this->getAttribute($this->getAttribute((isset($context["page"]) ? $context["page"] : null), "header", array()), "body_classes", array()); echo "\"> <div id=\"sb-site\"> "; // line 43 $this->displayBlock('header', $context, $blocks); // line 60 echo " "; // line 61 $this->displayBlock('showcase', $context, $blocks); // line 62 echo " "; // line 63 $this->displayBlock('body', $context, $blocks); // line 68 echo " "; // line 69 $this->displayBlock('footer', $context, $blocks); // line 77 echo " </div> <div class=\"sb-slidebar sb-left sb-width-thin\"> <div id=\"panel\"> "; // line 80 $this->loadTemplate("partials/navigation.html.twig", "partials/base.html.twig", 80)->display($context); // line 81 echo " </div> </div> "; // line 83 $this->displayBlock('bottom', $context, $blocks); // line 96 echo "</body> </html> "; } // line 5 public function block_head($context, array $blocks = array()) { // line 6 echo " <meta charset=\"utf-8\" /> <title>"; // line 7 if ($this->getAttribute((isset($context["header"]) ? $context["header"] : null), "title", array())) { echo twig_escape_filter($this->env, $this->getAttribute((isset($context["header"]) ? $context["header"] : null), "title", array()), "html"); echo " | "; } echo twig_escape_filter($this->env, $this->getAttribute((isset($context["site"]) ? $context["site"] : null), "title", array()), "html"); echo "</title> "; // line 8 $this->loadTemplate("partials/metadata.html.twig", "partials/base.html.twig", 8)->display($context); // line 9 echo " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"> <link rel=\"icon\" type=\"image/png\" href=\""; // line 10 echo $this->env->getExtension('Grav\Common\Twig\TwigExtension')->urlFunc("theme://images/favicon.png"); echo "\" /> <link rel=\"canonical\" href=\""; // line 11 echo $this->getAttribute((isset($context["page"]) ? $context["page"] : null), "url", array(0 => true, 1 => true), "method"); echo "\" /> "; // line 13 $this->displayBlock('stylesheets', $context, $blocks); // line 29 echo " "; echo $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "css", array(), "method"); echo " "; // line 31 $this->displayBlock('javascripts', $context, $blocks); // line 37 echo " "; echo $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "js", array(), "method"); echo " "; } // line 13 public function block_stylesheets($context, array $blocks = array()) { // line 14 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css/pure-0.5.0/grids-min.css", 1 => 103), "method"); // line 15 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css-compiled/nucleus.css", 1 => 102), "method"); // line 16 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css-compiled/template.css", 1 => 101), "method"); // line 17 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css/custom.css", 1 => 100), "method"); // line 18 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css/font-awesome.min.css", 1 => 100), "method"); // line 19 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css/slidebars.min.css"), "method"); // line 20 echo " "; // line 21 if ((($this->getAttribute((isset($context["browser"]) ? $context["browser"] : null), "getBrowser", array()) == "msie") && ($this->getAttribute((isset($context["browser"]) ? $context["browser"] : null), "getVersion", array()) == 10))) { // line 22 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css/nucleus-ie10.css"), "method"); // line 23 echo " "; } // line 24 echo " "; if (((($this->getAttribute((isset($context["browser"]) ? $context["browser"] : null), "getBrowser", array()) == "msie") && ($this->getAttribute((isset($context["browser"]) ? $context["browser"] : null), "getVersion", array()) >= 8)) && ($this->getAttribute((isset($context["browser"]) ? $context["browser"] : null), "getVersion", array()) <= 9))) { // line 25 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addCss", array(0 => "theme://css/nucleus-ie9.css"), "method"); // line 26 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addJs", array(0 => "theme://js/html5shiv-printshiv.min.js"), "method"); // line 27 echo " "; } // line 28 echo " "; } // line 31 public function block_javascripts($context, array $blocks = array()) { // line 32 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addJs", array(0 => "jquery", 1 => 101), "method"); // line 33 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addJs", array(0 => "theme://js/modernizr.custom.71422.js", 1 => 100), "method"); // line 34 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addJs", array(0 => "theme://js/antimatter.js"), "method"); // line 35 echo " "; $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "addJs", array(0 => "theme://js/slidebars.min.js"), "method"); // line 36 echo " "; } // line 43 public function block_header($context, array $blocks = array()) { // line 44 echo " <header id=\"header\"> <div id=\"logo\"> <h3><a href=\""; // line 46 echo ((((isset($context["base_url"]) ? $context["base_url"] : null) == "")) ? ("/") : ((isset($context["base_url"]) ? $context["base_url"] : null))); echo "\">"; echo $this->getAttribute($this->getAttribute((isset($context["config"]) ? $context["config"] : null), "site", array()), "title", array()); echo "</a></h3> </div> <div id=\"navbar\"> "; // line 49 $this->displayBlock('header_extra', $context, $blocks); // line 50 echo " "; if ($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["config"]) ? $context["config"] : null), "plugins", array()), "langswitcher", array()), "enabled", array())) { // line 51 echo " "; $this->loadTemplate("partials/langswitcher.html.twig", "partials/base.html.twig", 51)->display($context); // line 52 echo " "; } // line 53 echo " "; $this->displayBlock('header_navigation', $context, $blocks); // line 56 echo " <span class=\"panel-activation sb-toggle-left navbar-left menu-btn fa fa-bars\"></span> </div> </header> "; } // line 49 public function block_header_extra($context, array $blocks = array()) { } // line 53 public function block_header_navigation($context, array $blocks = array()) { // line 54 echo " "; $this->loadTemplate("partials/navigation.html.twig", "partials/base.html.twig", 54)->display($context); // line 55 echo " "; } // line 61 public function block_showcase($context, array $blocks = array()) { } // line 63 public function block_body($context, array $blocks = array()) { // line 64 echo " <section id=\"body\" class=\""; echo (isset($context["class"]) ? $context["class"] : null); echo "\"> "; // line 65 $this->displayBlock('content', $context, $blocks); // line 66 echo " </section> "; } // line 65 public function block_content($context, array $blocks = array()) { } // line 69 public function block_footer($context, array $blocks = array()) { // line 70 echo " <footer id=\"footer\"> <div class=\"totop\"> <span><a href=\"#\" id=\"toTop\"><i class=\"fa fa-arrow-up\"></i></a></span> </div> <p><a href=\"http://getgrav.org\">Grav</a> was <i class=\"fa fa-code\"></i> with <i class=\"fa fa-heart\"></i> by <a href=\"http://www.rockettheme.com\">RocketTheme</a>.</p> </footer> "; } // line 83 public function block_bottom($context, array $blocks = array()) { // line 84 echo " "; echo $this->getAttribute((isset($context["assets"]) ? $context["assets"] : null), "js", array(0 => "bottom"), "method"); echo " <script> \$(function () { \$(document).ready(function() { \$.slidebars({ hideControlClasses: true, scrollLock: true }); }); }); </script> "; } public function getTemplateName() { return "partials/base.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 291 => 84, 288 => 83, 278 => 70, 275 => 69, 270 => 65, 265 => 66, 263 => 65, 258 => 64, 255 => 63, 250 => 61, 246 => 55, 243 => 54, 240 => 53, 235 => 49, 228 => 56, 225 => 53, 222 => 52, 219 => 51, 216 => 50, 214 => 49, 206 => 46, 202 => 44, 199 => 43, 195 => 36, 192 => 35, 189 => 34, 186 => 33, 183 => 32, 180 => 31, 176 => 28, 173 => 27, 170 => 26, 167 => 25, 164 => 24, 161 => 23, 158 => 22, 156 => 21, 153 => 20, 150 => 19, 147 => 18, 144 => 17, 141 => 16, 138 => 15, 135 => 14, 132 => 13, 124 => 37, 122 => 31, 116 => 29, 114 => 13, 109 => 11, 105 => 10, 102 => 9, 100 => 8, 92 => 7, 89 => 6, 86 => 5, 80 => 96, 78 => 83, 74 => 81, 72 => 80, 67 => 77, 65 => 69, 62 => 68, 60 => 63, 57 => 62, 55 => 61, 52 => 60, 50 => 43, 45 => 41, 42 => 40, 40 => 5, 35 => 3, 32 => 2, 30 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("{% set theme_config = attribute(config.themes, config.system.pages.theme) %} <!DOCTYPE html> <html lang=\"{{ grav.language.getLanguage ?: 'en' }}\"> <head> {% block head %} <meta charset=\"utf-8\" /> <title>{% if header.title %}{{ header.title|e('html') }} | {% endif %}{{ site.title|e('html') }}</title> {% include 'partials/metadata.html.twig' %} <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"> <link rel=\"icon\" type=\"image/png\" href=\"{{ url('theme://images/favicon.png') }}\" /> <link rel=\"canonical\" href=\"{{ page.url(true, true) }}\" /> {% block stylesheets %} {% do assets.addCss('theme://css/pure-0.5.0/grids-min.css', 103) %} {% do assets.addCss('theme://css-compiled/nucleus.css', 102) %} {% do assets.addCss('theme://css-compiled/template.css', 101) %} {% do assets.addCss('theme://css/custom.css', 100) %} {% do assets.addCss('theme://css/font-awesome.min.css', 100) %} {% do assets.addCss('theme://css/slidebars.min.css') %} {% if browser.getBrowser == 'msie' and browser.getVersion == 10 %} {% do assets.addCss('theme://css/nucleus-ie10.css') %} {% endif %} {% if browser.getBrowser == 'msie' and browser.getVersion >= 8 and browser.getVersion <= 9 %} {% do assets.addCss('theme://css/nucleus-ie9.css') %} {% do assets.addJs('theme://js/html5shiv-printshiv.min.js') %} {% endif %} {% endblock %} {{ assets.css() }} {% block javascripts %} {% do assets.addJs('jquery', 101) %} {% do assets.addJs('theme://js/modernizr.custom.71422.js', 100) %} {% do assets.addJs('theme://js/antimatter.js') %} {% do assets.addJs('theme://js/slidebars.min.js') %} {% endblock %} {{ assets.js() }} {% endblock head %} </head> <body id=\"top\" class=\"{{ page.header.body_classes }}\"> <div id=\"sb-site\"> {% block header %} <header id=\"header\"> <div id=\"logo\"> <h3><a href=\"{{ base_url == '' ? '/' : base_url }}\">{{ config.site.title }}</a></h3> </div> <div id=\"navbar\"> {% block header_extra %}{% endblock %} {% if config.plugins.langswitcher.enabled %} {% include 'partials/langswitcher.html.twig' %} {% endif %} {% block header_navigation %} {% include 'partials/navigation.html.twig' %} {% endblock %} <span class=\"panel-activation sb-toggle-left navbar-left menu-btn fa fa-bars\"></span> </div> </header> {% endblock %} {% block showcase %}{% endblock %} {% block body %} <section id=\"body\" class=\"{{ class }}\"> {% block content %}{% endblock %} </section> {% endblock %} {% block footer %} <footer id=\"footer\"> <div class=\"totop\"> <span><a href=\"#\" id=\"toTop\"><i class=\"fa fa-arrow-up\"></i></a></span> </div> <p><a href=\"http://getgrav.org\">Grav</a> was <i class=\"fa fa-code\"></i> with <i class=\"fa fa-heart\"></i> by <a href=\"http://www.rockettheme.com\">RocketTheme</a>.</p> </footer> {% endblock %} </div> <div class=\"sb-slidebar sb-left sb-width-thin\"> <div id=\"panel\"> {% include 'partials/navigation.html.twig' %} </div> </div> {% block bottom %} {{ assets.js('bottom') }} <script> \$(function () { \$(document).ready(function() { \$.slidebars({ hideControlClasses: true, scrollLock: true }); }); }); </script> {% endblock %} </body> </html> ", "partials/base.html.twig", "/Users/emilkarlsson/Code/lundbergsab/user/themes/antimatter/templates/partials/base.html.twig"); } }
mit
getcha22/react-blog
webpack.config.js
1600
const { resolve } = require('path'); const webpack = require('webpack'); module.exports = { entry: [ 'react-hot-loader/patch', // activate HMR for React 'webpack-dev-server/client?http://localhost:8080', // bundle the client for webpack-dev-server // and connect to the provided endpoint 'webpack/hot/only-dev-server', // bundle the client for hot reloading // only- means to only hot reload for successful updates './src/app.js' // the entry point of our app ], output: { filename: 'bundle.js', // the output bundle path: resolve(__dirname, 'dist'), publicPath: '/js/' // necessary for HMR to know where to load the hot update chunks }, devtool: 'inline-source-map', devServer: { hot: false, // enable HMR on the server contentBase: resolve(__dirname, 'dist'), // match the output path publicPath: '/js/' // match the output `publicPath` }, module: { rules: [ { test: /\.js$/, use: [ 'babel-loader', ], exclude: /node_modules/ }, { test: /\.css$/, use: [ 'style-loader', 'css-loader?modules', 'postcss-loader', ], }, { test: /\.(eot|svg|ttf|woff|woff2)$/, use: ['file-loader?name=public/fonts/[name].[ext]'] } ], }, plugins: [ new webpack.HotModuleReplacementPlugin(), // enable HMR globally new webpack.NamedModulesPlugin(), // prints more readable module names in the browser console on HMR updates ], };
mit
jcwmoore/athena
Athena.SQLite/src/pcache_c.cs
19325
using System; using System.Diagnostics; using System.Text; using u32 = System.UInt32; using Pgno = System.UInt32; namespace System.Data.SQLite { using sqlite3_value = Sqlite3.Mem; using sqlite3_pcache = Sqlite3.PCache1; internal partial class Sqlite3 { /* ** 2008 August 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements that page cache. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" /* ** A complete page cache is an instance of this structure. */ public class PCache { public PgHdr pDirty, pDirtyTail; /* List of dirty pages in LRU order */ public PgHdr pSynced; /* Last synced page in dirty page list */ public int _nRef; /* Number of referenced pages */ public int nMax; /* Configured cache size */ public int szPage; /* Size of every page in this cache */ public int szExtra; /* Size of extra space for each page */ public bool bPurgeable; /* True if pages are on backing store */ public dxStress xStress; //int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */ public object pStress; /* Argument to xStress */ public sqlite3_pcache pCache; /* Pluggable cache module */ public PgHdr pPage1; /* Reference to page 1 */ public int nRef /* Number of referenced pages */ { get { return _nRef; } set { _nRef = value; } } public void Clear() { pDirty = null; pDirtyTail = null; pSynced = null; nRef = 0; } }; /* ** Some of the Debug.Assert() macros in this code are too expensive to run ** even during normal debugging. Use them only rarely on long-running ** tests. Enable the expensive asserts using the ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option. */ #if SQLITE_ENABLE_EXPENSIVE_ASSERT //# define expensive_assert(X) Debug.Assert(X) static void expensive_assert( bool x ) { Debug.Assert( x ); } #else //# define expensive_assert(X) #endif /********************************** Linked List Management ********************/ #if !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT /* ** Check that the pCache.pSynced variable is set correctly. If it ** is not, either fail an Debug.Assert or return zero. Otherwise, return ** non-zero. This is only used in debugging builds, as follows: ** ** expensive_assert( pcacheCheckSynced(pCache) ); */ static int pcacheCheckSynced(PCache pCache){ PgHdr p ; for(p=pCache.pDirtyTail; p!=pCache.pSynced; p=p.pDirtyPrev){ Debug.Assert( p.nRef !=0|| (p.flags&PGHDR_NEED_SYNC) !=0); } return (p==null || p.nRef!=0 || (p.flags&PGHDR_NEED_SYNC)==0)?1:0; } #endif //* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */ /* ** Remove page pPage from the list of dirty pages. */ static void pcacheRemoveFromDirtyList(PgHdr pPage) { PCache p = pPage.pCache; Debug.Assert(pPage.pDirtyNext != null || pPage == p.pDirtyTail); Debug.Assert(pPage.pDirtyPrev != null || pPage == p.pDirty); /* Update the PCache1.pSynced variable if necessary. */ if (p.pSynced == pPage) { PgHdr pSynced = pPage.pDirtyPrev; while (pSynced != null && (pSynced.flags & PGHDR_NEED_SYNC) != 0) { pSynced = pSynced.pDirtyPrev; } p.pSynced = pSynced; } if (pPage.pDirtyNext != null) { pPage.pDirtyNext.pDirtyPrev = pPage.pDirtyPrev; } else { Debug.Assert(pPage == p.pDirtyTail); p.pDirtyTail = pPage.pDirtyPrev; } if (pPage.pDirtyPrev != null) { pPage.pDirtyPrev.pDirtyNext = pPage.pDirtyNext; } else { Debug.Assert(pPage == p.pDirty); p.pDirty = pPage.pDirtyNext; } pPage.pDirtyNext = null; pPage.pDirtyPrev = null; #if SQLITE_ENABLE_EXPENSIVE_ASSERT expensive_assert( pcacheCheckSynced(p) ); #endif } /* ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to ** pPage). */ static void pcacheAddToDirtyList(PgHdr pPage) { PCache p = pPage.pCache; Debug.Assert(pPage.pDirtyNext == null && pPage.pDirtyPrev == null && p.pDirty != pPage); pPage.pDirtyNext = p.pDirty; if (pPage.pDirtyNext != null) { Debug.Assert(pPage.pDirtyNext.pDirtyPrev == null); pPage.pDirtyNext.pDirtyPrev = pPage; } p.pDirty = pPage; if (null == p.pDirtyTail) { p.pDirtyTail = pPage; } if (null == p.pSynced && 0 == (pPage.flags & PGHDR_NEED_SYNC)) { p.pSynced = pPage; } #if SQLITE_ENABLE_EXPENSIVE_ASSERT expensive_assert( pcacheCheckSynced(p) ); #endif } /* ** Wrapper around the pluggable caches xUnpin method. If the cache is ** being used for an in-memory database, this function is a no-op. */ static void pcacheUnpin(PgHdr p) { PCache pCache = p.pCache; if (pCache.bPurgeable) { if (p.pgno == 1) { pCache.pPage1 = null; } sqlite3GlobalConfig.pcache.xUnpin(pCache.pCache, p, false); } } /*************************************************** General Interfaces ****** ** ** Initialize and shutdown the page cache subsystem. Neither of these ** functions are threadsafe. */ static int sqlite3PcacheInitialize() { if (sqlite3GlobalConfig.pcache.xInit == null) { /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache. */ sqlite3PCacheSetDefault(); } return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg); } static void sqlite3PcacheShutdown() { if (sqlite3GlobalConfig.pcache.xShutdown != null) { /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg); } } /* ** Return the size in bytes of a PCache object. */ static int sqlite3PcacheSize() { return 4; }// sizeof( PCache ); } /* ** Create a new PCache object. Storage space to hold the object ** has already been allocated and is passed in as the p pointer. ** The caller discovers how much space needs to be allocated by ** calling sqlite3PcacheSize(). */ static void sqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ bool bPurgeable, /* True if pages are on backing store */ dxStress xStress,//int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */ object pStress, /* Argument to xStress */ PCache p /* Preallocated space for the PCache */ ) { p.Clear();//memset(p, 0, sizeof(PCache)); p.szPage = szPage; p.szExtra = szExtra; p.bPurgeable = bPurgeable; p.xStress = xStress; p.pStress = pStress; p.nMax = 100; } /* ** Change the page size for PCache object. The caller must ensure that there ** are no outstanding page references when this function is called. */ static void sqlite3PcacheSetPageSize(PCache pCache, int szPage) { Debug.Assert(pCache.nRef == 0 && pCache.pDirty == null); if (pCache.pCache != null) { sqlite3GlobalConfig.pcache.xDestroy(ref pCache.pCache); pCache.pCache = null; } pCache.szPage = szPage; } /* ** Try to obtain a page from the cache. */ static int sqlite3PcacheFetch( PCache pCache, /* Obtain the page from this cache */ u32 pgno, /* Page number to obtain */ int createFlag, /* If true, create page if it does not exist already */ ref PgHdr ppPage /* Write the page here */ ) { PgHdr pPage = null; int eCreate; Debug.Assert(pCache != null); Debug.Assert(createFlag == 1 || createFlag == 0); Debug.Assert(pgno > 0); /* If the pluggable cache (sqlite3_pcache*) has not been allocated, ** allocate it now. */ if (null == pCache.pCache && createFlag != 0) { sqlite3_pcache p; int nByte; nByte = pCache.szPage + pCache.szExtra + 0;// sizeof( PgHdr ); p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache.bPurgeable); //if ( null == p ) //{ // return SQLITE_NOMEM; //} sqlite3GlobalConfig.pcache.xCachesize(p, pCache.nMax); pCache.pCache = p; } eCreate = createFlag * (1 + ((!pCache.bPurgeable || null == pCache.pDirty) ? 1 : 0)); if (pCache.pCache != null) { pPage = sqlite3GlobalConfig.pcache.xFetch(pCache.pCache, pgno, eCreate); } if (null == pPage && eCreate == 1) { PgHdr pPg; /* Find a dirty page to write-out and recycle. First try to find a ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC ** cleared), but if that is not possible settle for any other ** unreferenced dirty page. */ #if SQLITE_ENABLE_EXPENSIVE_ASSERT expensive_assert( pcacheCheckSynced(pCache) ); #endif for (pPg = pCache.pSynced; pPg != null && (pPg.nRef != 0 || (pPg.flags & PGHDR_NEED_SYNC) != 0); pPg = pPg.pDirtyPrev ) ; pCache.pSynced = pPg; if (null == pPg) { for (pPg = pCache.pDirtyTail; pPg != null && pPg.nRef != 0; pPg = pPg.pDirtyPrev) ; } if (pPg != null) { int rc; #if SQLITE_LOG_CACHE_SPILL sqlite3_log(SQLITE_FULL, "spill page %d making room for %d - cache used: %d/%d", pPg->pgno, pgno, sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache), pCache->nMax); #endif rc = pCache.xStress(pCache.pStress, pPg); if (rc != SQLITE_OK && rc != SQLITE_BUSY) { return rc; } } pPage = sqlite3GlobalConfig.pcache.xFetch(pCache.pCache, pgno, 2); } if (pPage != null) { if (null == pPage.pData) { // memset(pPage, 0, sizeof(PgHdr)); pPage.pData = sqlite3Malloc(pCache.szPage);// pPage->pData = (void*)&pPage[1]; //pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage]; //memset(pPage->pExtra, 0, pCache->szExtra); pPage.pCache = pCache; pPage.pgno = pgno; } Debug.Assert(pPage.pCache == pCache); Debug.Assert(pPage.pgno == pgno); //assert(pPage->pData == (void*)&pPage[1]); //assert(pPage->pExtra == (void*)&((char*)&pPage[1])[pCache->szPage]); if (0 == pPage.nRef) { pCache.nRef++; } pPage.nRef++; if (pgno == 1) { pCache.pPage1 = pPage; } } ppPage = pPage; return (pPage == null && eCreate != 0) ? SQLITE_NOMEM : SQLITE_OK; } /* ** Decrement the reference count on a page. If the page is clean and the ** reference count drops to 0, then it is made elible for recycling. */ static void sqlite3PcacheRelease(PgHdr p) { Debug.Assert(p.nRef > 0); p.nRef--; if (p.nRef == 0) { PCache pCache = p.pCache; pCache.nRef--; if ((p.flags & PGHDR_DIRTY) == 0) { pcacheUnpin(p); } else { /* Move the page to the head of the dirty list. */ pcacheRemoveFromDirtyList(p); pcacheAddToDirtyList(p); } } } /* ** Increase the reference count of a supplied page by 1. */ static void sqlite3PcacheRef(PgHdr p) { Debug.Assert(p.nRef > 0); p.nRef++; } /* ** Drop a page from the cache. There must be exactly one reference to the ** page. This function deletes that reference, so after it returns the ** page pointed to by p is invalid. */ static void sqlite3PcacheDrop(PgHdr p) { PCache pCache; Debug.Assert(p.nRef == 1); if ((p.flags & PGHDR_DIRTY) != 0) { pcacheRemoveFromDirtyList(p); } pCache = p.pCache; pCache.nRef--; if (p.pgno == 1) { pCache.pPage1 = null; } sqlite3GlobalConfig.pcache.xUnpin(pCache.pCache, p, true); } /* ** Make sure the page is marked as dirty. If it isn't dirty already, ** make it so. */ static void sqlite3PcacheMakeDirty(PgHdr p) { p.flags &= ~PGHDR_DONT_WRITE; Debug.Assert(p.nRef > 0); if (0 == (p.flags & PGHDR_DIRTY)) { p.flags |= PGHDR_DIRTY; pcacheAddToDirtyList(p); } } /* ** Make sure the page is marked as clean. If it isn't clean already, ** make it so. */ static void sqlite3PcacheMakeClean(PgHdr p) { if ((p.flags & PGHDR_DIRTY) != 0) { pcacheRemoveFromDirtyList(p); p.flags &= ~(PGHDR_DIRTY | PGHDR_NEED_SYNC); if (p.nRef == 0) { pcacheUnpin(p); } } } /* ** Make every page in the cache clean. */ static void sqlite3PcacheCleanAll(PCache pCache) { PgHdr p; while ((p = pCache.pDirty) != null) { sqlite3PcacheMakeClean(p); } } /* ** Clear the PGHDR_NEED_SYNC flag from all dirty pages. */ static void sqlite3PcacheClearSyncFlags(PCache pCache) { PgHdr p; for (p = pCache.pDirty; p != null; p = p.pDirtyNext) { p.flags &= ~PGHDR_NEED_SYNC; } pCache.pSynced = pCache.pDirtyTail; } /* ** Change the page number of page p to newPgno. */ static void sqlite3PcacheMove(PgHdr p, Pgno newPgno) { PCache pCache = p.pCache; Debug.Assert(p.nRef > 0); Debug.Assert(newPgno > 0); sqlite3GlobalConfig.pcache.xRekey(pCache.pCache, p, p.pgno, newPgno); p.pgno = newPgno; if ((p.flags & PGHDR_DIRTY) != 0 && (p.flags & PGHDR_NEED_SYNC) != 0) { pcacheRemoveFromDirtyList(p); pcacheAddToDirtyList(p); } } /* ** Drop every cache entry whose page number is greater than "pgno". The ** caller must ensure that there are no outstanding references to any pages ** other than page 1 with a page number greater than pgno. ** ** If there is a reference to page 1 and the pgno parameter passed to this ** function is 0, then the data area associated with page 1 is zeroed, but ** the page object is not dropped. */ static void sqlite3PcacheTruncate(PCache pCache, u32 pgno) { if (pCache.pCache != null) { PgHdr p; PgHdr pNext; for (p = pCache.pDirty; p != null; p = pNext) { pNext = p.pDirtyNext; /* This routine never gets call with a positive pgno except right ** after sqlite3PcacheCleanAll(). So if there are dirty pages, ** it must be that pgno==0. */ Debug.Assert(p.pgno > 0); if (ALWAYS(p.pgno > pgno)) { Debug.Assert((p.flags & PGHDR_DIRTY) != 0); sqlite3PcacheMakeClean(p); } } if (pgno == 0 && pCache.pPage1 != null) { // memset( pCache.pPage1.pData, 0, pCache.szPage ); pCache.pPage1.pData = sqlite3Malloc(pCache.szPage); pgno = 1; } sqlite3GlobalConfig.pcache.xTruncate(pCache.pCache, pgno + 1); } } /* ** Close a cache. */ static void sqlite3PcacheClose(PCache pCache) { if (pCache.pCache != null) { sqlite3GlobalConfig.pcache.xDestroy(ref pCache.pCache); } } /* ** Discard the contents of the cache. */ static void sqlite3PcacheClear(PCache pCache) { sqlite3PcacheTruncate(pCache, 0); } /* ** Merge two lists of pages connected by pDirty and in pgno order. ** Do not both fixing the pDirtyPrev pointers. */ static PgHdr pcacheMergeDirtyList(PgHdr pA, PgHdr pB) { PgHdr result = new PgHdr(); PgHdr pTail = result; while (pA != null && pB != null) { if (pA.pgno < pB.pgno) { pTail.pDirty = pA; pTail = pA; pA = pA.pDirty; } else { pTail.pDirty = pB; pTail = pB; pB = pB.pDirty; } } if (pA != null) { pTail.pDirty = pA; } else if (pB != null) { pTail.pDirty = pB; } else { pTail.pDirty = null; } return result.pDirty; } /* ** Sort the list of pages in accending order by pgno. Pages are ** connected by pDirty pointers. The pDirtyPrev pointers are ** corrupted by this sort. ** ** Since there cannot be more than 2^31 distinct pages in a database, ** there cannot be more than 31 buckets required by the merge sorter. ** One extra bucket is added to catch overflow in case something ** ever changes to make the previous sentence incorrect. */ //#define N_SORT_BUCKET 32 const int N_SORT_BUCKET = 32; static PgHdr pcacheSortDirtyList(PgHdr pIn) { PgHdr[] a; PgHdr p;//a[N_SORT_BUCKET], p; int i; a = new PgHdr[N_SORT_BUCKET];//memset(a, 0, sizeof(a)); while (pIn != null) { p = pIn; pIn = p.pDirty; p.pDirty = null; for (i = 0; ALWAYS(i < N_SORT_BUCKET - 1); i++) { if (a[i] == null) { a[i] = p; break; } else { p = pcacheMergeDirtyList(a[i], p); a[i] = null; } } if (NEVER(i == N_SORT_BUCKET - 1)) { /* To get here, there need to be 2^(N_SORT_BUCKET) elements in ** the input list. But that is impossible. */ a[i] = pcacheMergeDirtyList(a[i], p); } } p = a[0]; for (i = 1; i < N_SORT_BUCKET; i++) { p = pcacheMergeDirtyList(p, a[i]); } return p; } /* ** Return a list of all dirty pages in the cache, sorted by page number. */ static PgHdr sqlite3PcacheDirtyList(PCache pCache) { PgHdr p; for (p = pCache.pDirty; p != null; p = p.pDirtyNext) { p.pDirty = p.pDirtyNext; } return pcacheSortDirtyList(pCache.pDirty); } /* ** Return the total number of referenced pages held by the cache. */ static int sqlite3PcacheRefCount(PCache pCache) { return pCache.nRef; } /* ** Return the number of references to the page supplied as an argument. */ static int sqlite3PcachePageRefcount(PgHdr p) { return p.nRef; } /* ** Return the total number of pages in the cache. */ static int sqlite3PcachePagecount(PCache pCache) { int nPage = 0; if (pCache.pCache != null) { nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache.pCache); } return nPage; } #if SQLITE_TEST /* ** Get the suggested cache-size value. */ static int sqlite3PcacheGetCachesize( PCache pCache ) { return pCache.nMax; } #endif /* ** Set the suggested cache-size value. */ static void sqlite3PcacheSetCachesize(PCache pCache, int mxPage) { pCache.nMax = mxPage; if (pCache.pCache != null) { sqlite3GlobalConfig.pcache.xCachesize(pCache.pCache, mxPage); } } #if SQLITE_CHECK_PAGES || (SQLITE_DEBUG) /* ** For all dirty pages currently in the cache, invoke the specified ** callback. This is only used if the SQLITE_CHECK_PAGES macro is ** defined. */ static void sqlite3PcacheIterateDirty( PCache pCache, dxIter xIter ) { PgHdr pDirty; for ( pDirty = pCache.pDirty; pDirty != null; pDirty = pDirty.pDirtyNext ) { xIter( pDirty ); } } #endif } }
mit
karthiick/ember.js
packages/ember-runtime/lib/system/namespace.js
5161
/** @module ember */ import { guidFor } from 'ember-utils'; import Ember, { get, Mixin, hasUnprocessedMixins, clearUnprocessedMixins, } from 'ember-metal'; // Preloaded into namespaces import { context } from 'ember-environment'; import { NAME_KEY } from 'ember-utils'; import EmberObject from './object'; let searchDisabled = false; export function isSearchDisabled() { return searchDisabled; } export function setSearchDisabled(flag) { searchDisabled = !!flag; } /** A Namespace is an object usually used to contain other objects or methods such as an application or framework. Create a namespace anytime you want to define one of these new containers. # Example Usage ```javascript MyFramework = Ember.Namespace.create({ VERSION: '1.0.0' }); ``` @class Namespace @namespace Ember @extends EmberObject @public */ const Namespace = EmberObject.extend({ isNamespace: true, init() { Namespace.NAMESPACES.push(this); Namespace.PROCESSED = false; }, toString() { let name = get(this, 'name') || get(this, 'modulePrefix'); if (name) { return name; } findNamespaces(); return this[NAME_KEY]; }, nameClasses() { processNamespace([this.toString()], this, {}); }, destroy() { let namespaces = Namespace.NAMESPACES; let toString = this.toString(); if (toString) { context.lookup[toString] = undefined; delete Namespace.NAMESPACES_BY_ID[toString]; } namespaces.splice(namespaces.indexOf(this), 1); this._super(...arguments); } }); Namespace.reopenClass({ NAMESPACES: [Ember], NAMESPACES_BY_ID: { Ember }, PROCESSED: false, processAll: processAllNamespaces, byName(name) { if (!searchDisabled) { processAllNamespaces(); } return NAMESPACES_BY_ID[name]; } }); let NAMESPACES_BY_ID = Namespace.NAMESPACES_BY_ID; let hasOwnProp = ({}).hasOwnProperty; function processNamespace(paths, root, seen) { let idx = paths.length; NAMESPACES_BY_ID[paths.join('.')] = root; // Loop over all of the keys in the namespace, looking for classes for (let key in root) { if (!hasOwnProp.call(root, key)) { continue; } let obj = root[key]; // If we are processing the `Ember` namespace, for example, the // `paths` will start with `["Ember"]`. Every iteration through // the loop will update the **second** element of this list with // the key, so processing `Ember.View` will make the Array // `['Ember', 'View']`. paths[idx] = key; // If we have found an unprocessed class if (obj && obj.toString === classToString && !obj[NAME_KEY]) { // Replace the class' `toString` with the dot-separated path // and set its `NAME_KEY` obj[NAME_KEY] = paths.join('.'); // Support nested namespaces } else if (obj && obj.isNamespace) { // Skip aliased namespaces if (seen[guidFor(obj)]) { continue; } seen[guidFor(obj)] = true; // Process the child namespace processNamespace(paths, obj, seen); } } paths.length = idx; // cut out last item } function isUppercase(code) { return code >= 65 && // A code <= 90; // Z } function tryIsNamespace(lookup, prop) { try { let obj = lookup[prop]; return obj && obj.isNamespace && obj; } catch (e) { // continue } } function findNamespaces() { if (Namespace.PROCESSED) { return; } let lookup = context.lookup; let keys = Object.keys(lookup); for (let i = 0; i < keys.length; i++) { let key = keys[i]; // Only process entities that start with uppercase A-Z if (!isUppercase(key.charCodeAt(0))) { continue; } let obj = tryIsNamespace(lookup, key); if (obj) { obj[NAME_KEY] = key; } } } function superClassString(mixin) { let superclass = mixin.superclass; if (superclass) { if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; } return superClassString(superclass); } } function calculateToString(target) { let str; if (!searchDisabled) { processAllNamespaces(); // can also be set by processAllNamespaces str = target[NAME_KEY]; if (str) { return str; } else { str = superClassString(target); str = str ? `(subclass of ${str})` : str; } } if (str) { return str; } else { return '(unknown mixin)'; } } function classToString() { let name = this[NAME_KEY]; if (name) { return name; } return (this[NAME_KEY] = calculateToString(this)); } function processAllNamespaces() { let unprocessedNamespaces = !Namespace.PROCESSED; let unprocessedMixins = hasUnprocessedMixins(); if (unprocessedNamespaces) { findNamespaces(); Namespace.PROCESSED = true; } if (unprocessedNamespaces || unprocessedMixins) { let namespaces = Namespace.NAMESPACES; let namespace; for (let i = 0; i < namespaces.length; i++) { namespace = namespaces[i]; processNamespace([namespace.toString()], namespace, {}); } clearUnprocessedMixins(); } } Mixin.prototype.toString = classToString; // ES6TODO: altering imported objects. SBB. export default Namespace;
mit
dhingratul/Deep-Learning
2_LR_GD.py
4431
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 7 09:58:16 2017 @author: dhingratul """ from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range def unPickle(pickle_file): """ Unpickles the data file into tr, te, and validation data """ with open(pickle_file, 'rb') as f: datasets = pickle.load(f) test_dataset = datasets['test_dataset'] test_labels = datasets['test_labels'] train_dataset = datasets['train_dataset'] train_labels = datasets['train_labels'] valid_dataset = datasets['valid_dataset'] valid_labels = datasets['valid_labels'] return test_dataset, test_labels, train_dataset, train_labels,\ valid_dataset, valid_labels pickle_file = "/home/dhingratul/Documents/Dataset/notMNIST.pickle" test_dataset, test_labels, train_dataset, train_labels, valid_dataset,\ valid_labels = unPickle(pickle_file) """ Reformat data as per the requirements of the program, data as a flat matrix, and label as one hot encoded vector """ image_size = 28 num_labels = 10 def reformat(data, labels): """ Converts the data into a flat matrix, and labels into one-hot encoding """ data = data.reshape((-1, image_size * image_size)).astype(np.float32) # -1:size being inferred from the parameters being passed labels = (np.arange(num_labels) == labels[:, None]).astype(np.float32) return data, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) # Training with tf batch_size = 5000 graph = tf.Graph() with graph.as_default(): # Data is treated as tf.constant in the tensorflow graph tf_train_data = tf.constant(train_dataset[:batch_size, :]) tf_train_labels = tf.constant(train_labels[:batch_size]) tf_valid_data = tf.constant(valid_dataset) tf_test_data = tf.constant(test_dataset) # Variables are the parameters that are trained: Weights and Biases # Initialize weights to random values, using truncated normal distribution weights = tf.Variable( tf.truncated_normal([image_size * image_size, num_labels])) biases = tf.Variable(tf.zeros([num_labels])) # Training computation logits = tf.matmul(tf_train_data, weights) + biases # Softmax loss loss_intermediate = tf.nn.softmax_cross_entropy_with_logits( labels=tf_train_labels, logits=logits) # Take mean over the loss avg_loss = tf.reduce_mean(loss_intermediate) # Gradient Descent Optimizer lr = 0.5 # Learning rate optimizer = tf.train.GradientDescentOptimizer(lr).minimize(avg_loss) # Predictions train_pred = tf.nn.softmax(logits) valid_logits = tf.matmul(tf_valid_data, weights) + biases valid_pred = tf.nn.softmax(valid_logits) test_logits = tf.matmul(tf_test_data, weights) + biases test_pred = tf.nn.softmax(test_logits) step_size = 500 def accuracy(predictions, labels): """ Outputs the accuracy based on gnd truth and predicted labels""" return (100 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / labels.shape[0]) # Initialize the graph defined above with tf.Session(graph=graph) as session: # Initialize weights tf.global_variables_initializer().run() for step in range(step_size): # Run the computations. We tell .run() that we want to run the # optimizer,and get the loss value and the training predictions # returned as numpy arrays. _, l, pred = session.run([optimizer, avg_loss, train_pred]) if step % 100 == 0: print("Loss at step %d: %f" % (step, l)) print("Training Accuracy: %0.1f%%" % accuracy(pred, train_labels[:batch_size, :])) # Calling .eval() on valid_prediction is basically like calling # run(), but just to get that one numpy array Note that it # recomputes all its graph dependencies. print('Validation accuracy: %.1f%%' % accuracy(valid_pred.eval(), valid_labels)) print('Test accuracy: %.1f%%' % accuracy(test_pred.eval(), test_labels))
mit
bearsunday/BEAR.Resource
tests/Fake/UnboundInterface.php
129
<?php declare(strict_types=1); namespace BEAR\Resource; /** * No implementation interface */ interface UnboundInterface { }
mit
toopy/django-toopy-website
src/toopy/forms.py
333
import floppyforms as forms from toopy.models import Contact class FormContact(forms.ModelForm): class Meta: model = Contact widgets = { 'email' : forms.EmailInput, 'subject': forms.TextInput, 'message': forms.Textarea, 'website': forms.URLInput, }
mit
dnjuguna/wepesi
lib/utilities/storage.js
920
"use strict"; var mongodb = require('mongodb'); var self = { store : {} }; module.exports = { set : function(){ self.store[arguments[0]] = arguments[1]; }, get : function(){ var key = arguments[0]; return self.store[key] ? self.store[key] : null; }, connect: function(settings, then){ var config = "mongodb://" + settings.servers + "/" + settings.name + "?w=2&readPreference=secondary"; mongodb.MongoClient.connect(config, function(error, db){ then(error, db); }); }, db : function(settings){ var server = new mongodb.Server(settings.host, settings.port, settings.server_options); return new mongodb.Db(settings.name, server, settings.db_options); }, uuid: function(){ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);}); }, timestamp: function(){ return (new Date()).getTime(); } };
mit
SuperPaintman/susanin
gulp/tasks/server.js.js
1254
'use strict'; /** Requires */ const path = require('path'); // Main const gulp = require('gulp'); const $ = require('gulp-load-plugins')(); // Config const config = require('../config.js'); const helps = require('../helps.js'); /** Constants */ const TASK_NAME = 'server:js'; const WATCH_TASK_NAME = `watch:${TASK_NAME}`; module.exports.TASK_NAME = TASK_NAME; module.exports.WATCH_TASK_NAME = WATCH_TASK_NAME; /** Task */ gulp.task(TASK_NAME, () => { return gulp.src(config.paths.server.js.from) // Error handler .pipe($.plumber({ errorHandler: helps.onError })) // Catch .pipe($.cached(TASK_NAME)) // Source map .pipe($.sourcemaps.init()) // Babel render .pipe($.babel(config.babel.server)) //End source map .pipe($.sourcemaps.write()) // Сохранение .pipe(gulp.dest(config.paths.server.js.to)) ; }); /** Watch */ gulp.task(WATCH_TASK_NAME, () => { return gulp.watch(config.paths.server.js.watch, [TASK_NAME]) .on('unlink', (filepath) => { const resolvedFilepath = path.resolve(filepath); if ($.cached.caches[TASK_NAME]) { delete $.cached.caches[TASK_NAME][resolvedFilepath]; } }); });
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.2.0/editor/selection-debug.js
130
version https://git-lfs.github.com/spec/v1 oid sha256:c65926f7c31b0d3c93de8ea950b714a69eeb0de2e594cb457fddac7e86cadb97 size 31108
mit
sakapon/Tools-2015
VisionPlate/VisionPlate/MainWindow.xaml.cs
783
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace VisionPlate { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MouseLeftButtonDown += (o, e) => DragMove(); MouseRightButtonUp += (o, e) => Close(); } } }
mit
trinhtran060392/angular-2
app/graph/graph.footer.component.ts
167
import { Component } from '@angular/core'; @Component({ selector: 'my-footer', templateUrl: 'app/graph/graph.footer.html' }) export class GraphFooterComponent { }
mit
wppurking/hutch-schedule
spec/hutch/patch/config_spec.rb
893
require "spec_helper" RSpec.describe Hutch::Config do it '#worker_pool_size' do expect(subject.get(:worker_pool_size)).to eq(20) expect(subject.is_num(:worker_pool_size)).to be_truthy end it '#poller_interval' do expect(subject.get(:poller_interval)).to eq(1) expect(subject.is_num(:poller_interval)).to be_truthy end it '#poller_batch_size' do expect(subject.get(:poller_batch_size)).to eq(100) expect(subject.is_num(:poller_batch_size)).to be_truthy end it '#ratelimit_redis_url' do expect(subject.get(:redis_url)).to eq("redis://127.0.0.1:6379/0") expect(subject.is_bool(:redis_url)).to be_falsey expect(subject.is_num(:redis_url)).to be_falsey end it '#ratelimit_bucket_interval' do expect(subject.get(:ratelimit_bucket_interval)).to eq(1) expect(subject.is_num(:ratelimit_bucket_interval)).to be_truthy end end
mit
marcelmoosbrugger/genetic-sudoku-solver
src/io/GridReader.java
3453
/* * This file is part of the genetic-sudoku-solver. * * (c) Marcel Moosbrugger * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ package io; import sudoku.SudokuGrid; import java.util.Scanner; /** * Class reads and returns a sudoku-grid */ public final class GridReader { /** * Reads and returns a sudoku-grid form the standard-input * @return a sudoku-grid */ public static SudokuGrid read() { try { Scanner scanner = new Scanner(System.in); GridWriter.printLabel("Size of a block ('3' for standard sudoku)"); int blockSize = GridReader.readBlockSize(scanner); SudokuGrid grid = new SudokuGrid(blockSize); GridWriter.printBiglabel("Sudoku ('0' for empty fields)"); GridReader.fillGrid(grid, scanner); return grid; } catch (InvalidInputException exception) { System.out.println("Error: " + exception.getMessage()); return null; } } /** * @return the blocksize for the sudoku-grid * @param scanner The scanner to read from * @throws InvalidInputException */ public static int readBlockSize(Scanner scanner) throws InvalidInputException { if (!scanner.hasNextLine() || !scanner.hasNextInt()) { throw new InvalidInputException("Please define a block-size (normal sudokus have '3')."); } int blockSize = scanner.nextInt(); scanner.nextLine(); return blockSize; } /** * Fills a passed grid with numbers from the standard-input * @param grid the grid to fill with numbers * @param scanner The scanner to read from * @throws InvalidInputException */ public static void fillGrid(SudokuGrid grid, Scanner scanner) throws InvalidInputException { int line = 0; while (scanner.hasNextLine()) { if (line >= grid.getSideLength()) { throw new InvalidInputException("Too many rows passed."); } GridReader.fillGridRow(grid, line, scanner.nextLine()); line += 1; } if (line < grid.getSideLength()) { throw new InvalidInputException("Too less rows passed."); } } /** * Fills a given row with a given index of a given grid with numbers * @param grid the grid to fill with numbers * @param rowIndex the index of the row which should be filled in the grid * @param row the row of numbers encoded as a string to fill into the grid * @throws InvalidInputException */ public static void fillGridRow(SudokuGrid grid, int rowIndex, String row) throws InvalidInputException { if (!row.contains(" ")) { row = row.replaceAll(".(?!$)", "$0 ").trim(); //space after each character } Scanner scanner = new Scanner(row); int numberIndex = 0; while (scanner.hasNextInt()) { if (numberIndex >= grid.getSideLength()) { throw new InvalidInputException("Too many numbers passed in row '" + rowIndex + "'."); } grid.write(numberIndex, rowIndex, scanner.nextInt()); numberIndex += 1; } if (numberIndex < grid.getSideLength()) { throw new InvalidInputException("Too less numbers passed in row '" + rowIndex + "'."); } } }
mit
jmgq/php-a-star
tests/Example/Graph/LinkTest.php
2132
<?php namespace JMGQ\AStar\Tests\Example\Graph; use JMGQ\AStar\Example\Graph\Coordinate; use JMGQ\AStar\Example\Graph\Link; use PHPUnit\Framework\TestCase; class LinkTest extends TestCase { /** * @return mixed[][] */ public function validDistanceProvider(): array { return [ [0], [3], ['7'], [99999999], [7.5], ['12.345'], ]; } /** * @return mixed[][] */ public function invalidDistanceProvider(): array { return [ [-1, \InvalidArgumentException::class, 'Invalid distance'], [-0.5, \InvalidArgumentException::class, 'Invalid distance'], [null, \TypeError::class, 'must be of type float'], ['a', \TypeError::class, 'must be of type float'], [[], \TypeError::class, 'must be of type float'], ]; } /** * @dataProvider validDistanceProvider */ public function testShouldSetValidDistance(mixed $distance): void { $expectedDistance = (float) $distance; $source = $this->createStub(Coordinate::class); $destination = $this->createStub(Coordinate::class); $sut = new Link($source, $destination, $distance); $this->assertSame($source, $sut->getSource()); $this->assertSame($destination, $sut->getDestination()); $this->assertSame($expectedDistance, $sut->getDistance()); } /** * @dataProvider invalidDistanceProvider * @param mixed $distance * @param class-string<\Throwable> $expectedException * @param string $expectedExceptionMessage */ public function testShouldNotSetInvalidDistance( mixed $distance, string $expectedException, string $expectedExceptionMessage ): void { $source = $this->createStub(Coordinate::class); $destination = $this->createStub(Coordinate::class); $this->expectException($expectedException); $this->expectExceptionMessage($expectedExceptionMessage); new Link($source, $destination, $distance); } }
mit
Azure/azure-sdk-for-net
sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/Models/ManagedDiskParameters.cs
3330
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Compute.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// The parameters of a managed disk. /// </summary> public partial class ManagedDiskParameters : SubResource { /// <summary> /// Initializes a new instance of the ManagedDiskParameters class. /// </summary> public ManagedDiskParameters() { CustomInit(); } /// <summary> /// Initializes a new instance of the ManagedDiskParameters class. /// </summary> /// <param name="id">Resource Id</param> /// <param name="storageAccountType">Specifies the storage account type /// for the managed disk. NOTE: UltraSSD_LRS can only be used with data /// disks, it cannot be used with OS Disk. Possible values include: /// 'Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS', /// 'Premium_ZRS', 'StandardSSD_ZRS'</param> /// <param name="diskEncryptionSet">Specifies the customer managed disk /// encryption set resource id for the managed disk.</param> /// <param name="securityProfile">Specifies the security profile for /// the managed disk.</param> public ManagedDiskParameters(string id = default(string), string storageAccountType = default(string), DiskEncryptionSetParameters diskEncryptionSet = default(DiskEncryptionSetParameters), VMDiskSecurityProfile securityProfile = default(VMDiskSecurityProfile)) : base(id) { StorageAccountType = storageAccountType; DiskEncryptionSet = diskEncryptionSet; SecurityProfile = securityProfile; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets specifies the storage account type for the managed /// disk. NOTE: UltraSSD_LRS can only be used with data disks, it /// cannot be used with OS Disk. Possible values include: /// 'Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS', /// 'Premium_ZRS', 'StandardSSD_ZRS' /// </summary> [JsonProperty(PropertyName = "storageAccountType")] public string StorageAccountType { get; set; } /// <summary> /// Gets or sets specifies the customer managed disk encryption set /// resource id for the managed disk. /// </summary> [JsonProperty(PropertyName = "diskEncryptionSet")] public DiskEncryptionSetParameters DiskEncryptionSet { get; set; } /// <summary> /// Gets or sets specifies the security profile for the managed disk. /// </summary> [JsonProperty(PropertyName = "securityProfile")] public VMDiskSecurityProfile SecurityProfile { get; set; } } }
mit
ritz078/ultron
Gruntfile.js
10289
/*jshint node:true*/ // Generated on 2015-10-16 using // generator-webapp-watchify 0.5.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // If you want to recursively match all subfolders, use: // 'test/spec/**/*.js' module.exports = function (grunt) { // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Configurable paths var config = { app: 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings config: config, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, // js: { // files: ['<%= config.app %>/scripts/{,*/}*.js'], // tasks: ['jshint'], // options: { // livereload: true // } // }, jstest: { files: ['test/spec/{,*/}*.js'], tasks: ['test:watch'] }, gruntfile: { files: ['Gruntfile.js'] }, sass: { files: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'], tasks: ['sass:server', 'autoprefixer'] }, styles: { files: ['<%= config.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= config.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= config.app %>/images/{,*/}*' ] } }, // The actual grunt server settings connect: { options: { port: 9000, open: true, livereload: 35729, // Change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, livereload: { options: { middleware: function(connect) { return [ connect.static('.tmp'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, test: { options: { open: false, port: 9001, middleware: function(connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, dist: { options: { base: '<%= config.dist %>', livereload: false } } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= config.dist %>/*', '!<%= config.dist %>/.git*' ] }] }, server: '.tmp' }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= config.app %>/scripts/{,*/}*.js', '!<%= config.app %>/scripts/vendor/*', 'test/spec/{,*/}*.js' ] }, // Mocha testing framework configuration options mocha: { all: { options: { run: true, urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html'] } } }, // Compiles Sass to CSS and generates necessary files if requested sass: { options: { loadPath: 'bower_components' }, dist: { files: [{ expand: true, cwd: '<%= config.app %>/styles', src: ['*.{scss,sass}'], dest: '.tmp/styles', ext: '.css' }] }, server: { files: [{ expand: true, cwd: '<%= config.app %>/styles', src: ['*.{scss,sass}'], dest: '.tmp/styles', ext: '.css' }] } }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'], map: { prev: '.tmp/styles/' } }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the HTML file wiredep: { app: { ignorePath: /^\/|\.\.\//, src: ['<%= config.app %>/index.html'] }, sass: { src: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'], ignorePath: /(\.\.\/){1,2}bower_components\// } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= config.dist %>/scripts/{,*/}*.js', '<%= config.dist %>/styles/{,*/}*.css', '<%= config.dist %>/images/{,*/}*.*', '<%= config.dist %>/styles/fonts/{,*/}*.*', '<%= config.dist %>/*.{ico,png}' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { options: { dest: '<%= config.dist %>' }, html: '<%= config.app %>/index.html' }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { options: { assetsDirs: [ '<%= config.dist %>', '<%= config.dist %>/images', '<%= config.dist %>/styles' ] }, html: ['<%= config.dist %>/{,*/}*.html'], css: ['<%= config.dist %>/styles/{,*/}*.css'] }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.{gif,jpeg,jpg,png}', dest: '<%= config.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.svg', dest: '<%= config.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseBooleanAttributes: true, collapseWhitespace: true, conservativeCollapse: true, removeAttributeQuotes: true, removeCommentsFromCDATA: true, removeEmptyAttributes: true, removeOptionalTags: true, removeRedundantAttributes: true, useShortDoctype: true }, files: [{ expand: true, cwd: '<%= config.dist %>', src: '{,*/}*.html', dest: '<%= config.dist %>' }] } }, // By default, your `index.html`'s <!-- Usemin block --> will take care // of minification. These next options are pre-configured if you do not // wish to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= config.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css', // '<%= config.app %>/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= config.dist %>/scripts/scripts.js': [ // '<%= config.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= config.app %>', dest: '<%= config.dist %>', src: [ '*.{ico,png,txt}', 'images/{,*/}*.png', 'images/*', '{,*/}*.html', 'styles/fonts/{,*/}*.*', 'fonts/*' ] }, { src: 'node_modules/apache-server-configs/dist/.htaccess', dest: '<%= config.dist %>/.htaccess' }] } }, // Run some tasks in parallel to speed up build process concurrent: { server: [ 'sass:server' ], test: [ ], dist: [ 'sass', 'imagemin', 'svgmin' ] }, watchify: { options: { debug: true }, dist: { src: './app/scripts/*.js', dest: './.tmp/scripts/bundle.js' } } }); grunt.loadNpmTasks('grunt-watchify'); grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) { if (grunt.option('allow-remote')) { grunt.config.set('connect.options.hostname', '0.0.0.0'); } if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'watchify', 'wiredep', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run([target ? ('serve:' + target) : 'serve']); }); grunt.registerTask('test', function (target) { if (target !== 'watch') { grunt.task.run([ 'clean:server', 'concurrent:test', 'autoprefixer' ]); } grunt.task.run([ 'connect:test', 'mocha' ]); }); grunt.registerTask('build', [ 'clean:dist', 'watchify', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'cssmin', 'uglify', 'copy:dist', // 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ // 'newer:jshint', 'watchify', 'test', 'build' ]); };
mit
KaelenJuntilla/KaelenJAwsomenauts2
js/gamemanagers/SpendGold.js
7742
game.SpendGold = Object.extend({ init: function(x, y, settings){ this.now = new Date().getTime(); this.lastBuy = new Date().getTime(); this.paused = false; this.alwaysUpdate = true; this.updateWhenPaused = true; this.buying = false; }, update: function(){ this.now = new Date().getTime(); if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >= 1000){ this.lastBuy = this.now; //this says if not buying then start buying// if(!this.buying){ this.startBuying(); }else{ //if buying then start buying// this.stopBuying(); } } this.checkBuyKeys(); return true; }, startBuying: function(){ this.buying = true; me.state.pause(me.state.PLAY); //this pauses my character in place when I start buying// game.data.pausePos = me.game.viewport.localToWorld(0, 0); //when games is paused then show this image which is the "Gold Screen" game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen')); game.data.buyscreen.updateWhenPaused = true; //this is how dark the screen when paused// game.data.buyscreen.setOpacity(0.8); me.game.world.addChild(game.data.buyscreen, 34); game.data.player.body.setVelocity(0, 0); me.input.bindKey(me.input.KEY.F1, "F1", true); me.input.bindKey(me.input.KEY.F2, "F2", true); me.input.bindKey(me.input.KEY.F3, "F3", true); me.input.bindKey(me.input.KEY.F4, "F4", true); me.input.bindKey(me.input.KEY.F5, "F5", true); me.input.bindKey(me.input.KEY.F6, "F6", true); this.setBuyText(); }, setBuyText: function(){ game.data.buytext = new (me.Renderable.extend({ init:function(){ this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]); this.font = new me.Font("Arial", 26, "white"); this.updateWhenPaused = true; this.alwaysUpdate = true; }, //this is all the skills in my buy screen// draw: function(renderer){ this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT. Current Gold: " + game.data.gold,this.pos.x, this.pos.y); this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost:" + ((game.data.skill1+1)*10),this.pos.x, this.pos.y + 40); this.font.draw(renderer.getContext(), "Skill 2: Run Faster! Current Level: " + game.data.skill2 + " Cost:" + ((game.data.skill2+1)*10),this.pos.x, this.pos.y + 80); this.font.draw(renderer.getContext(), "Skill 3: Increase Health! Current Level: " + game.data.skill3 + " Cost:" + ((game.data.skill3+1)*10),this.pos.x, this.pos.y + 120); this.font.draw(renderer.getContext(), "Q Ability: Speed Burst! Current Level" + game.data.ability1 + " Cost:" + ((game.data.ability1+1)*10),this.pos.x, this.pos.y + 160); this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep For Health:" + game.data.ability2 + " Cost:" + ((game.data.ability2+1)*10),this.pos.x, this.pos.y + 200); this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear:" + game.data.ability3 + " Cost:" + ((game.data.ability3+1)*10),this.pos.x, this.pos.y + 240); } })); me.game.world.addChild(game.data.buytext, 35); }, stopBuying: function(){ this.buying = false; //when wanting to return to the game then go back to the "PLAY" state// me.state.resume(me.state.PLAY); //When returning back to the play state then have a movespeed of 20// game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20); me.game.world.removeChild(game.data.buyscreen); me.input.unbindKey(me.input.KEY.F1, "F1", true); me.input.unbindKey(me.input.KEY.F2, "F2", true); me.input.unbindKey(me.input.KEY.F3, "F3", true); me.input.unbindKey(me.input.KEY.F4, "F4", true); me.input.unbindKey(me.input.KEY.F5, "F5", true); me.input.unbindKey(me.input.KEY.F6, "F6", true); me.game.world.removeChild(game.data.buytext); }, //this says if any keys were pressed during the buy screen then make the purchase// checkBuyKeys: function() { if(me.input.isKeyPressed("F1")){ //this says if the F1 key was pressed and have enough gold to buy then make the purchase to buy the ability or skill// if(this.checkCost(1)){ this.makePurchase(1); } }else if(me.input.isKeyPressed("F2")){ if(this.checkCost(2)){ this.makePurchase(2); } } else if(me.input.isKeyPressed("F3")){ if(this.checkCost(3)){ this.makePurchase(3); } } else if(me.input.isKeyPressed("F4")){ if(this.checkCost(4)){ this.makePurchase(4); } } else if(me.input.isKeyPressed("F5")){ if(this.checkCost(5)){ this.makePurchase(5); } } else if(me.input.isKeyPressed("F6")){ console.log(this.checkCost(6)); if(this.checkCost(6)){ this.makePurchase(6); } } }, checkCost: function(skill1){ //if skill 1 is selected and have more gold than the cost to level up skill 1 then return true// if(skill1===1 && (game.data.gold >= ((game.data.skill1+1)*10))) { return true; }else if(skill1===2 && (game.data.gold >= ((game.data.skill2+1)*10))) { return true; }else if(skill1===3 && (game.data.gold >= ((game.data.skill3+1)*10))) { return true; }else if(skill1===4 && (game.data.gold >= ((game.data.abilty1+1)*10))) { return true; }else if(skill1===5 && (game.data.gold >= ((game.data.ability2+1)*10))) { return true; }else if(skill1===6 && (game.data.gold >= ((game.data.ability3+1)*10))) { return true; }else{ return false; } }, makePurchase: function(skill){ //if you have enough to buy the skill then increase the player's ability or skill by one also the ability increases by ten // if(skill === 1){ game.data.gold -= ((game.data.skill1 +1)* 10); game.data.skill1 += 1; game.data.player.Attack += 1; }else if(skill ===2 ){ game.data.gold -= ((game.data.skill2 +1)* 10); game.data.skill2 += 1; }else if(skill ===3){ game.data.gold -= ((game.data.skill3 +1)* 10); game.data.skill3 += 1; } else if(skill ===4){ game.data.gold -= ((game.data.abilty1 +1)* 10); game.data.ability1 += 1; } else if(skill ===5){ game.data.gold -= ((game.data.ability2 +1)* 10); game.data.ability2 += 1; } else if(skill ===6){ game.data.gold -= ((game.data.ability3 +1)* 10); game.data.ability3 += 1; } } });
mit
xebia/akka-jigsaw
api/src/main/scala/com/xebia/akka/jigsaw/Events.scala
1082
package com.xebia.akka.jigsaw abstract class Event case class PieceMoved(id: String, x: Int, y: Int) extends Event case class UserJoined(id: String) extends Event case class UserLeft(id: String) extends Event case class EventWrapper(pieceMoved: Option[PieceMoved], userJoined: Option[UserJoined]) object EventWrapper { def wrap(event: Event): EventWrapper = event match { case pm: PieceMoved => EventWrapper(Some(pm), None) case uj: UserJoined => EventWrapper(None, Some(uj)) } def unwrap(eventWrapper: EventWrapper): Event = eventWrapper.pieceMoved match { case Some(event) => event case None => eventWrapper.userJoined match { case Some(event) => event } } } import spray.json.DefaultJsonProtocol import spray.json.JsonParser object MyJsonProtocol extends DefaultJsonProtocol { implicit val pieceMovedJson = jsonFormat3(PieceMoved) implicit val userJoinedJson = jsonFormat1(UserJoined) implicit val userLeftJson = jsonFormat1(UserLeft) implicit val eventWrapperJson = jsonFormat2(EventWrapper.apply) }
mit
feO2x/Light.GuardClauses
Code/Light.GuardClauses.Tests/ComparableAssertions/MustBeGreaterThanTests.cs
2140
using System; using FluentAssertions; using Xunit; namespace Light.GuardClauses.Tests.ComparableAssertions; public static class MustBeGreaterThanTests { [Theory] [InlineData(1, 1)] [InlineData(1, 2)] [InlineData(-1, -1)] [InlineData(0, 0)] public static void ParameterEqualOrLess(int first, int second) { Action act = () => first.MustBeGreaterThan(second, nameof(first)); var exceptionAssertion = act.Should().Throw<ArgumentOutOfRangeException>().Which; exceptionAssertion.Message.Should().Contain($"{nameof(first)} must be greater than {second}, but it actually is {first}."); exceptionAssertion.ParamName.Should().BeSameAs(nameof(first)); } [Theory] [InlineData(133, 99)] [InlineData(int.MaxValue, int.MaxValue - 1)] [InlineData(byte.MaxValue, byte.MinValue)] public static void ParameterGreater(int first, int second) => first.MustBeGreaterThan(second).Should().Be(first); [Fact] public static void CustomException() => Test.CustomException(40, 50, (x, y, exceptionFactory) => x.MustBeGreaterThan(y, exceptionFactory)); [Fact] public static void CustomExceptionParameterNull() => Test.CustomException((string) null, "Foo", (x, y, exceptionFactory) => x.MustBeGreaterThan(y, exceptionFactory)); [Fact] public static void NoCustomExceptionThrown() => 5.6m.MustBeGreaterThan(5.1m, (_, _) => null).Should().Be(5.6m); [Fact] public static void CustomMessage() => Test.CustomMessage<ArgumentOutOfRangeException>(message => 100.MustBeGreaterThan(100, message: message)); [Fact] public static void CustomMessageParameterNull() => Test.CustomMessage<ArgumentNullException>(message => ((string) null).MustBeGreaterThan("Bar", message: message)); [Fact] public static void CallerArgumentExpression() { var fifteen = 15; Action act = () => fifteen.MustBeGreaterThan(20); act.Should().Throw<ArgumentOutOfRangeException>() .And.ParamName.Should().Be(nameof(fifteen)); } }
mit
DavidBadura/Fixtures
src/Converter/ConverterRepositoryInterface.php
426
<?php declare(strict_types=1); namespace DavidBadura\Fixtures\Converter; /** * @author David Badura <[email protected]> */ interface ConverterRepositoryInterface { public function addConverter(ConverterInterface $converter): void; public function hasConverter(string $name): bool; public function getConverter(string $name): ConverterInterface; public function removeConverter(string $name): void; }
mit
nimeshvaghasiya/MyHeritage
src/MyHeritage.App/src/app/pages/dashboard/pieChart/index.js
187
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } __export(require('./pieChart.component')); //# sourceMappingURL=index.js.map
mit
ryrudnev/dss-wm
app/routes/user/EditRoute.js
1789
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as User } from '../../entities/User'; import { Collection as Companies } from '../../entities/Company'; import { PageHeader, Row, Col, Panel } from 'react-bootstrap'; import UserForm from '../../components/UserForm'; import Progress from 'react-progress-2'; import radio from 'backbone.radio'; const router = radio.channel('router'); const session = radio.channel('session'); export default class CompanyEditRoute extends Route { breadcrumb = 'Редактировать' authorize() { return session.request('currentUser').get('role') === 'admin'; } fetch({ params }) { this.user = new User({ id: params.id }); this.companies = new Companies; return [this.user.fetch(), this.companies.fetch()]; } onCancel() { router.request('navigate', `users/${this.user.id}`); } onSubmit(values) { Progress.show(); this.user.save(values, { success: model => { Progress.hide(); router.request('navigate', `users/${model.id}`); }, }); } render() { const values = { ...this.user.toJSON() }; return ( <div> <Helmet title={`Редактирование пользователя ${values.username}`} /> <PageHeader>{`Редактирование пользователя ${values.username}`}</PageHeader> <Row> <Col md={8}> <Panel> <UserForm values={values} onSubmit={vals => this.onSubmit(vals)} onCancel={() => this.onCancel()} companies={this.companies.toJSON()} /> </Panel> </Col> </Row> </div> ); } }
mit
wwdenis/wwa
samples/Marketplace/Marketplace.Web/app/models/Category.ts
282
// Copyright 2017 (c) [Denis Da Silva]. All rights reserved. // See License.txt in the project root for license information. /// <reference path="../_references.ts" /> module App.Models { 'use strict'; export class Category extends ActiveNamedModel { } }
mit
liruqi/bigfoot
Interface/AddOns/DBM-DMF/Gnoll.lua
1906
local mod = DBM:NewMod("Gnoll", "DBM-DMF") local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 17247 $"):sub(12, -3)) mod:SetZone() mod:RegisterEvents( "SPELL_AURA_APPLIED 101612", "SPELL_AURA_REMOVED 101612", "UNIT_SPELLCAST_SUCCEEDED player", "UNIT_POWER_FREQUENT player" ) mod.noStatistics = true local warnGameOverQuest = mod:NewAnnounce("warnGameOverQuest", 2, 101612, nil, false) local warnGameOverNoQuest = mod:NewAnnounce("warnGameOverNoQuest", 2, 101612, nil, false) mod:AddBoolOption("warnGameOver", true, "announce") local warnGnoll = mod:NewAnnounce("warnGnoll", 2, nil, false) local specWarnHogger = mod:NewSpecialWarning("specWarnHogger") local timerGame = mod:NewBuffActiveTimer(60, 101612, nil, nil, nil, 6) local countdownGame = mod:NewCountdownFades(60, 101612) local gameEarnedPoints = 0 local gameMaxPoints = 0 function mod:SPELL_AURA_APPLIED(args) if args.spellId == 101612 and args:IsPlayer() then gameEarnedPoints = 0 gameMaxPoints = 0 timerGame:Start() countdownGame:Start(60) end end function mod:SPELL_AURA_REMOVED(args) if args.spellId == 101612 and args:IsPlayer() then timerGame:Cancel() countdownGame:Cancel() if self.Options.warnGameOver then if gameEarnedPoints > 0 then warnGameOverQuest:Show(gameEarnedPoints, gameMaxPoints) else warnGameOverNoQuest:Show(gameMaxPoints) end end end end function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellID) if spellID == 102044 then--Hogger gameMaxPoints = gameMaxPoints + 3 if self:AntiSpam(2, 1) then specWarnHogger:Show() end elseif spellID == 102036 then--Gnoll gameMaxPoints = gameMaxPoints + 1 warnGnoll:Show() end end function mod:UNIT_POWER_FREQUENT(uId, type) if type == "ALTERNATE" then local playerPower = UnitPower("player", 10) if playerPower > gameEarnedPoints then gameEarnedPoints = playerPower end end end
mit
zauni/pngmin
test/pngmin_test.js
6708
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.pngmin = { setUp: function (done) { // setup here if necessary done(); }, default_options: function (test) { test.expect(2); var compressed = grunt.file.read('tmp/pngquant-logo-fs8.png'); var normal = grunt.file.read('test/fixtures/pngquant-logo.png'); test.ok(compressed.length < normal.length, 'should be smaller than before.'); test.ok(!grunt.file.exists('tmp/pngquant-logo.png')); test.done(); }, ext_test: function (test) { test.expect(2); var compressed = grunt.file.read('tmp/pngquant-logo-custom.png'); var normal = grunt.file.read('test/fixtures/pngquant-logo.png'); test.ok(compressed.length < normal.length, 'sould be smaller than before.'); test.ok(!grunt.file.exists('tmp/pngquant-logo.png')); test.done(); }, force_test: function (test) { test.expect(2); var compressed = grunt.file.read('tmp/force/force1.png'); var normal = grunt.file.read('test/fixtures/pngquant-logo.png'); test.ok(compressed.length < normal.length, 'sould be smaller than before.'); var actual = grunt.file.read('tmp/force/force2.png'); test.equal(actual.length, normal.length, 'should be the same size as the non-optimized file.'); test.done(); }, multiple_test: function (test) { test.expect(1); var actual = grunt.file.expand('tmp/multiple/*.png'); var expected = 10; test.equal(actual.length, expected, 'should be 10 images'); test.done(); }, subdir_test: function (test) { test.expect(4); var actual = grunt.file.expand('tmp/subdir_test/*.png'); var expected = 1; test.equal(actual.length, expected, 'should be just 1 image'); test.ok(grunt.file.isFile(actual[0]), 'should be a file and not a directory!'); test.ok(grunt.file.isDir('tmp/subdir_test/subdir1'), 'there should be subdir1 folder'); test.ok(grunt.file.isDir('tmp/subdir_test/subdir2'), 'there should be subdir2 folder'); test.done(); }, increase_test: function (test) { test.expect(3); var optimized = grunt.file.read('tmp/increase_test/glyphicons-halflings.png'); var nonOptimized = grunt.file.read('test/fixtures/increase_test/glyphicons-halflings.png'); test.ok(optimized.length < nonOptimized.length, 'optimized image should be smaller'); // the white icons are getting bigger if one tries to optimize them with pngquant // so pngmin should skip this file and just copy the source file to the destination test.ok(grunt.file.exists('tmp/increase_test/glyphicons-halflings-white.png'), 'file should be copied to the destination even if it wasn\'t optimized'); var skippedFile = grunt.file.read('tmp/increase_test/glyphicons-halflings-white.png'); var original = grunt.file.read('test/fixtures/increase_test/glyphicons-halflings-white.png'); test.equal(skippedFile.length, original.length, 'files should be the same size!'); test.done(); }, dest_test: function (test) { test.expect(1); var expected = 'tmp/dest_test/pngquant-logo.png'; test.ok(grunt.file.exists(expected) && grunt.file.isFile(expected), 'Image should be at the destination, even if we didn\'t use a directory as dest option!'); test.done(); }, exists_test: function (test) { test.expect(2); var actual = grunt.file.read('tmp/exists_test/pngquant-logo.png'); var expected = grunt.file.read('test/fixtures/pngquant-logo.png'); test.ok(actual.length < expected.length, 'there should be one optimized image.'); actual = grunt.file.expand('tmp/exists_test/*.png'); expected = 1; test.equal(actual.length, expected, 'should be just 1 image'); test.done(); }, quality_test: function (test) { test.expect(3); var actual = grunt.file.read('tmp/quality_test/pngquant-logo-qual2.png'); var already_optimized = grunt.file.read('tmp/pngquant-logo-fs8.png'); test.ok(actual.length < already_optimized.length, 'lower quality should result in even smaller images!'); var qualityError = grunt.file.read('tmp/quality_test/haustest-qual4.png'); var notOptimized = grunt.file.read('test/fixtures/haustest.png'); test.ok(qualityError.length < notOptimized.length, 'after an error with quality option, it should be optimized without quality option!'); test.ok(!grunt.file.exists('tmp/quality_test/haustest-qual5.png'), 'after an error with quality option, if options.retry is set to false, it should not be optimized without quality option!'); test.done(); }, nofs_test: function (test) { test.expect(2); var actual = grunt.file.read('tmp/nofs_test/pngquant-logo.png'); var expected = grunt.file.read('test/fixtures/nofs_test/pngquant-logonofs.png'); var original = grunt.file.read('tmp/pngquant-logo-fs8.png'); test.ok(Math.abs(actual.length - expected.length) <= 2000, 'file should be roughly the same size as the fixture (+- 2 kb)'); test.ok(actual.length < original.length, 'with nofs option the file should be smaller than a normal minimized file'); test.done(); }, error_test: function (test) { test.expect(1); // Prep to run grunt directly... var exec = require('child_process').exec, path = require('path'), execOptions = { cwd: path.join(__dirname, '..') }; // Call the grunt test directly and ensure we're getting a non-zero exit status. exec('grunt pngmin:error_test', execOptions, function(error, stdout) { test.ok(error && error.code !== 0, 'Ensure pngmin:error_test results in non-zero exit status. Exec result was: ' + JSON.stringify({error: error, stdout: stdout})); test.done(); }); }, };
mit
uyjco0/geli
GeLi/gggpIsokinetics/ExtractBioSecuenceFeatures.java
34281
package gggpIsokinetics; /** * * * @author Jorge Couchet * */ import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.Iterator; import java.util.Locale; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.impl.DenseDoubleMatrix1D; import util.io.file.GenericFile; /** * @author Jorge Couchet */ public class ExtractBioSecuenceFeatures { protected DoubleMatrix2D res; public static void main(String[] args) { ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Train/RN-Train.info", "C:/etc/Final/Iso/Genetic/RNormEje-Train18.sec", "C:/etc/Final/Iso/Genetic/RNormEje-Train26.sec", 0); ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Train/LN-Train.info", "C:/etc/Final/Iso/Genetic/LNormEje-Train18.sec", "C:/etc/Final/Iso/Genetic/LNormEje-Train26.sec", 0); ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Train/RC-Train.info", "C:/etc/Final/Iso/Genetic/RCondEje-Train18.sec", "C:/etc/Final/Iso/Genetic/RCondEje-Train26.sec", 1); ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Train/LC-Train.info", "C:/etc/Final/Iso/Genetic/LCondEje-Train18.sec", "C:/etc/Final/Iso/Genetic/LCondEje-Train26.sec", 1); ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Test/RN-Test.info", "C:/etc/Final/Iso/Genetic/RNormEje-Test18.sec", "C:/etc/Final/Iso/Genetic/RNormEje-Test26.sec", 0); ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Test/LN-Test.info", "C:/etc/Final/Iso/Genetic/LNormEje-Test18.sec", "C:/etc/Final/Iso/Genetic/LNormEje-Test26.sec", 0); ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Test/RC-Test.info", "C:/etc/Final/Iso/Genetic/RCondEje-Test18.sec", "C:/etc/Final/Iso/Genetic/RCondEje-Test26.sec", 1); ExtractBioSecuenceFeatures.BuildBioData("C:/etc/Final/Iso/Original3/Test/LC-Test.info", "C:/etc/Final/Iso/Genetic/LCondEje-Test18.sec", "C:/etc/Final/Iso/Genetic/LCondEje-Test26.sec", 1); } /** * * @return * Returns the first 72 primes. * */ static public double[] Prime() { int[] prime = new int[72]; double[] logPrime= new double[72]; prime[0] = 2; prime[1] = 3; prime[2] = 5; prime[3] = 7; prime[4] = 11; prime[5] = 13; prime[6] = 17; prime[7] = 19; prime[8] = 23; prime[9] = 29; prime[10] = 31; prime[11] = 37; prime[12] = 41; prime[13] = 43; prime[14] = 47; prime[15] = 53; prime[16] = 59; prime[17] = 61; prime[18] = 67; prime[19] = 71; prime[20] = 73; prime[21] = 79; prime[22] = 83; prime[23] = 89; prime[24] = 97; prime[25] = 101; prime[26] = 103; prime[27] = 107; prime[28] = 109; prime[29] = 113; prime[30] = 127; prime[31] = 131; prime[32] = 137; prime[33] = 139; prime[34] = 149; prime[35] = 151; prime[36] = 157; prime[37] = 163; prime[38] = 167; prime[39] = 173; prime[40] = 179; prime[41] = 181; prime[42] = 191; prime[43] = 193; prime[44] = 197; prime[45] = 199; prime[46] = 211; prime[47] = 223; prime[48] = 227; prime[49] = 229; prime[50] = 233; prime[51] = 239; prime[52] = 241; prime[53] = 251; prime[54] = 257; prime[55] = 263; prime[56] = 269; prime[57] = 271; prime[58] = 277; prime[59] = 281; prime[60] = 283; prime[61] = 293; prime[62] = 307; prime[63] = 311; prime[64] = 313; prime[65] = 317; prime[66] = 331; prime[67] = 337; prime[68] = 347; prime[69] = 349; prime[70] = 353; prime[71] = 359; for (int i=0;i<prime.length; i++){ logPrime[i]= Math.log10(prime[i]); } return logPrime; } /** * * The function extracts the features from a Isokinetics Time Series corresponding to an excercise. * * @param fileInfo * The file with the Isokinetics Time Series of several excercises. * * @param fileSecfeatureVec18 * The name of the file where the 18 features extracted from each excercise will * be saved. * * @param fileSecfeatureVec26 * The name of the file where the 26 features extracted from each excercise will * be saved. * * @param label * The label corresponding to "fileInfo", it is NORMAL ( = 0) or INJURY ( = 1). That is, all the * excercises holded in the file are of the same class. * * */ static public void BuildBioData(String fileInfo, String fileSecfeatureVec18, String fileSecfeatureVec26, int label){ /** ESTADISTICAS EN LA REPETICION */ // El torque máximo en una repetición double max_torque_rep; // El ángulo del torque máximo en la repetición double max_torque_ang_rep; // El tiempo del torque máximo double max_t_tor_rep; // El torque mínimo en una repetición double min_torque_rep; // El ángulo del torque mínimo en la repetición double min_torque_ang_rep; // El tiempo del torque mínimo double min_t_tor_rep; // El tiempo de la extensión en la repetición double t_ext_rep; double old_t_ext_rep; // El tiempo de la flexión en la repetición double t_flex_rep; double old_t_flex_rep; // Cantidad de elementos en la extensión int tot_elem_ext_rep; // Suma de los torques de una extensión double tot_torque_ext_rep; // Torque medio en la extensión double torque_medio_ext_rep; // Desviación torque medio en la extensión double torque_desv_medio_ext_rep; // Cantidad de elementos en la flexión int tot_elem_flex_rep; // Suma de los torques de una flexión double tot_torque_flex_rep; // Torque medio en la flexión double torque_medio_flex_rep; // Desviación torque medio en la flexión double torque_desv_medio_flex_rep; // Tiempo total de una repetición double t_total_rep; /** ESTADISTICAS EN EL EJERCICIO */ // Cantidad de repeticiones del ejercicio int tot_rep_eje; // Números primos para ser usados para codificar la secuencias de diferencias entre máximos en // las distintas repeticiones (también se codifican los mínimos y los correspondientes ángulos) double[] primes = ExtractBioSecuenceFeatures.Prime(); // Secuencia de diferencias entre máximos de las repeticiones de un ejercicio double sec_dif_max; double old_sec_max; // Secuencia de diferencias entre ángulos correspondientes a los máximos de las repeticiones de un ejercicio double sec_dif_max_ang; double old_sec_ang_max; // Secuencia de diferencias entre mínimos de las repeticiones de un ejercicio double sec_dif_min; double old_sec_min; // Secuencia de diferencias entre ángulos correspondientes a los mínimos de las repeticiones de un ejercicio double sec_dif_min_ang; double old_sec_ang_min; // El tiempo del ejercicio double t_eje; // El tiempo en llegar al máximo en el ejercicio double t_max_eje; // El tiempo en llegar al mínimo en el ejercicio double t_min_eje; // El torque máximo en un ejercicio double max_torque; // El ángulo del torque máximo en el ejercicio double max_torque_ang; // El torque mínimo en un ejercicio double min_torque; // El ángulo del torque mínimo en ejercicio double min_torque_ang; // Se usa para calcular el tiempo medio para llegar al máximo en las extensiones double tot_t_max; double tot_t_med_max; double tot_t_desv_max; // Se usa para calcular el tiempo medio para llegar al mínimo en las flexiones double tot_t_min; double tot_t_med_min; double tot_t_desv_min; //Se usa para calcular el tiempo medio de las extensiones double tot_t_ext; double tot_t_med_ext; double tot_t_desv_ext; // Se usa para calcular el tiempo medio de las flexiones double tot_t_flex; double tot_t_med_flex; double tot_t_desv_flex; // Se usa para calcular el tiempo medio de las repeticiones double tot_t_rep; double tot_t_med_rep; double tot_t_desv_rep; // Cantidad de elementos en las extensiones int tot_elem_ext; // Suma de los torques de las extensiones double tot_torque_ext; double tot_torque_med_ext; double tot_torque_desv_ext; // Cantidad de elementos en las flexión int tot_elem_flex; // Suma de los torques de las flexiones double tot_torque_flex; double tot_torque_med_flex; double tot_torque_desv_flex; GenericFile gen; gen = new GenericFile(); try{ gen.load(fileInfo); DoubleMatrix2D d = gen.getData(); int rowsDLrn = 0; int colsDLrn = 4; int rowsDSecRep = 0; int colsDSecRep = 17; int rowsDSecEje = 0; int colsDSecEje = 32; tot_rep_eje = 0; tot_elem_ext = 0; tot_elem_flex = 0; tot_torque_flex = 0; tot_torque_ext = 0; max_torque = Integer.MIN_VALUE; max_torque_ang = Integer.MIN_VALUE; min_torque = Integer.MAX_VALUE; min_torque_ang = Integer.MAX_VALUE; sec_dif_max = 1; sec_dif_max_ang = 1; sec_dif_min = 1; sec_dif_min_ang = 1; old_sec_max = 0; old_sec_ang_max = 0; old_sec_min = 0; old_sec_ang_min = 0; t_eje = 0; t_max_eje = 0; t_min_eje = 0; tot_t_max = 0; tot_t_min = 0; tot_t_ext = 0; tot_t_flex = 0; tot_t_rep = 0; DoubleMatrix2D dLrnRep = new DenseDoubleMatrix2D(d.rows(), colsDLrn); DoubleMatrix2D dSecRep = new DenseDoubleMatrix2D(d.rows(), colsDSecRep); DoubleMatrix2D dSecEje = new DenseDoubleMatrix2D(d.rows(), colsDSecEje); DoubleMatrix2D auxExt = new DenseDoubleMatrix2D(d.rows(),1); DoubleMatrix2D auxFlex = new DenseDoubleMatrix2D(d.rows(),1); int i=0; while(i < d.rows()){ /** Aquí comienza un ejercicio */ if(d.get(i, 0) == -3535){ rowsDSecEje++; tot_rep_eje =0; //Key dSecEje.set(rowsDSecEje-1, 0, rowsDSecEje); // Comienzo de la secuencia de repeticiones de un ejercicio dSecEje.set(rowsDSecEje-1, 1, (rowsDSecRep + 1)); //Label dSecEje.set(rowsDSecEje-1, 3, label); //Id de la persona dSecEje.set(rowsDSecEje-1, 4, d.get(i, 1)); //Sexo de la persona dSecEje.set(rowsDSecEje-1, 5, d.get(i, 2)); max_torque = Integer.MIN_VALUE; max_torque_ang = Integer.MIN_VALUE; min_torque = Integer.MAX_VALUE; min_torque_ang = Integer.MAX_VALUE; tot_elem_ext = 0; tot_torque_ext = 0; tot_elem_flex = 0; tot_torque_flex = 0; sec_dif_max = 1; sec_dif_max_ang = 1; sec_dif_min = 1; sec_dif_min_ang = 1; t_eje = 0; t_max_eje = 0; t_min_eje = 0; tot_t_max = 0; tot_t_min = 0; tot_t_ext = 0; tot_t_flex = 0; tot_t_rep = 0; i++; } int start_rep = rowsDSecRep; /** Aquí estoy dentro de un ejercicio */ while((i<d.rows()) && (d.get(i, 0) != -3535)){ /** Aquí comienza una repetición */ rowsDSecRep++; tot_rep_eje++; max_torque_rep = Integer.MIN_VALUE; max_torque_ang_rep = Integer.MIN_VALUE; max_t_tor_rep = 0; min_torque_rep = Integer.MAX_VALUE; min_torque_ang_rep = Integer.MAX_VALUE; min_t_tor_rep = 0; // Key dSecRep.set(rowsDSecRep-1, 0, rowsDSecRep); // Comienzo de secuencia de valores de una repetición dSecRep.set(rowsDSecRep-1, 1, (rowsDLrn + 1)); /** Aquí estoy dentro de la extensión de la repetición */ tot_elem_ext_rep = 0; tot_torque_ext_rep = 0; t_ext_rep = 0; old_t_ext_rep = 0; int start_ext = rowsDLrn; while((i<d.rows()) && (d.get(i, 2) >= 0) && (d.get(i, 0) != -3535)){ tot_elem_ext_rep++; tot_elem_ext++; rowsDLrn++; // Key dLrnRep.set(rowsDLrn-1, 0, rowsDLrn); // Valor absoluto del tiempo dLrnRep.set(rowsDLrn-1, 1, Math.abs(d.get(i, 0))); // Valor absoluto del angulo dLrnRep.set(rowsDLrn-1, 2, Math.abs(d.get(i, 1))); // Torque dLrnRep.set(rowsDLrn-1, 3, d.get(i, 2)); //Necesito los torques de todas las extensiones para calcular su desviación global auxExt.set(tot_elem_ext-1, 0, d.get(i, 2)); tot_torque_ext_rep = tot_torque_ext_rep + d.get(i, 2); tot_torque_ext = tot_torque_ext + d.get(i, 2); if(tot_elem_ext_rep != 1){ t_ext_rep = t_ext_rep + Math.abs(Math.abs(d.get(i, 0)) - old_t_ext_rep); t_eje = t_eje + Math.abs(Math.abs(d.get(i, 0)) - old_t_ext_rep); old_t_ext_rep = Math.abs(d.get(i, 0)); }else{ old_t_ext_rep = Math.abs(d.get(i, 0)); } if(d.get(i, 2) > max_torque_rep){ max_torque_rep = d.get(i, 2); max_torque_ang_rep = Math.abs(d.get(i, 1)); max_t_tor_rep = t_ext_rep; } if(d.get(i, 2) > max_torque){ max_torque = d.get(i, 2); t_max_eje = t_eje; max_torque_ang = Math.abs(d.get(i, 1)); } i++; } /** Aquí finaliza una extensión */ int final_ext = rowsDLrn; //Calculo el torque medio de la extensión torque_medio_ext_rep = 0; if(tot_elem_ext_rep != 0){ torque_medio_ext_rep = tot_torque_ext_rep/tot_elem_ext_rep; } //Calculo la varianza muestral del torque en la extensión torque_desv_medio_ext_rep = 0; for(int j= start_ext; j < final_ext; j++){ torque_desv_medio_ext_rep = torque_desv_medio_ext_rep + Math.pow((dLrnRep.get(j, 3)-torque_medio_ext_rep),2); } if((tot_elem_ext_rep-1) != 0){ torque_desv_medio_ext_rep = torque_desv_medio_ext_rep/(tot_elem_ext_rep-1); } //Verifico que no sea la primera repetición if(tot_rep_eje != 1){ //Calculo el elemento actual de diferencia entre máximos y lo codifico con primos //(Teo fundamental de la aritmética y le aplico logaritmo) sec_dif_max = sec_dif_max + primes[tot_rep_eje-2]*(old_sec_max - max_torque_rep); sec_dif_max_ang = sec_dif_max_ang + primes[tot_rep_eje-2]*(old_sec_ang_max - max_torque_ang_rep); old_sec_max = max_torque_rep; old_sec_ang_max = max_torque_ang_rep; }else{ old_sec_max = max_torque_rep; old_sec_ang_max = max_torque_ang_rep; } /** Aquí estoy dentro de la flexión de la repetición */ tot_elem_flex_rep = 0; tot_torque_flex_rep = 0; t_flex_rep = 0; old_t_flex_rep = 0; int start_flex = rowsDLrn; while((i< d.rows()) && (d.get(i, 2) <= 0) && (d.get(i, 0) != -3535)){ tot_elem_flex_rep++; tot_elem_flex++; rowsDLrn++; // Key dLrnRep.set(rowsDLrn-1, 0, rowsDLrn); // Valor absoluto del tiempo dLrnRep.set(rowsDLrn-1, 1, Math.abs(d.get(i, 0))); // Valor absoluto del angulo dLrnRep.set(rowsDLrn-1, 2, Math.abs(d.get(i, 1))); // Torque dLrnRep.set(rowsDLrn-1, 3, d.get(i, 2)); // Necesito los torques de todas las flexiones para calcular su desviación global auxFlex.set(tot_elem_flex-1, 0, d.get(i, 2)); tot_torque_flex_rep = tot_torque_flex_rep + d.get(i, 2); tot_torque_flex = tot_torque_flex + d.get(i, 2); if(tot_elem_flex_rep != 1){ t_flex_rep = t_flex_rep + Math.abs(Math.abs(d.get(i, 0)) - old_t_flex_rep); t_eje = t_eje + Math.abs(Math.abs(d.get(i, 0)) - old_t_flex_rep); old_t_flex_rep = Math.abs(d.get(i, 0)); }else{ old_t_flex_rep = Math.abs(d.get(i, 0)); } if(d.get(i, 2) < min_torque_rep){ min_torque_rep = d.get(i, 2); min_torque_ang_rep = Math.abs(d.get(i, 1)); min_t_tor_rep = t_flex_rep; } if(d.get(i, 2) < min_torque){ min_torque = d.get(i, 2); t_min_eje = t_eje; min_torque_ang = Math.abs(d.get(i, 1)); } i++; } /** Aquí finaliza la flexión */ int final_flex = rowsDLrn; //Calculo el torque medio de la flexión torque_medio_flex_rep = 0; if(tot_elem_flex_rep != 0){ torque_medio_flex_rep = tot_torque_flex_rep/tot_elem_flex_rep; } // Calculo la varianza muestral del torque en la flexion torque_desv_medio_flex_rep = 0; for(int j= start_flex; j < final_flex; j++){ torque_desv_medio_flex_rep = torque_desv_medio_flex_rep + Math.pow((dLrnRep.get(j, 3)-torque_medio_flex_rep),2); } if((tot_elem_flex_rep-1) != 0){ torque_desv_medio_flex_rep = torque_desv_medio_flex_rep/(tot_elem_flex_rep-1); } // Verifico que no sea la primera repetición if(tot_rep_eje != 1){ //Calculo el elemento actual de diferencia entre mínimos y lo codifico con primos //(Teo fundamental de la aritmética y le aplico logaritmo) sec_dif_min = sec_dif_min + primes[tot_rep_eje-2]*(old_sec_min - min_torque_rep); sec_dif_min_ang = sec_dif_min_ang + primes[tot_rep_eje-2]*(old_sec_ang_min - min_torque_ang_rep); old_sec_min = min_torque_rep; old_sec_ang_min = min_torque_ang_rep; }else{ old_sec_min = min_torque_rep; old_sec_ang_min = min_torque_ang_rep; } // Final de secuencia de valores de una repetición dSecRep.set(rowsDSecRep-1, 2, dSecRep.get(rowsDSecRep-1, 1) + (tot_elem_ext_rep + tot_elem_flex_rep - 1)); //Label dSecRep.set(rowsDSecRep-1, 3, label); //Tiempo total de una repetición t_total_rep = t_ext_rep + t_flex_rep; dSecRep.set(rowsDSecRep-1, 4, t_total_rep); //Tiempo total de la extensión en la repetición dSecRep.set(rowsDSecRep-1, 5, t_ext_rep); //Tiempo total de la flexión en la repetición dSecRep.set(rowsDSecRep-1, 6, t_flex_rep); //Máximo de la extensión en la repetición dSecRep.set(rowsDSecRep-1, 7, max_torque_rep); //Angulo del máximo de la extensión en la repetición dSecRep.set(rowsDSecRep-1, 8, max_torque_ang_rep); //Mínimo de la flexión en la repetición dSecRep.set(rowsDSecRep-1, 9, min_torque_rep); //Angulo del mínimo de la flexión en la repetición dSecRep.set(rowsDSecRep-1, 10, min_torque_ang_rep); // Tiempo en llegar al máximo en la extensión dSecRep.set(rowsDSecRep-1, 11, max_t_tor_rep); // Tiempo en llegar al mínimo en la flexión dSecRep.set(rowsDSecRep-1, 12, min_t_tor_rep); // Torque medio en la extensión dSecRep.set(rowsDSecRep-1, 13, torque_medio_ext_rep); // Desviación muestral del torque medio en la extensión dSecRep.set(rowsDSecRep-1, 14, torque_desv_medio_ext_rep); // Torque medio en la flexión dSecRep.set(rowsDSecRep-1, 15, torque_medio_flex_rep); // Desviación muestral del torque medio en la flexión dSecRep.set(rowsDSecRep-1, 16, torque_desv_medio_flex_rep); tot_t_max = tot_t_max + max_t_tor_rep; tot_t_min = tot_t_min + min_t_tor_rep; tot_t_ext = tot_t_ext + t_ext_rep; tot_t_flex = tot_t_flex + t_flex_rep; tot_t_rep = tot_t_rep + t_total_rep; } /** Aquí finaliza el ejercicio */ int final_rep = rowsDSecRep; // Final de la secuencia de repeticiones de un ejercicio dSecEje.set(rowsDSecEje-1, 2, (dSecEje.get(rowsDSecEje-1,1) + (tot_rep_eje - 1))); // Cantidad de repeticiones del ejercicio dSecEje.set(rowsDSecEje-1, 6, tot_rep_eje); //Secuencia de diferencias de máximos del ejercicio codificada en un solo número dSecEje.set(rowsDSecEje-1, 7, sec_dif_max); // Secuencia de diferencias de ángulos de máximos del ejercicio codificada en un solo número dSecEje.set(rowsDSecEje-1, 8, sec_dif_max_ang); // Secuencia de diferencias de mínimos del ejercicio codificada en un solo número dSecEje.set(rowsDSecEje-1, 9, sec_dif_min); // Secuencia de diferencias de ángulos de mínimos del ejercicio codificada en un solo número dSecEje.set(rowsDSecEje-1, 10, sec_dif_min_ang); // Tiempo total del ejercicio dSecEje.set(rowsDSecEje-1, 11, t_eje); // Máximo torque del ejercicio dSecEje.set(rowsDSecEje-1, 12, max_torque); // Angulo del máximo torque del ejercicio dSecEje.set(rowsDSecEje-1, 13, max_torque_ang); // Tiempo del máximo torque del ejercicio dSecEje.set(rowsDSecEje-1, 14, t_max_eje); // Mínimo torque del ejercicio dSecEje.set(rowsDSecEje-1, 15, min_torque); // Angulo del mínimo torque del ejercicio dSecEje.set(rowsDSecEje-1, 16, min_torque_ang); // Tiempo del mínimo torque del ejercicio dSecEje.set(rowsDSecEje-1, 17, t_min_eje); tot_t_med_max = 0; tot_t_med_min = 0; tot_t_med_ext = 0; tot_t_med_flex = 0; tot_t_med_rep = 0; if(tot_rep_eje != 0){ //Tiempo medio de llegar al máximo en las extensiones de las distintas repeticiones tot_t_med_max = tot_t_max/tot_rep_eje; //Tiempo medio de llegar al mínimo en las flexiones de las distintas repeticiones tot_t_med_min = tot_t_min/tot_rep_eje; //Tiempo medio de las extensiones en un ejercicio tot_t_med_ext = tot_t_ext/tot_rep_eje; //Tiempo medio de las flexiones en un ejercicio tot_t_med_flex = tot_t_flex/tot_rep_eje; //Tiempo medio de las repeticiones en un ejercicio tot_t_med_rep = tot_t_rep/tot_rep_eje; } tot_torque_med_ext = 0; if(tot_elem_ext != 0){ //Torque medio en las extensiones de las distintas repeticiones tot_torque_med_ext = tot_torque_ext/tot_elem_ext; } tot_torque_med_flex = 0; if(tot_elem_flex != 0){ //Torque medio en las flexiones de las distintas repeticiones tot_torque_med_flex = tot_torque_flex/tot_elem_flex; } tot_t_desv_max = 0; tot_t_desv_min = 0; tot_t_desv_ext = 0; tot_t_desv_flex = 0; tot_t_desv_rep = 0; for(int j=start_rep; j < final_rep; j++ ){ //Desviación estándar muestral del tiempo medio en llegar al máximo de las distintas extensiones tot_t_desv_max = tot_t_desv_max + Math.pow((dSecRep.get(j, 11)-tot_t_med_max),2); //Desviación estándar muestral del tiempo medio en llegar al mínimo de las distintas flexiones tot_t_desv_min = tot_t_desv_min + Math.pow((dSecRep.get(j, 12)-tot_t_med_min),2); //Desviación estandar muestral del tiempo de las extensiones en un ejercicio tot_t_desv_ext = tot_t_desv_ext + Math.pow((dSecRep.get(j, 5)-tot_t_med_ext),2); //Desviación estandar muestral del tiempo de las flexiones en un ejercicio tot_t_desv_flex = tot_t_desv_flex + Math.pow((dSecRep.get(j, 6)-tot_t_med_flex),2); //Desviacion estandar muestral del tiempo de las repeticiones en un ejercicio tot_t_desv_rep = tot_t_desv_rep + Math.pow((dSecRep.get(j, 4)-tot_t_med_rep),2); } tot_torque_desv_ext = 0; //Desviación estándar muestral del torque medio de las distintas extensiones for(int j=0; j < tot_elem_ext; j++){ tot_torque_desv_ext = tot_torque_desv_ext + Math.pow((auxExt.get(j, 0) - tot_torque_med_ext),2); } tot_torque_desv_flex = 0; //Desviación estándar muestral del torque medio de las distintas flexiones for(int j=0; j < tot_elem_flex; j++){ tot_torque_desv_flex = tot_torque_desv_flex + Math.pow((auxFlex.get(j, 0) - tot_torque_med_flex ),2); } if((tot_rep_eje-1) != 0){ //Desviación estándar muestral del tiempo medio en llegar al máximo de las distintas extensiones tot_t_desv_max = tot_t_desv_max/(tot_rep_eje-1); //Desviación estándar muestral del tiempo medio en llegar al mínimo de las distintas flexiones tot_t_desv_min = tot_t_desv_min/(tot_rep_eje-1); //Desviación estandar muestral del tiempo de las extensiones en un ejercicio tot_t_desv_ext = tot_t_desv_ext/(tot_rep_eje-1); //Desviación estandar muestral del tiempo de las flexiones en un ejercicio tot_t_desv_flex = tot_t_desv_flex/(tot_rep_eje-1); //Desviacion estandar muestral del tiempo de las repeticiones en un ejercicio tot_t_desv_rep = tot_t_desv_rep/(tot_rep_eje-1); } if((tot_elem_ext-1) != 0){ //Desviación estándar muestral del torque medio de las distintas extensiones tot_torque_desv_ext = tot_torque_desv_ext/(tot_elem_ext-1); } if((tot_elem_flex-1) != 0){ //Desviación estándar muestral del torque medio de las distintas flexiones tot_torque_desv_flex = tot_torque_desv_flex/(tot_elem_flex-1); } // Tiempo medio de las repeticiones en llegar al máximo dSecEje.set(rowsDSecEje-1, 18, tot_t_med_max); // Desviación estándar muestral del tiempo medio de las repeticiones en llegar al máximo dSecEje.set(rowsDSecEje-1, 19, tot_t_desv_max); // Tiempo medio de las repeticiones en llegar al mínimo dSecEje.set(rowsDSecEje-1, 20, tot_t_med_min); // Desviación estándar muestral del tiempo medio de las repeticiones en llegar al mínimo dSecEje.set(rowsDSecEje-1, 21, tot_t_desv_min); // Torque medio en las extensiones de las distintas repeticiones dSecEje.set(rowsDSecEje-1, 22, tot_torque_med_ext); // Desviación estándar muestral del torque medio de las distintas extensiones dSecEje.set(rowsDSecEje-1, 23, tot_torque_desv_ext); // Torque medio en las flexiones de las distintas repeticiones dSecEje.set(rowsDSecEje-1, 24, tot_torque_med_flex); // Desviación estándar muestral del torque medio de las distintas flexiones dSecEje.set(rowsDSecEje-1, 25, tot_torque_desv_flex); //Tiempo medio de las extensiones en un ejercicio dSecEje.set(rowsDSecEje-1, 26, tot_t_med_ext); //Desviación estandar muestral del tiempo de las extensiones en un ejercicio dSecEje.set(rowsDSecEje-1, 27, tot_t_desv_ext); //Tiempo medio de las flexiones en un ejercicio dSecEje.set(rowsDSecEje-1, 28, tot_t_med_flex); //Desviación estandar muestral del tiempo de las flexiones en un ejercicio dSecEje.set(rowsDSecEje-1, 29, tot_t_desv_flex); //Tiempo medio de las repeticiones en un ejercicio dSecEje.set(rowsDSecEje-1, 30, tot_t_med_rep); //Desviacion estandar muestral del tiempo de las repeticiones en un ejercicio dSecEje.set(rowsDSecEje-1, 31, tot_t_desv_rep); } GenericFile gen2 = new GenericFile(); //Genera a partir del dSecEje un SEC file con las 18 features para el algoritmo genético DoubleMatrix2D featureVec18 = new DenseDoubleMatrix2D(rowsDSecEje, 18); int amountRows = 0; while( amountRows < rowsDSecEje){ featureVec18.set(amountRows, 0, dSecEje.get(amountRows, 7)); featureVec18.set(amountRows, 1, dSecEje.get(amountRows, 8)); featureVec18.set(amountRows, 2, dSecEje.get(amountRows, 9)); featureVec18.set(amountRows, 3, dSecEje.get(amountRows, 10)); featureVec18.set(amountRows, 4, dSecEje.get(amountRows, 12)); featureVec18.set(amountRows, 5, dSecEje.get(amountRows, 13)); featureVec18.set(amountRows, 6, dSecEje.get(amountRows, 14)); featureVec18.set(amountRows, 7, dSecEje.get(amountRows, 15)); featureVec18.set(amountRows, 8, dSecEje.get(amountRows, 16)); featureVec18.set(amountRows, 9, dSecEje.get(amountRows, 17)); featureVec18.set(amountRows, 10, dSecEje.get(amountRows, 18)); featureVec18.set(amountRows, 11, dSecEje.get(amountRows, 20)); featureVec18.set(amountRows, 12, dSecEje.get(amountRows, 22)); featureVec18.set(amountRows, 13, dSecEje.get(amountRows, 24)); featureVec18.set(amountRows, 14, dSecEje.get(amountRows, 19)); featureVec18.set(amountRows, 15, dSecEje.get(amountRows, 21)); featureVec18.set(amountRows, 16, dSecEje.get(amountRows, 23)); featureVec18.set(amountRows, 17, dSecEje.get(amountRows, 25)); amountRows++; } gen2.setColumns(18); gen2.setRows(rowsDSecEje); gen2.setData(featureVec18); gen2.save(fileSecfeatureVec18); // Genera a partir del dSecEje un SEC file con las 26 features para el algoritmo genético DoubleMatrix2D featureVec26 = new DenseDoubleMatrix2D(rowsDSecEje, 26); amountRows = 0; while( amountRows < rowsDSecEje){ featureVec26.set(amountRows, 0, dSecEje.get(amountRows, 6)); featureVec26.set(amountRows, 1, dSecEje.get(amountRows, 7)); featureVec26.set(amountRows, 2, dSecEje.get(amountRows, 8)); featureVec26.set(amountRows, 3, dSecEje.get(amountRows, 9)); featureVec26.set(amountRows, 4, dSecEje.get(amountRows, 10)); featureVec26.set(amountRows, 5, dSecEje.get(amountRows, 11)); featureVec26.set(amountRows, 6, dSecEje.get(amountRows, 12)); featureVec26.set(amountRows, 7, dSecEje.get(amountRows, 13)); featureVec26.set(amountRows, 8, dSecEje.get(amountRows, 14)); featureVec26.set(amountRows, 9, dSecEje.get(amountRows, 15)); featureVec26.set(amountRows, 10, dSecEje.get(amountRows, 16)); featureVec26.set(amountRows, 11, dSecEje.get(amountRows, 17)); featureVec26.set(amountRows, 12, dSecEje.get(amountRows, 18)); featureVec26.set(amountRows, 13, dSecEje.get(amountRows, 19)); featureVec26.set(amountRows, 14, dSecEje.get(amountRows, 20)); featureVec26.set(amountRows, 15, dSecEje.get(amountRows, 21)); featureVec26.set(amountRows, 16, dSecEje.get(amountRows, 22)); featureVec26.set(amountRows, 17, dSecEje.get(amountRows, 23)); featureVec26.set(amountRows, 18, dSecEje.get(amountRows, 24)); featureVec26.set(amountRows, 19, dSecEje.get(amountRows, 25)); featureVec26.set(amountRows, 20, dSecEje.get(amountRows, 26)); featureVec26.set(amountRows, 21, dSecEje.get(amountRows, 27)); featureVec26.set(amountRows, 22, dSecEje.get(amountRows, 28)); featureVec26.set(amountRows, 23, dSecEje.get(amountRows, 29)); featureVec26.set(amountRows, 24, dSecEje.get(amountRows, 30)); featureVec26.set(amountRows, 25, dSecEje.get(amountRows, 31)); amountRows++; } gen2.setColumns(26); gen2.setRows(rowsDSecEje); gen2.setData(featureVec26); gen2.save(fileSecfeatureVec26); } catch (IOException e) { System.out.println("error processing the file: " + e.getMessage()); } } static public void FormatBioFile (String fileInfo, String fileInfo2, int col){ GenericFile gen; gen = new GenericFile(); try{ gen.loadWithoutHeader(fileInfo,col); DoubleMatrix2D d = gen.getData(); System.out.println(""); for(int i =0; i < d.rows(); i++){ for(int j=0; j < d.columns(); j++){ System.out.print(d.get(i, j)); System.out.print(" "); } System.out.println(""); } gen.save(fileInfo2); } catch (IOException e) { System.out.println("error processing the file: " + e.getMessage()); } } /** * * * @param fileInfo * The name and path of the file with the features of the training items. * * @param col * The amount of colums in the file with the features. * * @param names * A list with the name of each feature. * * @return * The mapping from the name of each feature to his average real value in the training items. * */ static public Map<String, Double> calculateAverageFeatures (String fileInfo, int col, Collection<String> names){ GenericFile gen; DoubleMatrix1D res; Map<String, Double> result = null; double avg; int pos; String s; Iterator<String> it; if (names.size() == (col-1)){ gen = new GenericFile(); /** The decimal sepatator is the character "." */ gen.setLocale(Locale.US); res = new DenseDoubleMatrix1D (col-1); result = new ConcurrentHashMap<String, Double>(); try{ gen.load(fileInfo); DoubleMatrix2D d = gen.getData(); /** The last column has the label: 0 = NORMAL, 1 = INJURY. */ for(int i =0; i < (d.columns()-1); i++){ avg = 0; for(int j=0; j < d.rows(); j++){ avg = avg + d.get(j, i); } avg = avg/d.rows(); res.set(i, avg); } } catch (IOException e) { System.out.println("error processing the file: " + e.getMessage()); } pos = 0; it = names.iterator(); while (it.hasNext()){ s = it.next(); result.put(s, new Double(res.get(pos))); pos++; } } return result; } }
mit
ollie314/angular.js
test/ng/rootScopeSpec.js
72603
'use strict'; describe('Scope', function() { beforeEach(module(provideLog)); describe('$root', function() { it('should point to itself', inject(function($rootScope) { expect($rootScope.$root).toEqual($rootScope); expect($rootScope.hasOwnProperty('$root')).toBeTruthy(); })); it('should expose the constructor', inject(function($rootScope) { if (msie < 11) return; // eslint-disable-next-line no-proto expect($rootScope.__proto__).toBe($rootScope.constructor.prototype); })); it('should not have $root on children, but should inherit', inject(function($rootScope) { var child = $rootScope.$new(); expect(child.$root).toEqual($rootScope); expect(child.hasOwnProperty('$root')).toBeFalsy(); })); }); describe('$parent', function() { it('should point to itself in root', inject(function($rootScope) { expect($rootScope.$root).toEqual($rootScope); })); it('should point to parent', inject(function($rootScope) { var child = $rootScope.$new(); expect($rootScope.$parent).toEqual(null); expect(child.$parent).toEqual($rootScope); expect(child.$new().$parent).toEqual(child); })); }); describe('$id', function() { it('should have a unique id', inject(function($rootScope) { expect($rootScope.$id < $rootScope.$new().$id).toBeTruthy(); })); }); describe('this', function() { it('should evaluate \'this\' to be the scope', inject(function($rootScope) { var child = $rootScope.$new(); expect($rootScope.$eval('this')).toEqual($rootScope); expect(child.$eval('this')).toEqual(child); })); it('\'this\' should not be recursive', inject(function($rootScope) { expect($rootScope.$eval('this.this')).toBeUndefined(); expect($rootScope.$eval('$parent.this')).toBeUndefined(); })); it('should not be able to overwrite the \'this\' keyword', inject(function($rootScope) { $rootScope['this'] = 123; expect($rootScope.$eval('this')).toEqual($rootScope); })); it('should be able to access a variable named \'this\'', inject(function($rootScope) { $rootScope['this'] = 42; expect($rootScope.$eval('this[\'this\']')).toBe(42); })); }); describe('$new()', function() { it('should create a child scope', inject(function($rootScope) { var child = $rootScope.$new(); $rootScope.a = 123; expect(child.a).toEqual(123); })); it('should create a non prototypically inherited child scope', inject(function($rootScope) { var child = $rootScope.$new(true); $rootScope.a = 123; expect(child.a).toBeUndefined(); expect(child.$parent).toEqual($rootScope); expect(child.$new).toBe($rootScope.$new); expect(child.$root).toBe($rootScope); })); it('should attach the child scope to a specified parent', inject(function($rootScope) { var isolated = $rootScope.$new(true); var trans = $rootScope.$new(false, isolated); $rootScope.a = 123; expect(isolated.a).toBeUndefined(); expect(trans.a).toEqual(123); expect(trans.$parent).toBe(isolated); })); }); describe('$watch/$digest', function() { it('should watch and fire on simple property change', inject(function($rootScope) { var spy = jasmine.createSpy(); $rootScope.$watch('name', spy); $rootScope.$digest(); spy.calls.reset(); expect(spy).not.toHaveBeenCalled(); $rootScope.$digest(); expect(spy).not.toHaveBeenCalled(); $rootScope.name = 'misko'; $rootScope.$digest(); expect(spy).toHaveBeenCalledWith('misko', undefined, $rootScope); })); it('should not expose the `inner working of watch', inject(function($rootScope) { function Getter() { expect(this).toBeUndefined(); return 'foo'; } function Listener() { expect(this).toBeUndefined(); } if (msie < 10) return; $rootScope.$watch(Getter, Listener); $rootScope.$digest(); })); it('should watch and fire on expression change', inject(function($rootScope) { var spy = jasmine.createSpy(); $rootScope.$watch('name.first', spy); $rootScope.$digest(); spy.calls.reset(); $rootScope.name = {}; expect(spy).not.toHaveBeenCalled(); $rootScope.$digest(); expect(spy).not.toHaveBeenCalled(); $rootScope.name.first = 'misko'; $rootScope.$digest(); expect(spy).toHaveBeenCalled(); })); it('should not keep constant expressions on watch queue', inject(function($rootScope) { $rootScope.$watch('1 + 1', function() {}); expect($rootScope.$$watchers.length).toEqual(1); expect($rootScope.$$watchersCount).toEqual(1); $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(0); expect($rootScope.$$watchersCount).toEqual(0); })); it('should decrement the watcherCount when destroying a child scope', inject(function($rootScope) { var child1 = $rootScope.$new(), child2 = $rootScope.$new(), grandChild1 = child1.$new(), grandChild2 = child2.$new(); child1.$watch('a', function() {}); child2.$watch('a', function() {}); grandChild1.$watch('a', function() {}); grandChild2.$watch('a', function() {}); expect($rootScope.$$watchersCount).toBe(4); expect(child1.$$watchersCount).toBe(2); expect(child2.$$watchersCount).toBe(2); expect(grandChild1.$$watchersCount).toBe(1); expect(grandChild2.$$watchersCount).toBe(1); grandChild2.$destroy(); expect(child2.$$watchersCount).toBe(1); expect($rootScope.$$watchersCount).toBe(3); child1.$destroy(); expect($rootScope.$$watchersCount).toBe(1); })); it('should decrement the watcherCount when calling the remove function', inject(function($rootScope) { var child1 = $rootScope.$new(), child2 = $rootScope.$new(), grandChild1 = child1.$new(), grandChild2 = child2.$new(), remove1, remove2; remove1 = child1.$watch('a', function() {}); child2.$watch('a', function() {}); grandChild1.$watch('a', function() {}); remove2 = grandChild2.$watch('a', function() {}); remove2(); expect(grandChild2.$$watchersCount).toBe(0); expect(child2.$$watchersCount).toBe(1); expect($rootScope.$$watchersCount).toBe(3); remove1(); expect(grandChild1.$$watchersCount).toBe(1); expect(child1.$$watchersCount).toBe(1); expect($rootScope.$$watchersCount).toBe(2); // Execute everything a second time to be sure that calling the remove function // several times, it only decrements the counter once remove2(); expect(child2.$$watchersCount).toBe(1); expect($rootScope.$$watchersCount).toBe(2); remove1(); expect(child1.$$watchersCount).toBe(1); expect($rootScope.$$watchersCount).toBe(2); })); it('should not keep constant literals on the watch queue', inject(function($rootScope) { $rootScope.$watch('[]', function() {}); $rootScope.$watch('{}', function() {}); expect($rootScope.$$watchers.length).toEqual(2); $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(0); })); it('should clean up stable watches on the watch queue', inject(function($rootScope) { $rootScope.$watch('::foo', function() {}); expect($rootScope.$$watchers.length).toEqual(1); $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(1); $rootScope.foo = 'foo'; $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(0); })); it('should clean up stable watches from $watchCollection', inject(function($rootScope) { $rootScope.$watchCollection('::foo', function() {}); expect($rootScope.$$watchers.length).toEqual(1); $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(1); $rootScope.foo = []; $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(0); })); it('should clean up stable watches from $watchGroup', inject(function($rootScope) { $rootScope.$watchGroup(['::foo', '::bar'], function() {}); expect($rootScope.$$watchers.length).toEqual(2); $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(2); $rootScope.foo = 'foo'; $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(1); $rootScope.bar = 'bar'; $rootScope.$digest(); expect($rootScope.$$watchers.length).toEqual(0); })); it('should delegate exceptions', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($rootScope, $exceptionHandler, $log) { $rootScope.$watch('a', function() {throw new Error('abc');}); $rootScope.a = 1; $rootScope.$digest(); expect($exceptionHandler.errors[0].message).toEqual('abc'); $log.assertEmpty(); }); }); it('should fire watches in order of addition', inject(function($rootScope) { // this is not an external guarantee, just our own sanity var log = ''; $rootScope.$watch('a', function() { log += 'a'; }); $rootScope.$watch('b', function() { log += 'b'; }); // constant expressions have slightly different handling, // let's ensure they are kept in the same list as others $rootScope.$watch('1', function() { log += '1'; }); $rootScope.$watch('c', function() { log += 'c'; }); $rootScope.$watch('2', function() { log += '2'; }); $rootScope.a = $rootScope.b = $rootScope.c = 1; $rootScope.$digest(); expect(log).toEqual('ab1c2'); })); it('should call child $watchers in addition order', inject(function($rootScope) { // this is not an external guarantee, just our own sanity var log = ''; var childA = $rootScope.$new(); var childB = $rootScope.$new(); var childC = $rootScope.$new(); childA.$watch('a', function() { log += 'a'; }); childB.$watch('b', function() { log += 'b'; }); childC.$watch('c', function() { log += 'c'; }); childA.a = childB.b = childC.c = 1; $rootScope.$digest(); expect(log).toEqual('abc'); })); it('should allow $digest on a child scope with and without a right sibling', inject( function($rootScope) { // tests a traversal edge case which we originally missed var log = '', childA = $rootScope.$new(), childB = $rootScope.$new(); $rootScope.$watch(function() { log += 'r'; }); childA.$watch(function() { log += 'a'; }); childB.$watch(function() { log += 'b'; }); // init $rootScope.$digest(); expect(log).toBe('rabrab'); log = ''; childA.$digest(); expect(log).toBe('a'); log = ''; childB.$digest(); expect(log).toBe('b'); })); it('should repeat watch cycle while model changes are identified', inject(function($rootScope) { var log = ''; $rootScope.$watch('c', function(v) {$rootScope.d = v; log += 'c'; }); $rootScope.$watch('b', function(v) {$rootScope.c = v; log += 'b'; }); $rootScope.$watch('a', function(v) {$rootScope.b = v; log += 'a'; }); $rootScope.$digest(); log = ''; $rootScope.a = 1; $rootScope.$digest(); expect($rootScope.b).toEqual(1); expect($rootScope.c).toEqual(1); expect($rootScope.d).toEqual(1); expect(log).toEqual('abc'); })); it('should repeat watch cycle from the root element', inject(function($rootScope) { var log = ''; var child = $rootScope.$new(); $rootScope.$watch(function() { log += 'a'; }); child.$watch(function() { log += 'b'; }); $rootScope.$digest(); expect(log).toEqual('abab'); })); it('should prevent infinite recursion and print watcher expression',function() { module(function($rootScopeProvider) { $rootScopeProvider.digestTtl(100); }); inject(function($rootScope) { $rootScope.$watch('a', function() {$rootScope.b++;}); $rootScope.$watch('b', function() {$rootScope.a++;}); $rootScope.a = $rootScope.b = 0; expect(function() { $rootScope.$digest(); }).toThrowMinErr('$rootScope', 'infdig', '100 $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + '[[{"msg":"a","newVal":96,"oldVal":95},{"msg":"b","newVal":97,"oldVal":96}],' + '[{"msg":"a","newVal":97,"oldVal":96},{"msg":"b","newVal":98,"oldVal":97}],' + '[{"msg":"a","newVal":98,"oldVal":97},{"msg":"b","newVal":99,"oldVal":98}],' + '[{"msg":"a","newVal":99,"oldVal":98},{"msg":"b","newVal":100,"oldVal":99}],' + '[{"msg":"a","newVal":100,"oldVal":99},{"msg":"b","newVal":101,"oldVal":100}]]'); expect($rootScope.$$phase).toBeNull(); }); }); it('should prevent infinite recursion and print watcher function name or body', inject(function($rootScope) { $rootScope.$watch(function watcherA() {return $rootScope.a;}, function() {$rootScope.b++;}); $rootScope.$watch(function() {return $rootScope.b;}, function() {$rootScope.a++;}); $rootScope.a = $rootScope.b = 0; try { $rootScope.$digest(); throw new Error('Should have thrown exception'); } catch (e) { expect(e.message.match(/"fn: (watcherA|function)/g).length).toBe(10); } })); it('should prevent infinite loop when creating and resolving a promise in a watched expression', function() { module(function($rootScopeProvider) { $rootScopeProvider.digestTtl(10); }); inject(function($rootScope, $q) { var d = $q.defer(); d.resolve('Hello, world.'); $rootScope.$watch(function() { var $d2 = $q.defer(); $d2.resolve('Goodbye.'); $d2.promise.then(function() { }); return d.promise; }, function() { return 0; }); expect(function() { $rootScope.$digest(); }).toThrowMinErr('$rootScope', 'infdig', '10 $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: []'); expect($rootScope.$$phase).toBeNull(); }); }); it('should not fire upon $watch registration on initial $digest', inject(function($rootScope) { var log = ''; $rootScope.a = 1; $rootScope.$watch('a', function() { log += 'a'; }); $rootScope.$watch('b', function() { log += 'b'; }); $rootScope.$digest(); log = ''; $rootScope.$digest(); expect(log).toEqual(''); })); it('should watch objects', inject(function($rootScope) { var log = ''; $rootScope.a = []; $rootScope.b = {}; $rootScope.$watch('a', function(value) { log += '.'; expect(value).toBe($rootScope.a); }, true); $rootScope.$watch('b', function(value) { log += '!'; expect(value).toBe($rootScope.b); }, true); $rootScope.$digest(); log = ''; $rootScope.a.push({}); $rootScope.b.name = ''; $rootScope.$digest(); expect(log).toEqual('.!'); })); it('should watch functions', function() { module(provideLog); inject(function($rootScope, log) { $rootScope.fn = function() {return 'a';}; $rootScope.$watch('fn', function(fn) { log(fn()); }); $rootScope.$digest(); expect(log).toEqual('a'); $rootScope.fn = function() {return 'b';}; $rootScope.$digest(); expect(log).toEqual('a; b'); }); }); it('should prevent $digest recursion', inject(function($rootScope) { var callCount = 0; $rootScope.$watch('name', function() { expect(function() { $rootScope.$digest(); }).toThrowMinErr('$rootScope', 'inprog', '$digest already in progress'); callCount++; }); $rootScope.name = 'a'; $rootScope.$digest(); expect(callCount).toEqual(1); })); it('should allow a watch to be added while in a digest', inject(function($rootScope) { var watch1 = jasmine.createSpy('watch1'), watch2 = jasmine.createSpy('watch2'); $rootScope.$watch('foo', function() { $rootScope.$watch('foo', watch1); $rootScope.$watch('foo', watch2); }); $rootScope.$apply('foo = true'); expect(watch1).toHaveBeenCalled(); expect(watch2).toHaveBeenCalled(); })); it('should not infinitely digest when current value is NaN', inject(function($rootScope) { $rootScope.$watch(function() { return NaN;}); expect(function() { $rootScope.$digest(); }).not.toThrow(); })); it('should always call the watcher with newVal and oldVal equal on the first run', inject(function($rootScope) { var log = []; function logger(scope, newVal, oldVal) { var val = (newVal === oldVal || (newVal !== oldVal && oldVal !== newVal)) ? newVal : 'xxx'; log.push(val); } $rootScope.$watch(function() { return NaN;}, logger); $rootScope.$watch(function() { return undefined;}, logger); $rootScope.$watch(function() { return '';}, logger); $rootScope.$watch(function() { return false;}, logger); $rootScope.$watch(function() { return {};}, logger, true); $rootScope.$watch(function() { return 23;}, logger); $rootScope.$digest(); expect(isNaN(log.shift())).toBe(true); //jasmine's toBe and toEqual don't work well with NaNs expect(log).toEqual([undefined, '', false, {}, 23]); log = []; $rootScope.$digest(); expect(log).toEqual([]); })); describe('$watch deregistration', function() { it('should return a function that allows listeners to be deregistered', inject( function($rootScope) { var listener = jasmine.createSpy('watch listener'), listenerRemove; listenerRemove = $rootScope.$watch('foo', listener); $rootScope.$digest(); //init expect(listener).toHaveBeenCalled(); expect(listenerRemove).toBeDefined(); listener.calls.reset(); $rootScope.foo = 'bar'; $rootScope.$digest(); //trigger expect(listener).toHaveBeenCalledOnce(); listener.calls.reset(); $rootScope.foo = 'baz'; listenerRemove(); $rootScope.$digest(); //trigger expect(listener).not.toHaveBeenCalled(); })); it('should allow a watch to be deregistered while in a digest', inject(function($rootScope) { var remove1, remove2; $rootScope.$watch('remove', function() { remove1(); remove2(); }); remove1 = $rootScope.$watch('thing', function() {}); remove2 = $rootScope.$watch('thing', function() {}); expect(function() { $rootScope.$apply('remove = true'); }).not.toThrow(); })); it('should not mess up the digest loop if deregistration happens during digest', inject( function($rootScope, log) { // we are testing this due to regression #5525 which is related to how the digest loops lastDirtyWatch // short-circuiting optimization works // scenario: watch1 deregistering watch1 var scope = $rootScope.$new(); var deregWatch1 = scope.$watch(log.fn('watch1'), function() { deregWatch1(); log('watchAction1'); }); scope.$watch(log.fn('watch2'), log.fn('watchAction2')); scope.$watch(log.fn('watch3'), log.fn('watchAction3')); $rootScope.$digest(); expect(log).toEqual(['watch1', 'watchAction1', 'watch2', 'watchAction2', 'watch3', 'watchAction3', 'watch2', 'watch3']); scope.$destroy(); log.reset(); // scenario: watch1 deregistering watch2 scope = $rootScope.$new(); scope.$watch(log.fn('watch1'), function() { deregWatch2(); log('watchAction1'); }); var deregWatch2 = scope.$watch(log.fn('watch2'), log.fn('watchAction2')); scope.$watch(log.fn('watch3'), log.fn('watchAction3')); $rootScope.$digest(); expect(log).toEqual(['watch1', 'watchAction1', 'watch1', 'watch3', 'watchAction3', 'watch1', 'watch3']); scope.$destroy(); log.reset(); // scenario: watch2 deregistering watch1 scope = $rootScope.$new(); deregWatch1 = scope.$watch(log.fn('watch1'), log.fn('watchAction1')); scope.$watch(log.fn('watch2'), function() { deregWatch1(); log('watchAction2'); }); scope.$watch(log.fn('watch3'), log.fn('watchAction3')); $rootScope.$digest(); expect(log).toEqual(['watch1', 'watchAction1', 'watch2', 'watchAction2', 'watch3', 'watchAction3', 'watch2', 'watch3']); })); }); describe('$watchCollection', function() { var log, $rootScope, deregister; beforeEach(inject(function(_$rootScope_, _log_) { $rootScope = _$rootScope_; log = _log_; deregister = $rootScope.$watchCollection('obj', function logger(newVal, oldVal) { var msg = {newVal: newVal, oldVal: oldVal}; if (newVal === oldVal) { msg.identical = true; } log(msg); }); })); it('should not trigger if nothing change', inject(function($rootScope) { $rootScope.$digest(); expect(log).toEqual([{ newVal: undefined, oldVal: undefined, identical: true }]); log.reset(); $rootScope.$digest(); expect(log).toEqual([]); })); it('should allow deregistration', function() { $rootScope.obj = []; $rootScope.$digest(); expect(log.toArray().length).toBe(1); log.reset(); $rootScope.obj.push('a'); deregister(); $rootScope.$digest(); expect(log).toEqual([]); }); describe('array', function() { it('should return oldCollection === newCollection only on the first listener call', inject(function($rootScope, log) { // first time should be identical $rootScope.obj = ['a', 'b']; $rootScope.$digest(); expect(log).toEqual([{newVal: ['a', 'b'], oldVal: ['a', 'b'], identical: true}]); log.reset(); // second time should be different $rootScope.obj[1] = 'c'; $rootScope.$digest(); expect(log).toEqual([{newVal: ['a', 'c'], oldVal: ['a', 'b']}]); })); it('should trigger when property changes into array', function() { $rootScope.obj = 'test'; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: 'test', oldVal: 'test', identical: true}]); $rootScope.obj = []; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: [], oldVal: 'test'}]); $rootScope.obj = {}; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {}, oldVal: []}]); $rootScope.obj = []; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: [], oldVal: {}}]); $rootScope.obj = undefined; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: undefined, oldVal: []}]); }); it('should not trigger change when object in collection changes', function() { $rootScope.obj = [{}]; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: [{}], oldVal: [{}], identical: true}]); $rootScope.obj[0].name = 'foo'; $rootScope.$digest(); expect(log).toEqual([]); }); it('should watch array properties', function() { $rootScope.obj = []; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: [], oldVal: [], identical: true}]); $rootScope.obj.push('a'); $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: ['a'], oldVal: []}]); $rootScope.obj[0] = 'b'; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: ['b'], oldVal: ['a']}]); $rootScope.obj.push([]); $rootScope.obj.push({}); $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: ['b', [], {}], oldVal: ['b']}]); var temp = $rootScope.obj[1]; $rootScope.obj[1] = $rootScope.obj[2]; $rootScope.obj[2] = temp; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: ['b', {}, []], oldVal: ['b', [], {}]}]); $rootScope.obj.shift(); $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: [{}, []], oldVal: ['b', {}, []]}]); }); it('should not infinitely digest when current value is NaN', function() { $rootScope.obj = [NaN]; expect(function() { $rootScope.$digest(); }).not.toThrow(); }); it('should watch array-like objects like arrays', function() { var arrayLikelog = []; $rootScope.$watchCollection('arrayLikeObject', function logger(obj) { forEach(obj, function(element) { arrayLikelog.push(element.name); }); }); window.document.body.innerHTML = '<p>' + '<a name=\'x\'>a</a>' + '<a name=\'y\'>b</a>' + '</p>'; $rootScope.arrayLikeObject = window.document.getElementsByTagName('a'); $rootScope.$digest(); expect(arrayLikelog).toEqual(['x', 'y']); }); }); describe('object', function() { it('should return oldCollection === newCollection only on the first listener call', inject(function($rootScope, log) { $rootScope.obj = {'a': 'b'}; // first time should be identical $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {'a': 'b'}, oldVal: {'a': 'b'}, identical: true}]); // second time not identical $rootScope.obj.a = 'c'; $rootScope.$digest(); expect(log).toEqual([{newVal: {'a': 'c'}, oldVal: {'a': 'b'}}]); })); it('should trigger when property changes into object', function() { $rootScope.obj = 'test'; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: 'test', oldVal: 'test', identical: true}]); $rootScope.obj = {}; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {}, oldVal: 'test'}]); }); it('should not trigger change when object in collection changes', function() { $rootScope.obj = {name: {}}; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {name: {}}, oldVal: {name: {}}, identical: true}]); $rootScope.obj.name.bar = 'foo'; $rootScope.$digest(); expect(log.empty()).toEqual([]); }); it('should watch object properties', function() { $rootScope.obj = {}; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {}, oldVal: {}, identical: true}]); $rootScope.obj.a = 'A'; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {a: 'A'}, oldVal: {}}]); $rootScope.obj.a = 'B'; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {a: 'B'}, oldVal: {a: 'A'}}]); $rootScope.obj.b = []; $rootScope.obj.c = {}; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {a: 'B', b: [], c: {}}, oldVal: {a: 'B'}}]); var temp = $rootScope.obj.a; $rootScope.obj.a = $rootScope.obj.b; $rootScope.obj.c = temp; $rootScope.$digest(); expect(log.empty()). toEqual([{newVal: {a: [], b: [], c: 'B'}, oldVal: {a: 'B', b: [], c: {}}}]); delete $rootScope.obj.a; $rootScope.$digest(); expect(log.empty()).toEqual([{newVal: {b: [], c: 'B'}, oldVal: {a: [], b: [], c: 'B'}}]); }); it('should not infinitely digest when current value is NaN', function() { $rootScope.obj = {a: NaN}; expect(function() { $rootScope.$digest(); }).not.toThrow(); }); it('should handle objects created using `Object.create(null)`', function() { $rootScope.obj = Object.create(null); $rootScope.obj.a = 'a'; $rootScope.obj.b = 'b'; $rootScope.$digest(); expect(log.empty()[0].newVal).toEqual(extend(Object.create(null), {a: 'a', b: 'b'})); delete $rootScope.obj.b; $rootScope.$digest(); expect(log.empty()[0].newVal).toEqual(extend(Object.create(null), {a: 'a'})); }); }); }); describe('optimizations', function() { function setupWatches(scope, log) { scope.$watch(function() { log('w1'); return scope.w1; }, log.fn('w1action')); scope.$watch(function() { log('w2'); return scope.w2; }, log.fn('w2action')); scope.$watch(function() { log('w3'); return scope.w3; }, log.fn('w3action')); scope.$digest(); log.reset(); } it('should check watches only once during an empty digest', inject(function(log, $rootScope) { setupWatches($rootScope, log); $rootScope.$digest(); expect(log).toEqual(['w1', 'w2', 'w3']); })); it('should quit digest early after we check the last watch that was previously dirty', inject(function(log, $rootScope) { setupWatches($rootScope, log); $rootScope.w1 = 'x'; $rootScope.$digest(); expect(log).toEqual(['w1', 'w1action', 'w2', 'w3', 'w1']); })); it('should not quit digest early if a new watch was added from an existing watch action', inject(function(log, $rootScope) { setupWatches($rootScope, log); $rootScope.$watch(log.fn('w4'), function() { log('w4action'); $rootScope.$watch(log.fn('w5'), log.fn('w5action')); }); $rootScope.$digest(); expect(log).toEqual(['w1', 'w2', 'w3', 'w4', 'w4action', 'w1', 'w2', 'w3', 'w4', 'w5', 'w5action', 'w1', 'w2', 'w3', 'w4', 'w5']); })); it('should not quit digest early if an evalAsync task was scheduled from a watch action', inject(function(log, $rootScope) { setupWatches($rootScope, log); $rootScope.$watch(log.fn('w4'), function() { log('w4action'); $rootScope.$evalAsync(function() { log('evalAsync'); }); }); $rootScope.$digest(); expect(log).toEqual(['w1', 'w2', 'w3', 'w4', 'w4action', 'evalAsync', 'w1', 'w2', 'w3', 'w4']); })); it('should quit digest early but not too early when various watches fire', inject(function(log, $rootScope) { setupWatches($rootScope, log); $rootScope.$watch(function() { log('w4'); return $rootScope.w4; }, function(newVal) { log('w4action'); $rootScope.w2 = newVal; }); $rootScope.$digest(); log.reset(); $rootScope.w1 = 'x'; $rootScope.w4 = 'x'; $rootScope.$digest(); expect(log).toEqual(['w1', 'w1action', 'w2', 'w3', 'w4', 'w4action', 'w1', 'w2', 'w2action', 'w3', 'w4', 'w1', 'w2']); })); }); }); describe('$watchGroup', function() { var scope; var log; beforeEach(inject(function($rootScope, _log_) { scope = $rootScope.$new(); log = _log_; })); it('should detect a change to any one expression in the group', function() { scope.$watchGroup(['a', 'b'], function(values, oldValues, s) { expect(s).toBe(scope); log(oldValues + ' >>> ' + values); }); scope.a = 'foo'; scope.b = 'bar'; scope.$digest(); expect(log).toEqual('foo,bar >>> foo,bar'); log.reset(); scope.$digest(); expect(log).toEqual(''); scope.a = 'a'; scope.$digest(); expect(log).toEqual('foo,bar >>> a,bar'); log.reset(); scope.a = 'A'; scope.b = 'B'; scope.$digest(); expect(log).toEqual('a,bar >>> A,B'); }); it('should work for a group with just a single expression', function() { scope.$watchGroup(['a'], function(values, oldValues, s) { expect(s).toBe(scope); log(oldValues + ' >>> ' + values); }); scope.a = 'foo'; scope.$digest(); expect(log).toEqual('foo >>> foo'); log.reset(); scope.$digest(); expect(log).toEqual(''); scope.a = 'bar'; scope.$digest(); expect(log).toEqual('foo >>> bar'); }); it('should call the listener once when the array of watchExpressions is empty', function() { scope.$watchGroup([], function(values, oldValues) { log(oldValues + ' >>> ' + values); }); expect(log).toEqual(''); scope.$digest(); expect(log).toEqual(' >>> '); log.reset(); scope.$digest(); expect(log).toEqual(''); }); it('should not call watch action fn when watchGroup was deregistered', function() { var deregisterMany = scope.$watchGroup(['a', 'b'], function(values, oldValues) { log(oldValues + ' >>> ' + values); }), deregisterOne = scope.$watchGroup(['a'], function(values, oldValues) { log(oldValues + ' >>> ' + values); }), deregisterNone = scope.$watchGroup([], function(values, oldValues) { log(oldValues + ' >>> ' + values); }); deregisterMany(); deregisterOne(); deregisterNone(); scope.a = 'xxx'; scope.b = 'yyy'; scope.$digest(); expect(log).toEqual(''); }); }); describe('$destroy', function() { var first = null, middle = null, last = null, log = null; beforeEach(inject(function($rootScope) { log = ''; first = $rootScope.$new(); middle = $rootScope.$new(); last = $rootScope.$new(); first.$watch(function() { log += '1';}); middle.$watch(function() { log += '2';}); last.$watch(function() { log += '3';}); $rootScope.$digest(); log = ''; })); it('should broadcast $destroy on rootScope', inject(function($rootScope) { var spy = jasmine.createSpy('$destroy handler'); $rootScope.$on('$destroy', spy); $rootScope.$destroy(); expect(spy).toHaveBeenCalled(); expect($rootScope.$$destroyed).toBe(true); })); it('should remove all listeners after $destroy of rootScope', inject(function($rootScope) { var spy = jasmine.createSpy('$destroy handler'); $rootScope.$on('dummy', spy); $rootScope.$destroy(); $rootScope.$broadcast('dummy'); expect(spy).not.toHaveBeenCalled(); })); it('should remove all watchers after $destroy of rootScope', inject(function($rootScope) { var spy = jasmine.createSpy('$watch spy'); var digest = $rootScope.$digest; $rootScope.$watch(spy); $rootScope.$destroy(); digest.call($rootScope); expect(spy).not.toHaveBeenCalled(); })); it('should call $browser.$$applicationDestroyed when destroying rootScope', inject(function($rootScope, $browser) { spyOn($browser, '$$applicationDestroyed'); $rootScope.$destroy(); expect($browser.$$applicationDestroyed).toHaveBeenCalledOnce(); })); it('should remove first', inject(function($rootScope) { first.$destroy(); $rootScope.$digest(); expect(log).toEqual('23'); })); it('should remove middle', inject(function($rootScope) { middle.$destroy(); $rootScope.$digest(); expect(log).toEqual('13'); })); it('should remove last', inject(function($rootScope) { last.$destroy(); $rootScope.$digest(); expect(log).toEqual('12'); })); it('should broadcast the $destroy event', inject(function($rootScope, log) { first.$on('$destroy', log.fn('first')); first.$new().$on('$destroy', log.fn('first-child')); first.$destroy(); expect(log).toEqual('first; first-child'); })); it('should $destroy a scope only once and ignore any further destroy calls', inject(function($rootScope) { $rootScope.$digest(); expect(log).toBe('123'); first.$destroy(); // once a scope is destroyed apply should not do anything any more first.$apply(); expect(log).toBe('123'); first.$destroy(); first.$destroy(); first.$apply(); expect(log).toBe('123'); })); it('should broadcast the $destroy only once', inject(function($rootScope, log) { var isolateScope = first.$new(true); isolateScope.$on('$destroy', log.fn('event')); first.$destroy(); isolateScope.$destroy(); expect(log).toEqual('event'); })); it('should decrement ancestor $$listenerCount entries', inject(function($rootScope) { var EVENT = 'fooEvent', spy = jasmine.createSpy('listener'), firstSecond = first.$new(); firstSecond.$on(EVENT, spy); firstSecond.$on(EVENT, spy); middle.$on(EVENT, spy); expect($rootScope.$$listenerCount[EVENT]).toBe(3); expect(first.$$listenerCount[EVENT]).toBe(2); firstSecond.$destroy(); expect($rootScope.$$listenerCount[EVENT]).toBe(1); expect(first.$$listenerCount[EVENT]).toBeUndefined(); $rootScope.$broadcast(EVENT); expect(spy).toHaveBeenCalledTimes(1); })); it('should do nothing when a child event listener is registered after parent\'s destruction', inject(function($rootScope) { var parent = $rootScope.$new(), child = parent.$new(); parent.$destroy(); var fn = child.$on('someEvent', function() {}); expect(fn).toBe(noop); })); it('should do nothing when a child watch is registered after parent\'s destruction', inject(function($rootScope) { var parent = $rootScope.$new(), child = parent.$new(); parent.$destroy(); var fn = child.$watch('somePath', function() {}); expect(fn).toBe(noop); })); it('should do nothing when $apply()ing after parent\'s destruction', inject(function($rootScope) { var parent = $rootScope.$new(), child = parent.$new(); parent.$destroy(); var called = false; function applyFunc() { called = true; } child.$apply(applyFunc); expect(called).toBe(false); })); it('should do nothing when $evalAsync()ing after parent\'s destruction', inject(function($rootScope, $timeout) { var parent = $rootScope.$new(), child = parent.$new(); parent.$destroy(); var called = false; function applyFunc() { called = true; } child.$evalAsync(applyFunc); $timeout.verifyNoPendingTasks(); expect(called).toBe(false); })); it('should preserve all (own and inherited) model properties on a destroyed scope', inject(function($rootScope) { // This test simulates an async task (xhr response) interacting with the scope after the scope // was destroyed. Since we can't abort the request, we should ensure that the task doesn't // throw NPEs because the scope was cleaned up during destruction. var parent = $rootScope.$new(), child = parent.$new(); parent.parentModel = 'parent'; child.childModel = 'child'; child.$destroy(); expect(child.parentModel).toBe('parent'); expect(child.childModel).toBe('child'); })); if (msie === 9) { // See issue https://github.com/angular/angular.js/issues/10706 it('should completely disconnect all child scopes on IE9', inject(function($rootScope) { var parent = $rootScope.$new(), child1 = parent.$new(), child2 = parent.$new(), grandChild1 = child1.$new(), grandChild2 = child1.$new(); child1.$destroy(); $rootScope.$digest(); expect(isDisconnected(parent)).toBe(false); expect(isDisconnected(child1)).toBe(true); expect(isDisconnected(child2)).toBe(false); expect(isDisconnected(grandChild1)).toBe(true); expect(isDisconnected(grandChild2)).toBe(true); function isDisconnected($scope) { return $scope.$$nextSibling === null && $scope.$$prevSibling === null && $scope.$$childHead === null && $scope.$$childTail === null && $scope.$root === null && $scope.$$watchers === null; } })); } }); describe('$eval', function() { it('should eval an expression', inject(function($rootScope) { expect($rootScope.$eval('a=1')).toEqual(1); expect($rootScope.a).toEqual(1); $rootScope.$eval(function(self) {self.b = 2;}); expect($rootScope.b).toEqual(2); })); it('should allow passing locals to the expression', inject(function($rootScope) { expect($rootScope.$eval('a+1', {a: 2})).toBe(3); $rootScope.$eval(function(scope, locals) { scope.c = locals.b + 4; }, {b: 3}); expect($rootScope.c).toBe(7); })); }); describe('$evalAsync', function() { it('should run callback before $watch', inject(function($rootScope) { var log = ''; var child = $rootScope.$new(); $rootScope.$evalAsync(function(scope) { log += 'parent.async;'; }); $rootScope.$watch('value', function() { log += 'parent.$digest;'; }); child.$evalAsync(function(scope) { log += 'child.async;'; }); child.$watch('value', function() { log += 'child.$digest;'; }); $rootScope.$digest(); expect(log).toEqual('parent.async;child.async;parent.$digest;child.$digest;'); })); it('should not run another digest for an $$postDigest call', inject(function($rootScope) { var internalWatchCount = 0; var externalWatchCount = 0; $rootScope.internalCount = 0; $rootScope.externalCount = 0; $rootScope.$evalAsync(function(scope) { $rootScope.internalCount++; }); $rootScope.$$postDigest(function(scope) { $rootScope.externalCount++; }); $rootScope.$watch('internalCount', function(value) { internalWatchCount = value; }); $rootScope.$watch('externalCount', function(value) { externalWatchCount = value; }); $rootScope.$digest(); expect(internalWatchCount).toEqual(1); expect(externalWatchCount).toEqual(0); })); it('should cause a $digest rerun', inject(function($rootScope) { $rootScope.log = ''; $rootScope.value = 0; $rootScope.$watch('value', function() { $rootScope.log = $rootScope.log + '.'; }); $rootScope.$watch('init', function() { $rootScope.$evalAsync('value = 123; log = log + "=" '); expect($rootScope.value).toEqual(0); }); $rootScope.$digest(); expect($rootScope.log).toEqual('.=.'); })); it('should run async in the same order as added', inject(function($rootScope) { $rootScope.log = ''; $rootScope.$evalAsync('log = log + 1'); $rootScope.$evalAsync('log = log + 2'); $rootScope.$digest(); expect($rootScope.log).toBe('12'); })); it('should allow passing locals to the expression', inject(function($rootScope) { $rootScope.log = ''; $rootScope.$evalAsync('log = log + a', {a: 1}); $rootScope.$digest(); expect($rootScope.log).toBe('1'); })); it('should run async expressions in their proper context', inject(function($rootScope) { var child = $rootScope.$new(); $rootScope.ctx = 'root context'; $rootScope.log = ''; child.ctx = 'child context'; child.log = ''; child.$evalAsync('log=ctx'); $rootScope.$digest(); expect($rootScope.log).toBe(''); expect(child.log).toBe('child context'); })); it('should operate only with a single queue across all child and isolate scopes', inject(function($rootScope, $parse) { var childScope = $rootScope.$new(); var isolateScope = $rootScope.$new(true); $rootScope.$evalAsync('rootExpression'); childScope.$evalAsync('childExpression'); isolateScope.$evalAsync('isolateExpression'); expect(childScope.$$asyncQueue).toBe($rootScope.$$asyncQueue); expect(isolateScope.$$asyncQueue).toBeUndefined(); expect($rootScope.$$asyncQueue).toEqual([ {scope: $rootScope, expression: $parse('rootExpression'), locals: undefined}, {scope: childScope, expression: $parse('childExpression'), locals: undefined}, {scope: isolateScope, expression: $parse('isolateExpression'), locals: undefined} ]); })); describe('auto-flushing when queueing outside of an $apply', function() { var log, $rootScope, $browser; beforeEach(inject(function(_log_, _$rootScope_, _$browser_) { log = _log_; $rootScope = _$rootScope_; $browser = _$browser_; })); it('should auto-flush the queue asynchronously and trigger digest', function() { $rootScope.$evalAsync(log.fn('eval-ed!')); $rootScope.$watch(log.fn('digesting')); expect(log).toEqual([]); $browser.defer.flush(0); expect(log).toEqual(['eval-ed!', 'digesting', 'digesting']); }); it('should not trigger digest asynchronously if the queue is empty in the next tick', function() { $rootScope.$evalAsync(log.fn('eval-ed!')); $rootScope.$watch(log.fn('digesting')); expect(log).toEqual([]); $rootScope.$digest(); expect(log).toEqual(['eval-ed!', 'digesting', 'digesting']); log.reset(); $browser.defer.flush(0); expect(log).toEqual([]); }); it('should not schedule more than one auto-flush task', function() { $rootScope.$evalAsync(log.fn('eval-ed 1!')); $rootScope.$evalAsync(log.fn('eval-ed 2!')); $browser.defer.flush(0); expect(log).toEqual(['eval-ed 1!', 'eval-ed 2!']); $browser.defer.flush(100000); expect(log).toEqual(['eval-ed 1!', 'eval-ed 2!']); }); }); }); describe('$apply', function() { it('should apply expression with full lifecycle', inject(function($rootScope) { var log = ''; var child = $rootScope.$new(); $rootScope.$watch('a', function(a) { log += '1'; }); child.$apply('$parent.a=0'); expect(log).toEqual('1'); })); it('should catch exceptions', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($rootScope, $exceptionHandler, $log) { var log = ''; var child = $rootScope.$new(); $rootScope.$watch('a', function(a) { log += '1'; }); $rootScope.a = 0; child.$apply(function() { throw new Error('MyError'); }); expect(log).toEqual('1'); expect($exceptionHandler.errors[0].message).toEqual('MyError'); $log.error.logs.shift(); }); }); it('should log exceptions from $digest', function() { module(function($rootScopeProvider, $exceptionHandlerProvider) { $rootScopeProvider.digestTtl(2); $exceptionHandlerProvider.mode('log'); }); inject(function($rootScope, $exceptionHandler) { $rootScope.$watch('a', function() {$rootScope.b++;}); $rootScope.$watch('b', function() {$rootScope.a++;}); $rootScope.a = $rootScope.b = 0; expect(function() { $rootScope.$apply(); }).toThrow(); expect($exceptionHandler.errors[0]).toBeDefined(); expect($rootScope.$$phase).toBeNull(); }); }); describe('exceptions', function() { var log; beforeEach(module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); })); beforeEach(inject(function($rootScope) { log = ''; $rootScope.$watch(function() { log += '$digest;'; }); $rootScope.$digest(); log = ''; })); it('should execute and return value and update', inject( function($rootScope, $exceptionHandler) { $rootScope.name = 'abc'; expect($rootScope.$apply(function(scope) { return scope.name; })).toEqual('abc'); expect(log).toEqual('$digest;'); expect($exceptionHandler.errors).toEqual([]); })); it('should catch exception and update', inject(function($rootScope, $exceptionHandler) { var error = new Error('MyError'); $rootScope.$apply(function() { throw error; }); expect(log).toEqual('$digest;'); expect($exceptionHandler.errors).toEqual([error]); })); }); describe('recursive $apply protection', function() { it('should throw an exception if $apply is called while an $apply is in progress', inject( function($rootScope) { expect(function() { $rootScope.$apply(function() { $rootScope.$apply(); }); }).toThrowMinErr('$rootScope', 'inprog', '$apply already in progress'); })); it('should not clear the state when calling $apply during an $apply', inject( function($rootScope) { $rootScope.$apply(function() { expect(function() { $rootScope.$apply(); }).toThrowMinErr('$rootScope', 'inprog', '$apply already in progress'); expect(function() { $rootScope.$apply(); }).toThrowMinErr('$rootScope', 'inprog', '$apply already in progress'); }); expect(function() { $rootScope.$apply(); }).not.toThrow(); })); it('should throw an exception if $apply is called while flushing evalAsync queue', inject( function($rootScope) { expect(function() { $rootScope.$apply(function() { $rootScope.$evalAsync(function() { $rootScope.$apply(); }); }); }).toThrowMinErr('$rootScope', 'inprog', '$digest already in progress'); })); it('should throw an exception if $apply is called while a watch is being initialized', inject( function($rootScope) { var childScope1 = $rootScope.$new(); childScope1.$watch('x', function() { childScope1.$apply(); }); expect(function() { childScope1.$apply(); }).toThrowMinErr('$rootScope', 'inprog', '$digest already in progress'); })); it('should thrown an exception if $apply in called from a watch fn (after init)', inject( function($rootScope) { var childScope2 = $rootScope.$new(); childScope2.$apply(function() { childScope2.$watch('x', function(newVal, oldVal) { if (newVal !== oldVal) { childScope2.$apply(); } }); }); expect(function() { childScope2.$apply(function() { childScope2.x = 'something'; }); }).toThrowMinErr('$rootScope', 'inprog', '$digest already in progress'); })); }); }); describe('$applyAsync', function() { beforeEach(module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); })); it('should evaluate in the context of specific $scope', inject(function($rootScope, $browser) { var scope = $rootScope.$new(); scope.$applyAsync('x = "CODE ORANGE"'); $browser.defer.flush(); expect(scope.x).toBe('CODE ORANGE'); expect($rootScope.x).toBeUndefined(); })); it('should evaluate queued expressions in order', inject(function($rootScope, $browser) { $rootScope.x = []; $rootScope.$applyAsync('x.push("expr1")'); $rootScope.$applyAsync('x.push("expr2")'); $browser.defer.flush(); expect($rootScope.x).toEqual(['expr1', 'expr2']); })); it('should evaluate subsequently queued items in same turn', inject(function($rootScope, $browser) { $rootScope.x = []; $rootScope.$applyAsync(function() { $rootScope.x.push('expr1'); $rootScope.$applyAsync('x.push("expr2")'); expect($browser.deferredFns.length).toBe(0); }); $browser.defer.flush(); expect($rootScope.x).toEqual(['expr1', 'expr2']); })); it('should pass thrown exceptions to $exceptionHandler', inject(function($rootScope, $browser, $exceptionHandler) { $rootScope.$applyAsync(function() { throw 'OOPS'; }); $browser.defer.flush(); expect($exceptionHandler.errors).toEqual([ 'OOPS' ]); })); it('should evaluate subsequent expressions after an exception is thrown', inject(function($rootScope, $browser) { $rootScope.$applyAsync(function() { throw 'OOPS'; }); $rootScope.$applyAsync('x = "All good!"'); $browser.defer.flush(); expect($rootScope.x).toBe('All good!'); })); it('should be cancelled if a $rootScope digest occurs before the next tick', inject(function($rootScope, $browser) { var apply = spyOn($rootScope, '$apply').and.callThrough(); var cancel = spyOn($browser.defer, 'cancel').and.callThrough(); var expression = jasmine.createSpy('expr'); $rootScope.$applyAsync(expression); $rootScope.$digest(); expect(expression).toHaveBeenCalledOnce(); expect(cancel).toHaveBeenCalledOnce(); expression.calls.reset(); cancel.calls.reset(); // assert that we no longer are waiting to execute expect($browser.deferredFns.length).toBe(0); // assert that another digest won't call the function again $rootScope.$digest(); expect(expression).not.toHaveBeenCalled(); expect(cancel).not.toHaveBeenCalled(); })); }); describe('$$postDigest', function() { it('should process callbacks as a queue (FIFO) when the scope is digested', inject(function($rootScope) { var signature = ''; $rootScope.$$postDigest(function() { signature += 'A'; $rootScope.$$postDigest(function() { signature += 'D'; }); }); $rootScope.$$postDigest(function() { signature += 'B'; }); $rootScope.$$postDigest(function() { signature += 'C'; }); expect(signature).toBe(''); $rootScope.$digest(); expect(signature).toBe('ABCD'); })); it('should support $apply calls nested in $$postDigest callbacks', inject(function($rootScope) { var signature = ''; $rootScope.$$postDigest(function() { signature += 'A'; }); $rootScope.$$postDigest(function() { signature += 'B'; $rootScope.$apply(); signature += 'D'; }); $rootScope.$$postDigest(function() { signature += 'C'; }); expect(signature).toBe(''); $rootScope.$digest(); expect(signature).toBe('ABCD'); })); it('should run a $$postDigest call on all child scopes when a parent scope is digested', inject(function($rootScope) { var parent = $rootScope.$new(), child = parent.$new(), count = 0; $rootScope.$$postDigest(function() { count++; }); parent.$$postDigest(function() { count++; }); child.$$postDigest(function() { count++; }); expect(count).toBe(0); $rootScope.$digest(); expect(count).toBe(3); })); it('should run a $$postDigest call even if the child scope is isolated', inject(function($rootScope) { var parent = $rootScope.$new(), child = parent.$new(true), signature = ''; parent.$$postDigest(function() { signature += 'A'; }); child.$$postDigest(function() { signature += 'B'; }); expect(signature).toBe(''); $rootScope.$digest(); expect(signature).toBe('AB'); })); }); describe('events', function() { describe('$on', function() { it('should add listener for both $emit and $broadcast events', inject(function($rootScope) { var log = '', child = $rootScope.$new(); function eventFn() { log += 'X'; } child.$on('abc', eventFn); expect(log).toEqual(''); child.$emit('abc'); expect(log).toEqual('X'); child.$broadcast('abc'); expect(log).toEqual('XX'); })); it('should increment ancestor $$listenerCount entries', inject(function($rootScope) { var child1 = $rootScope.$new(), child2 = child1.$new(), spy = jasmine.createSpy(); $rootScope.$on('event1', spy); expect($rootScope.$$listenerCount).toEqual({event1: 1}); child1.$on('event1', spy); expect($rootScope.$$listenerCount).toEqual({event1: 2}); expect(child1.$$listenerCount).toEqual({event1: 1}); child2.$on('event2', spy); expect($rootScope.$$listenerCount).toEqual({event1: 2, event2: 1}); expect(child1.$$listenerCount).toEqual({event1: 1, event2: 1}); expect(child2.$$listenerCount).toEqual({event2: 1}); })); describe('deregistration', function() { it('should return a function that deregisters the listener', inject(function($rootScope) { var log = '', child = $rootScope.$new(), listenerRemove; function eventFn() { log += 'X'; } listenerRemove = child.$on('abc', eventFn); expect(log).toEqual(''); expect(listenerRemove).toBeDefined(); child.$emit('abc'); child.$broadcast('abc'); expect(log).toEqual('XX'); expect($rootScope.$$listenerCount['abc']).toBe(1); log = ''; listenerRemove(); child.$emit('abc'); child.$broadcast('abc'); expect(log).toEqual(''); expect($rootScope.$$listenerCount['abc']).toBeUndefined(); })); it('should decrement ancestor $$listenerCount entries', inject(function($rootScope) { var child1 = $rootScope.$new(), child2 = child1.$new(), spy = jasmine.createSpy(); $rootScope.$on('event1', spy); expect($rootScope.$$listenerCount).toEqual({event1: 1}); child1.$on('event1', spy); expect($rootScope.$$listenerCount).toEqual({event1: 2}); expect(child1.$$listenerCount).toEqual({event1: 1}); var deregisterEvent2Listener = child2.$on('event2', spy); expect($rootScope.$$listenerCount).toEqual({event1: 2, event2: 1}); expect(child1.$$listenerCount).toEqual({event1: 1, event2: 1}); expect(child2.$$listenerCount).toEqual({event2: 1}); deregisterEvent2Listener(); expect($rootScope.$$listenerCount).toEqual({event1: 2}); expect(child1.$$listenerCount).toEqual({event1: 1}); expect(child2.$$listenerCount).toEqual({}); })); it('should not decrement $$listenerCount when called second time', inject(function($rootScope) { var child = $rootScope.$new(), listener1Spy = jasmine.createSpy(), listener2Spy = jasmine.createSpy(); child.$on('abc', listener1Spy); expect($rootScope.$$listenerCount).toEqual({abc: 1}); expect(child.$$listenerCount).toEqual({abc: 1}); var deregisterEventListener = child.$on('abc', listener2Spy); expect($rootScope.$$listenerCount).toEqual({abc: 2}); expect(child.$$listenerCount).toEqual({abc: 2}); deregisterEventListener(); expect($rootScope.$$listenerCount).toEqual({abc: 1}); expect(child.$$listenerCount).toEqual({abc: 1}); deregisterEventListener(); expect($rootScope.$$listenerCount).toEqual({abc: 1}); expect(child.$$listenerCount).toEqual({abc: 1}); })); }); }); describe('$emit', function() { var log, child, grandChild, greatGrandChild; function logger(event) { log += event.currentScope.id + '>'; } beforeEach(module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); })); beforeEach(inject(function($rootScope) { log = ''; child = $rootScope.$new(); grandChild = child.$new(); greatGrandChild = grandChild.$new(); $rootScope.id = 0; child.id = 1; grandChild.id = 2; greatGrandChild.id = 3; $rootScope.$on('myEvent', logger); child.$on('myEvent', logger); grandChild.$on('myEvent', logger); greatGrandChild.$on('myEvent', logger); })); it('should bubble event up to the root scope', function() { grandChild.$emit('myEvent'); expect(log).toEqual('2>1>0>'); }); it('should allow all events on the same scope to run even if stopPropagation is called', function() { child.$on('myEvent', logger); grandChild.$on('myEvent', function(e) { e.stopPropagation(); }); grandChild.$on('myEvent', logger); grandChild.$on('myEvent', logger); grandChild.$emit('myEvent'); expect(log).toEqual('2>2>2>'); }); it('should dispatch exceptions to the $exceptionHandler', inject(function($exceptionHandler) { child.$on('myEvent', function() { throw 'bubbleException'; }); grandChild.$emit('myEvent'); expect(log).toEqual('2>1>0>'); expect($exceptionHandler.errors).toEqual(['bubbleException']); })); it('should allow stopping event propagation', function() { child.$on('myEvent', function(event) { event.stopPropagation(); }); grandChild.$emit('myEvent'); expect(log).toEqual('2>1>'); }); it('should forward method arguments', function() { child.$on('abc', function(event, arg1, arg2) { expect(event.name).toBe('abc'); expect(arg1).toBe('arg1'); expect(arg2).toBe('arg2'); }); child.$emit('abc', 'arg1', 'arg2'); }); it('should allow removing event listener inside a listener on $emit', function() { var spy1 = jasmine.createSpy('1st listener'); var spy2 = jasmine.createSpy('2nd listener'); var spy3 = jasmine.createSpy('3rd listener'); var remove1 = child.$on('evt', spy1); var remove2 = child.$on('evt', spy2); var remove3 = child.$on('evt', spy3); spy1.and.callFake(remove1); expect(child.$$listeners['evt'].length).toBe(3); // should call all listeners and remove 1st child.$emit('evt'); expect(spy1).toHaveBeenCalledOnce(); expect(spy2).toHaveBeenCalledOnce(); expect(spy3).toHaveBeenCalledOnce(); expect(child.$$listeners['evt'].length).toBe(3); // cleanup will happen on next $emit spy1.calls.reset(); spy2.calls.reset(); spy3.calls.reset(); // should call only 2nd because 1st was already removed and 2nd removes 3rd spy2.and.callFake(remove3); child.$emit('evt'); expect(spy1).not.toHaveBeenCalled(); expect(spy2).toHaveBeenCalledOnce(); expect(spy3).not.toHaveBeenCalled(); expect(child.$$listeners['evt'].length).toBe(1); }); it('should allow removing event listener inside a listener on $broadcast', function() { var spy1 = jasmine.createSpy('1st listener'); var spy2 = jasmine.createSpy('2nd listener'); var spy3 = jasmine.createSpy('3rd listener'); var remove1 = child.$on('evt', spy1); var remove2 = child.$on('evt', spy2); var remove3 = child.$on('evt', spy3); spy1.and.callFake(remove1); expect(child.$$listeners['evt'].length).toBe(3); // should call all listeners and remove 1st child.$broadcast('evt'); expect(spy1).toHaveBeenCalledOnce(); expect(spy2).toHaveBeenCalledOnce(); expect(spy3).toHaveBeenCalledOnce(); expect(child.$$listeners['evt'].length).toBe(3); //cleanup will happen on next $broadcast spy1.calls.reset(); spy2.calls.reset(); spy3.calls.reset(); // should call only 2nd because 1st was already removed and 2nd removes 3rd spy2.and.callFake(remove3); child.$broadcast('evt'); expect(spy1).not.toHaveBeenCalled(); expect(spy2).toHaveBeenCalledOnce(); expect(spy3).not.toHaveBeenCalled(); expect(child.$$listeners['evt'].length).toBe(1); }); describe('event object', function() { it('should have methods/properties', function() { var eventFired = false; child.$on('myEvent', function(e) { expect(e.targetScope).toBe(grandChild); expect(e.currentScope).toBe(child); expect(e.name).toBe('myEvent'); eventFired = true; }); grandChild.$emit('myEvent'); expect(eventFired).toBe(true); }); it('should have its `currentScope` property set to null after emit', function() { var event; child.$on('myEvent', function(e) { event = e; }); grandChild.$emit('myEvent'); expect(event.currentScope).toBe(null); expect(event.targetScope).toBe(grandChild); expect(event.name).toBe('myEvent'); }); it('should have preventDefault method and defaultPrevented property', function() { var event = grandChild.$emit('myEvent'); expect(event.defaultPrevented).toBe(false); child.$on('myEvent', function(event) { event.preventDefault(); }); event = grandChild.$emit('myEvent'); expect(event.defaultPrevented).toBe(true); expect(event.currentScope).toBe(null); }); }); }); describe('$broadcast', function() { describe('event propagation', function() { var log, child1, child2, child3, grandChild11, grandChild21, grandChild22, grandChild23, greatGrandChild211; function logger(event) { log += event.currentScope.id + '>'; } beforeEach(inject(function($rootScope) { log = ''; child1 = $rootScope.$new(); child2 = $rootScope.$new(); child3 = $rootScope.$new(); grandChild11 = child1.$new(); grandChild21 = child2.$new(); grandChild22 = child2.$new(); grandChild23 = child2.$new(); greatGrandChild211 = grandChild21.$new(); $rootScope.id = 0; child1.id = 1; child2.id = 2; child3.id = 3; grandChild11.id = 11; grandChild21.id = 21; grandChild22.id = 22; grandChild23.id = 23; greatGrandChild211.id = 211; $rootScope.$on('myEvent', logger); child1.$on('myEvent', logger); child2.$on('myEvent', logger); child3.$on('myEvent', logger); grandChild11.$on('myEvent', logger); grandChild21.$on('myEvent', logger); grandChild22.$on('myEvent', logger); grandChild23.$on('myEvent', logger); greatGrandChild211.$on('myEvent', logger); // R // / | \ // 1 2 3 // / / | \ // 11 21 22 23 // | // 211 })); it('should broadcast an event from the root scope', inject(function($rootScope) { $rootScope.$broadcast('myEvent'); expect(log).toBe('0>1>11>2>21>211>22>23>3>'); })); it('should broadcast an event from a child scope', function() { child2.$broadcast('myEvent'); expect(log).toBe('2>21>211>22>23>'); }); it('should broadcast an event from a leaf scope with a sibling', function() { grandChild22.$broadcast('myEvent'); expect(log).toBe('22>'); }); it('should broadcast an event from a leaf scope without a sibling', function() { grandChild23.$broadcast('myEvent'); expect(log).toBe('23>'); }); it('should not not fire any listeners for other events', inject(function($rootScope) { $rootScope.$broadcast('fooEvent'); expect(log).toBe(''); })); it('should not descend past scopes with a $$listerCount of 0 or undefined', inject(function($rootScope) { var EVENT = 'fooEvent', spy = jasmine.createSpy('listener'); // Precondition: There should be no listeners for fooEvent. expect($rootScope.$$listenerCount[EVENT]).toBeUndefined(); // Add a spy listener to a child scope. $rootScope.$$childHead.$$listeners[EVENT] = [spy]; // $rootScope's count for 'fooEvent' is undefined, so spy should not be called. $rootScope.$broadcast(EVENT); expect(spy).not.toHaveBeenCalled(); })); it('should return event object', function() { var result = child1.$broadcast('some'); expect(result).toBeDefined(); expect(result.name).toBe('some'); expect(result.targetScope).toBe(child1); }); }); describe('listener', function() { it('should receive event object', inject(function($rootScope) { var scope = $rootScope, child = scope.$new(), eventFired = false; child.$on('fooEvent', function(event) { eventFired = true; expect(event.name).toBe('fooEvent'); expect(event.targetScope).toBe(scope); expect(event.currentScope).toBe(child); }); scope.$broadcast('fooEvent'); expect(eventFired).toBe(true); })); it('should have the event\'s `currentScope` property set to null after broadcast', inject(function($rootScope) { var scope = $rootScope, child = scope.$new(), event; child.$on('fooEvent', function(e) { event = e; }); scope.$broadcast('fooEvent'); expect(event.name).toBe('fooEvent'); expect(event.targetScope).toBe(scope); expect(event.currentScope).toBe(null); })); it('should support passing messages as varargs', inject(function($rootScope) { var scope = $rootScope, child = scope.$new(), args; child.$on('fooEvent', function() { args = arguments; }); scope.$broadcast('fooEvent', 'do', 're', 'me', 'fa'); expect(args.length).toBe(5); expect(sliceArgs(args, 1)).toEqual(['do', 're', 'me', 'fa']); })); }); }); }); describe('doc examples', function() { it('should properly fire off watch listeners upon scope changes', inject(function($rootScope) { //<docs tag="docs1"> var scope = $rootScope.$new(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function() { scope.greeting = scope.salutation + ' ' + scope.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); //</docs> })); }); });
mit
cowthan/Ayo2022
ProjFringe/ayo-ui-list/src/main/java/org/ayo/list/LocalDisplay.java
1942
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.ayo.list; import android.content.Context; import android.util.DisplayMetrics; import android.view.View; import android.view.WindowManager; public class LocalDisplay { public static int SCREEN_WIDTH_PIXELS; public static int SCREEN_HEIGHT_PIXELS; public static float SCREEN_DENSITY; public static int SCREEN_WIDTH_DP; public static int SCREEN_HEIGHT_DP; private static boolean sInitialed; public LocalDisplay() { } public static float sp2px(Context context, float value) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return value * metrics.scaledDensity; } public static void init(Context context) { if(!sInitialed && context != null) { sInitialed = true; DisplayMetrics dm = new DisplayMetrics(); WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(dm); SCREEN_WIDTH_PIXELS = dm.widthPixels; SCREEN_HEIGHT_PIXELS = dm.heightPixels; SCREEN_DENSITY = dm.density; SCREEN_WIDTH_DP = (int)((float)SCREEN_WIDTH_PIXELS / dm.density); SCREEN_HEIGHT_DP = (int)((float)SCREEN_HEIGHT_PIXELS / dm.density); } } public static int dp2px(float dp) { float scale = SCREEN_DENSITY; return (int)(dp * scale + 0.5F); } public static int designedDP2px(float designedDp) { if(SCREEN_WIDTH_DP != 320) { designedDp = designedDp * (float)SCREEN_WIDTH_DP / 320.0F; } return dp2px(designedDp); } public static void setPadding(View view, float left, float top, float right, float bottom) { view.setPadding(designedDP2px(left), dp2px(top), designedDP2px(right), dp2px(bottom)); } }
mit
rjschultz18/rachel-catarse-crowdfunding
app/models/concerns/project/base_validator.rb
1426
# -*- coding: utf-8 -*- # This module handles with default project state validation module Project::BaseValidator extend ActiveSupport::Concern included do # All valid states for projects in_analysis to end of publication ON_ANALYSIS_TO_END_STATES = %w(in_analysis approved online successful waiting_funds failed).freeze # All valid states for projects approved to end of publication ON_ONLINE_TO_END_STATES = %w(online successful waiting_funds failed).freeze # Start validations when project state # is included on ON_ANALYSIS_TO_END_STATE with_options if: -> (x) { ON_ANALYSIS_TO_END_STATES.include? x.state } do |wo| wo.validates_presence_of :about_html, :headline, :goal wo.validates_presence_of :uploaded_image, unless: ->(project) { project.video_thumbnail.present? } wo.validate do [:uploaded_image, :about_html, :name].each do |attr| self.user.errors.add_on_blank(attr) end self.user.errors.each do |error, error_message| self.errors.add('user.' + error.to_s, error_message) end end end with_options if: -> (x) { ON_ONLINE_TO_END_STATES.include? x.state } do |wo| wo.validate do if self.account && (self.account.agency.try(:size) || 0) < 4 self.errors['account.agency_size'] << "Agência deve ter pelo menos 4 dígitos" end end end end end
mit
mmkassem/gitlabhq
spec/finders/packages/group_packages_finder_spec.rb
4985
# frozen_string_literal: true require 'spec_helper' RSpec.describe Packages::GroupPackagesFinder do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, namespace: group) } let(:another_group) { create(:group) } before do group.add_developer(user) end describe '#execute' do let(:params) { { exclude_subgroups: false } } subject { described_class.new(user, group, params).execute } shared_examples 'with package type' do |package_type| let(:params) { { exclude_subgroups: false, package_type: package_type } } it { is_expected.to match_array([send("package_#{package_type}")]) } end def self.package_types @package_types ||= Packages::Package.package_types.keys end context 'group has packages' do let!(:package1) { create(:maven_package, project: project) } let!(:package2) { create(:maven_package, project: project) } let!(:package3) { create(:maven_package) } it { is_expected.to match_array([package1, package2]) } context 'subgroup has packages' do let(:subgroup) { create(:group, parent: group) } let(:subproject) { create(:project, namespace: subgroup) } let!(:package4) { create(:npm_package, project: subproject) } it { is_expected.to match_array([package1, package2, package4]) } context 'excluding subgroups' do let(:params) { { exclude_subgroups: true } } it { is_expected.to match_array([package1, package2]) } end end context 'when there are processing packages' do let!(:package4) { create(:nuget_package, project: project, name: Packages::Nuget::CreatePackageService::TEMPORARY_PACKAGE_NAME) } it { is_expected.to match_array([package1, package2]) } end context 'does not include packages without version number' do let!(:package_without_version) { create(:maven_package, project: project, version: nil) } it { is_expected.not_to include(package_without_version) } end context 'with package_name' do let_it_be(:named_package) { create(:maven_package, project: project, name: 'maven') } let(:params) { { package_name: package_name } } context 'as complete name' do let(:package_name) { 'maven' } it { is_expected.to eq([named_package]) } end %w[aven mav ave].each do |filter| context "for fuzzy filter #{filter}" do let(:package_name) { filter } it { is_expected.to eq([named_package]) } end end end end context 'group has package of all types' do package_types.each { |pt| let!("package_#{pt}") { create("#{pt}_package", project: project) } } package_types.each do |package_type| it_behaves_like 'with package type', package_type end end context 'group has no packages' do it { is_expected.to be_empty } end context 'group is nil' do subject { described_class.new(user, nil).execute } it { is_expected.to be_empty} end context 'package type is nil' do let!(:package1) { create(:maven_package, project: project) } subject { described_class.new(user, group, package_type: nil).execute } it { is_expected.to match_array([package1])} end context 'with invalid package_type' do let(:params) { { package_type: 'invalid_type' } } it { expect { subject }.to raise_exception(described_class::InvalidPackageTypeError) } end context 'when project is public' do let_it_be(:other_user) { create(:user) } let(:finder) { described_class.new(other_user, group) } before do project.update!(visibility_level: ProjectFeature::ENABLED) end context 'when packages are public' do before do project.project_feature.update!( builds_access_level: ProjectFeature::PRIVATE, merge_requests_access_level: ProjectFeature::PRIVATE, repository_access_level: ProjectFeature::ENABLED) end it 'returns group packages' do package1 = create(:maven_package, project: project) package2 = create(:maven_package, project: project) create(:maven_package) expect(finder.execute).to match_array([package1, package2]) end end context 'packages are members only' do before do project.project_feature.update!( builds_access_level: ProjectFeature::PRIVATE, merge_requests_access_level: ProjectFeature::PRIVATE, repository_access_level: ProjectFeature::PRIVATE) create(:maven_package, project: project) create(:maven_package) end it 'filters out the project if the user doesn\'t have permission' do expect(finder.execute).to be_empty end end end end end
mit
CS2103AUG2016-T14-C3/main
src/test/java/guitests/ListNotDoneCommandTest.java
957
package guitests; import static seedu.taskmanager.logic.commands.ListNotDoneCommand.COMMAND_WORD; import static seedu.taskmanager.logic.commands.ListNotDoneCommand.SHORT_COMMAND_WORD; import static seedu.taskmanager.logic.commands.ListNotDoneCommand.MESSAGE_SUCCESS; import org.junit.Test; import seedu.taskmanager.commons.core.Messages; //@@author A0140060A public class ListNotDoneCommandTest extends TaskManagerGuiTest { @Test public void listNotDone_success() { assertListNotDoneCommandSuccess(COMMAND_WORD); assertListNotDoneCommandSuccess(SHORT_COMMAND_WORD); } @Test public void listNotDone_invalidCommand_unknownCommandMessage() { commandBox.runCommand("listnotdones"); assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND); } private void assertListNotDoneCommandSuccess(String commandWord) { commandBox.runCommand(commandWord); assertResultMessage(MESSAGE_SUCCESS); } }
mit
scalation/fda
scalation_1.3/scalation_mathstat/src/main/scala/scalation/plot/HeatMapFX.scala
9018
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author Michael E. Cotterell & Alec Molinaro * @version 1.2 * @date THR Apr 20 00:05:16 EST 2015 * @see LICENSE (MIT style license file). */ package scalation.plot import javafx.application.Application import javafx.scene.Scene import javafx.scene.chart.NumberAxis import javafx.scene.chart.LineChart import javafx.scene.chart.XYChart import javafx.scene.chart.Axis import javafx.scene.shape.{Line, Rectangle} import javafx.scene.paint.Color import java.io.File import scalation.linalgebra.{VectoD, VectoI} import scalation.scala2d.{Panel, VizFrame} import scala.math.{Ordering, pow} import scala.util.Sorting import javafx.application.Application import javafx.event.{ActionEvent, EventHandler} import javafx.geometry.Insets import javafx.scene.{Group, Node, Scene} import javafx.scene.chart._ import javafx.scene.paint.Color import javafx.stage.Stage import javafx.scene.control.{ToggleButton, ScrollPane} import javafx.scene.control.ScrollPane.ScrollBarPolicy import javafx.scene.layout.{HBox, VBox, FlowPane} import javafx.geometry.Orientation import scala.math._ import scalation.linalgebra.{MatriD, VectoD} import scalation.linalgebra.{VectoD, VectoI} import scalation.linalgebra.{MatrixD, VectorD} import scalation.scala2d.{Panel, VizFrame} import scala.math.pow //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `HeatMapFX` class takes 'x' and 'y' vectors of data values and plots the '(x, y)' * data points. For more vertical vectors use `PlotM`. * @param xx the x matrix of data values where x(i) is the i-th vector * @param cl the cl array of data values (horizontal) * @param k the number of clusters in the data * @param _title the title of the plot */ class HeatMapFX (x: MatrixD, cl: Array [Int], k: Int, _title: String = "HeatMapFX") extends VizFrame (_title, null) { val xx = if (cl != null) sorted () else x val WIDTH = 600 / x.dim2 //200 // constant for rectangle width val HEIGHT = 1 // constant for rectangle hieght val WAVE_LOW = 380.0 // constant for lower wavelength val WAVE_HIGH = 780.0 // constant for higher wavelength val min = xx.min() // minimum value in matrix val max = xx.max() // maximum value in matrix val c = new CanvasFX(_title, 700, 600) // canvas that holds everything val scene: Scene = new Scene(new Group()) // scene that everything is put into val fpane: FlowPane = new FlowPane() // creating flow pane val vbox: VBox = new VBox() // VBox for styling val hbox: HBox = new HBox() // HBox for styling hbox.setSpacing(10) // styling HBox fpane.setPrefWrapLength(WIDTH*xx.dim2) // styling for flow pane val sp = new ScrollPane() // creating a scroll pane sp.setPrefSize(700, 578) // setting for size for scroll pane var map = Array.ofDim[Rectangle](xx.dim1, xx.dim2) // creating a mapping of recatngles for (i <- xx.range1; j <- xx.range2) { // looping over values val r = new Rectangle() // creating a rectangle r.setWidth(WIDTH) // setting width r.setHeight(HEIGHT) // setting height r.setX(WIDTH*j) // spacing out rectangles r.setY(HEIGHT*i) // spacing our rectangles val ci = wToRGB(linearInterp(xx(i, j))) // getting rectangle a color value r.setFill(ci) // setting color value map(i)(j) = r // adding rectangle to map fpane.getChildren.addAll(r) // putting the rectangle in the flow pane } // for // sizing the scroll bar sp.setHbarPolicy(ScrollBarPolicy.AS_NEEDED) // adding horizontal bar when its needed sp.setVbarPolicy(ScrollBarPolicy.AS_NEEDED) // adding vertical bar when its needed sp.setPannable(true) // lets you pan along the scroll pane sp.setFitToHeight(true) // fits scroll pane to canvas size sp.setContent(fpane) // adds flow pane to scroll pane c.nodes.getChildren.addAll(sp) // add scroll pane to canvas c.show() // display canvas //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Linearally interpolates a plot of several 'v' vectors versus an 'x' vector. * @param v the v vector of data values (horizontal) */ def linearInterp(v: Double): Double = { val wavelength = ( (v-min)/(max-min) ) * (WAVE_HIGH - WAVE_LOW) + WAVE_LOW return wavelength } // linearInterp //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Translates a plot of a 'w' vector versus an 'x' vector. * @param w the w vector of data values (horizontal) * @see http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm */ def wToRGB (w: Double): Color = { val GAMMA = 0.80 val INTENSITY_MAX = 255.0 val INTENSITY_MIN = 0.0 var r = 0.0 var b = 0.0 var g = 0.0 var factor = 0.0 def adjust (color: Double, factor: Double): Int = { // adjusts color for dispaly val result = if (color == 0) 0 else math.round(INTENSITY_MAX * math.pow(color * factor, GAMMA)) result.toInt } //adjust if (380 <= w && w < 440 ) { // each level assigns a value for rgb based on w r = -(w - 440) / (440 - 380) g = 0 b = 1 } else if (440 <= w && w < 490){ r = 0 g = (w - 440) / (490 - 440) b = 1 } else if (490 <= w && w < 510) { r = 0 g = 1 b = - (w - 510) / (510 - 490) } else if (510 <= w && w < 580) { r = (w - 510) / (580 - 510) g = 1 b = 0 } else if (580 <= w && w < 645) { r = 1 g = - (w - 645) / (645 - 580) b = 0 } else if (645 <= w && w <= 780) { r = 1 g = 0 b = 0 } else { r = 0 g = 0 b = 0 } // if if (380 <= w && w < 420) factor = 0.3 + 0.7 * (w - 380) / (420 - 380) else if (420 <= w && w < 701) factor = 1 else if (701 <= w && w <= 780) factor = 0.3 + 0.7 * (780 - w) / (780 - 700) else factor = 0 r = adjust(r, factor) g = adjust(g, factor) b = adjust(b, factor) Color.rgb(r.toInt, g.toInt, b.toInt) // assigns a color to recatangle based on its value } // wToXYZ //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Returns the matrix sorted according to cluster assignment. */ def sorted (): MatrixD = { val clusters = cl.zipWithIndex Sorting.quickSort (clusters)(Ordering.by[(Int, Int), Int](_._1)) val sort = clusters.map(_._2) MatrixD (for (i <- sort) yield x(i), false) } // sorted } // HeatMapFX class //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `HeatMapFXTest` object is used to test the `HeatMapFXTest` class. */ object HeatMapFXTest extends App { val f = new File("nzdata.csv") println(f.getAbsolutePath()) val m = MatrixD (f.getAbsolutePath()) val hmap = new HeatMapFX(m, null, 0, null) } // HeatMapFXTest //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `HeatMapFXTest2` object is used to test the `HeatMapFXTest2` class. */ object HeatMapFXTest2 extends App { val f = new File("random.csv") println(f.getAbsolutePath()) val m = MatrixD (f.getAbsolutePath()) val hmap = new HeatMapFX(m, null, 0, null) } // HeatMapFXTest2 //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `HeatMapFXTest3` object is used to test the `HeatMapFXTest3` class. */ object HeatMapFXTest3 extends App { val f = new File("randomSorted.csv") println(f.getAbsolutePath()) val m = MatrixD (f.getAbsolutePath()) val hmap = new HeatMapFX(m, null, 0, null) } // HeatMapFXTest3
mit
hbobenicio/sta-to-csv
libsta/src/sta-converter.cpp
346
#include "sta-converter.h" #include <string> #include "fields.h" using namespace std; string STAConverter::formatDecimal(const FieldInfo& info, const string& value) { string response = value; if (info.isDecimal()) { int pos = stoi(info.beforeDecimalSeparator()); response.insert(pos, ","); } return response; }
mit
InWork/queue_dispatcher
lib/queue_dispatcher/qd_logger.rb
481
module QdLogger attr_accessor :logger def initialize_logger(logger = nil) @logger = logger || Logger.new("#{File.expand_path(Rails.root)}/log/queue_dispatcher.log") end # Write a standart log message def log(args = {}) sev = args[:sev] || :info msg = Time.now.to_s + " #{sev.to_s.upcase} #{$$} (#{self.class.name}): " + args[:msg] logger.send(sev, msg) if logger puts "#{sev.to_s.upcase}: #{args[:msg]}" if logger.nil? || args[:print_log] end end
mit
senna-project/senna
src/Senna/Bundle/AppBundle/EventListener/UserListener.php
3351
<?php namespace Senna\Bundle\AppBundle\EventListener; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Events; use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Event\PreUpdateEventArgs; use Senna\Bundle\AppBundle\Model\User; use Polymorph\Component\User\Model\UserInterface; class UserListener implements EventSubscriber { protected $encoderFactory; public function getSubscribedEvents() { return array( Events::prePersist, Events::preUpdate, ); } /** * @param EncoderFactoryInterface $encoder */ public function __construct(EncoderFactoryInterface $encoder) { return $this->encoderFactory = $encoder; } protected function getEncoder(User $user) { return $this->encoderFactory->getEncoder($user); } /** * kernel.request event. If a guest user doesn't have an opened session, locale is equal to * "undefined" as configured by default in parameters.ini. If so, set as a locale the user's * preferred language. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event */ public function setLocaleForUnauthenticatedUser(GetResponseEvent $event) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { return; } $request = $event->getRequest(); if ('undefined' == $request->getLocale()) { $request->setLocale($request->getPreferredLanguage()); } } /** * security.interactive_login event. If a user chose a locale in preferences, it would be set, * if not, a locale that was set by setLocaleForUnauthenticatedUser remains. * * @param \Symfony\Component\Security\Http\Event\InteractiveLoginEvent $event */ public function setLocaleForAuthenticatedUser(InteractiveLoginEvent $event) { /** @var \Senna\Bundle\AppBundle\Model\User $user */ $user = $event->getAuthenticationToken()->getUser(); if ($user->getLocale()) { $event->getRequest()->setLocale($user->getLocale()); } } /** * @param LifecycleEventArgs $args */ public function prePersist($args) { $object = $args->getEntity(); if ($object instanceof UserInterface) { $this->updateUserFields($object); } } /** * @param PreUpdateEventArgs $args */ public function preUpdate($args) { $object = $args->getEntity(); if ($object instanceof UserInterface) { $this->updateUserFields($object); } } protected function updatePassword(UserInterface $user) { if (0 !== strlen($password = $user->getPlainPassword())) { $encoder = $this->getEncoder($user); $user->setPassword($encoder->encodePassword($password, $user->getSalt())); $user->eraseCredentials(); } return $user; } public function updateUserFields(UserInterface $user) { $this->updatePassword($user); return $this; } }
mit
object/Simple.OData.Client
src/Simple.OData.Client.V4.Adapter/ResourceProperties.cs
714
using System.Collections.Generic; using System.Linq; using Microsoft.OData; using Microsoft.OData.Edm; using Simple.OData.Client.Extensions; namespace Simple.OData.Client.V4.Adapter { public class ResourceProperties { public ODataResource Resource { get; } public string TypeName { get; set; } public IEnumerable<ODataProperty> PrimitiveProperties => this.Resource.Properties; public IDictionary<string, ODataCollectionValue> CollectionProperties { get; set; } public IDictionary<string, ODataResource> StructuralProperties { get; set; } public ResourceProperties(ODataResource resource) { this.Resource = resource; } } }
mit
jievro/parser
spec/statement/loop/for/test_expression_spec.rb
479
require 'jievro/parser/tools/tokens' def source 'for;false;{}' end def expected_tokens [ T_FOR, T_SEMICOLON, T_FALSE, T_SEMICOLON, T_OPEN_CURLY_BRACKET, T_CLOSE_CURLY_BRACKET ] end def expected_ast { __type: 'program', body: [ { __type: 'for-statement', init: [], test: { __type: 'literal-boolean', value: false }, body: [] } ] } end load 'spec_builder.rb'
mit
jeselxe/WebSeries-cli
app/scripts/components/Temporadas/Temporada.js
1632
import React, { PropTypes } from 'react'; import ActionButton from '../ActionButton'; import {connect} from 'react-redux'; import {temporadasActions} from '../../Actions'; const mapStateToProps = (state) => { return { token : state.login.token, serie: state.series.serie, temporada: state.series.temporada } } const mapDispatchToProps = (dispatch) => { return { selectSeason: (serie, season) => { temporadasActions.selectSeason(dispatch, serie, season); }, deleteSeason: (token, serie, season) => { temporadasActions.deleteSeason(dispatch, token, serie, season); } } } class Temporada extends React.Component { borrar() { this.props.deleteSeason(this.props.token, this.props.serie.id, this.props.id); } click(){ this.props.selectSeason(this.props.serie.id, this.props.id); } render () { let style = "btn btn-default"; if (this.props.temporada === this.props.id) style += " active"; return ( <div className="btn-group actions-list"> <button className={style} id={'temporada_' + this.props.id} onClick={this.click.bind(this)}> {this.props.children} </button> <div className="actions"> <ActionButton> <ActionButton.Item onClick={ this.borrar.bind(this) }>Borrar</ActionButton.Item> </ActionButton> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(Temporada);
mit
dinjonya/blog
CorePlugs20/Models/ConfigModel.cs
3287
using System.Collections.Generic; namespace CorePlugs20.Models { public class ConfigModel { public string EnvironmentName { get; set; } public int PageSize { get; set; } public AuthenServerModel AuthenServer { get; set; } public BlogUiModel BlogUi { get; set; } public ApiBlogModel ApiBlog { get; set; } public MongoConfigModel MongoConfig { get; set; } public RssConfig Rss { get; set; } } public class AuthenServerModel { public bool AuthenEnable { get; set; } public List<string> AuthenServerUrls { get; set; } public NoAuthenIpConfig NoAuthenIp { get; set; } public string ConnectionString { get; set; } } public class NoAuthenIpConfig { public bool Enable { get; set; } public List<string> Ips { get; set; } } public class BlogUiModel { public List<string> BlogUiUrls { get; set; } public bool Authen { get; set; } public string UploadPath { get; set; } public List<Apis_Config> Apis { get; set; } public Apis_Config this[string apiName] { get { foreach (var item in Apis) { if(item.ApiName == apiName) return item; } return null; } } } public class Apis_Config { public string ApiName { get; set; } public string Uri { get; set; } public string UriPath { get; set; } } public class ApiBlogModel { public List<string> ApiBlogUrls { get; set; } public bool Debug { get; set; } public bool AutoCreateDb { get; set; } public string ConnectionString { get; set; } public bool Authen { get; set; } public List<string> AllowCorsUris { get; set; } } public class MongoConfigModel { public string DataBase { get; set; } public string ConnectionString { get; set; } public List<Collections_Config> Collections { get; set; } public Collections_Config this[string collectionName] { get { foreach (var collection in Collections) { if (collection.CollectionName == collectionName) { return collection; } } return null; } } } public partial class Collections_Config { /// <summary> /// Log集合名称 /// </summary> public string CollectionName { get; set; } public string CollectionNameValue { get; set; } } public partial class RssConfig { public string RssTitle { get; set; } public string AlternateLink { get; set; } public string SelfLink { get; set; } public AtomTagConfig AtomTag { get; set; } public string SubTitle { get; set; } public string AuthorName { get; set; } public string AuthorEmail { get; set; } } public partial class AtomTagConfig { public string Id { get; set; } public string Domain { get; set; } } }
mit
vuikit/vuikit
packages/vuikit-icons/src/uikit/triangle-down.js
492
// icon-triangle-down export default { functional: true, render: function (h, { props }) { let width = props.width || 20 let height = props.height || 20 const viewBox = props.viewBox || '0 0 20 20' return h('svg', { attrs: { version: '1.1', meta: 'vk-icons-triangle-down', width: width, height: height, viewBox: viewBox }, domProps: { innerHTML: '<polygon points="5 7 15 7 10 12" />' } }) } }
mit
Grafikart/arraytree-gem
lib/Array.rb
528
Array.class_eval do def tree(foreign_key = :parent_id, id_key = :id) grouped = self.group_by { |i| i[foreign_key].nil? ? 0 : i[foreign_key] } grouped.each do |parent_id, children| if parent_id && parent_id != 0 parent = self.select { |e| e[id_key] == parent_id }.first if parent.respond_to? :leaves parent.leaves = children else parent[:leaves] = children end end end grouped[0] end end
mit
eikes/sqek
db/migrate/20150910081733_add_external_url_to_city.rb
140
class AddExternalUrlToCity < ActiveRecord::Migration[4.2] def change add_column :cities, :external_url, :string, default: 0 end end
mit
seznam/IMA.js-core
test.js
1034
var root = typeof window !== 'undefined' && window !== null ? window : global; root.$IMA = root.$IMA || {}; root.$IMA.Test = true; root.$IMA.$Debug = true; root.$Debug = true; root.$IMA.Loader = root.$IMA.Loader || { register: function() {}, replaceModule: function() {}, import: function() { return Promise.resolve(); }, importSync: function() {}, initAllModules: function() { return Promise.resolve(); } }; root.extend = extend; root.using = using; root.$import = $import; function using(values, func) { for (var i = 0, count = values.length; i < count; i++) { if (Object.prototype.toString.call(values[i]) !== '[object Array]') { values[i] = [values[i]]; } func.apply(this, values[i]); } } function extend(ChildClass, ParentClass) { ChildClass.prototype = new ParentClass(); ChildClass.prototype.constructor = ChildClass; } function $import(path, name) { var module = $IMA.Loader.importSync(path); name = name || 'default'; return name === '*' ? module : module[name]; }
mit
leyyin/university
systems-for-design-and-implementation/labs/lab3/LibraryServer/src/library/server/ServerStartRPC.scala
977
package library.server import library.network.utils.{AbstractServer, LibraryRPCConcurrentServer, ServerException} import library.persistance.repository.jdbc.{BookRepositoryJDBC, UserRepositoryJDBC} import library.persistance.repository.{IBookRepository, IUserRepository} import library.services.impl.LibraryServerImpl import library.services.{Constants, ILibraryServer} object ServerStartRPC { def main(args: Array[String]) { println("Starting Server") val userRepository: IUserRepository = new UserRepositoryJDBC val bookRepository: IBookRepository = new BookRepositoryJDBC val libraryServerImpl: ILibraryServer = new LibraryServerImpl(userRepository, bookRepository) val server: AbstractServer = new LibraryRPCConcurrentServer(Constants.PORT, libraryServerImpl) try { server.start() } catch { case e: ServerException => println(e.getMessage) } } }
mit
StefanoFiumara/Harry-Potter-Unity
Assets/Scripts/HarryPotterUnity/Cards/Characters/RonYoungestBrother.cs
617
using System.Collections.Generic; namespace HarryPotterUnity.Cards.Characters { public class RonYoungestBrother : BaseCharacter { public override bool CanPerformInPlayAction() { return this.Player.Hand.Cards.Count == 0 && this.Player.IsLocalPlayer && this.Player.CanUseActions(); } public override void OnInPlayAction(List<BaseCard> targets = null) { for (int i = 0; i < 5; i++) { this.Player.Deck.DrawCard(); } this.Player.UseActions(); } } }
mit
jasonwnorris/SuperAwesomeGameEngine
include/SAGE/AudioSource.hpp
939
// AudioSource.hpp #ifndef __SAGE_AUDIOSOURCE_HPP__ #define __SAGE_AUDIOSOURCE_HPP__ // OpenAL Includes #include <AL/al.h> // SAGE Includes #include <SAGE/Vector2.hpp> namespace SAGE { class AudioSource { public: AudioSource(); AudioSource(ALuint p_BufferID); ~AudioSource(); void SetBuffer(ALuint p_BufferID); void SetPosition(ALfloat p_PositionX, ALfloat p_PositionY); void SetPosition(const Vector2& p_Position); void SetVelocity(ALfloat p_VelocityX, ALfloat p_VelocityY); void SetVelocity(const Vector2& p_Velocity); void SetPitch(ALfloat p_Pitch); void SetGain(ALfloat p_Gain); void SetLooping(ALboolean p_IsLooping); void Play(); void Pause(); void Stop(); private: ALuint m_ID; ALuint m_BufferID; ALfloat m_PositionX; ALfloat m_PositionY; ALfloat m_VelocityX; ALfloat m_VelocityY; ALfloat m_Pitch; ALfloat m_Gain; ALboolean m_IsLooping; }; } #endif
mit
aabasse/otacos
web/js/photo.js
3850
$(function(){ var nbrPhoto = $('#formPhoto-fields-list').data('nbr-photo'); /*$('.element').each(function(){ var src = $(this).data('url'); var label = $('label', $(this)); //console.log(url); remplacerImageApercu(label, src, ''); })*/ $('#add-photo').click(function(e) { e.preventDefault(); var photoList = $('#formPhoto-fields-list'); // grab the prototype template var newWidget = photoList.attr('data-prototype'); // replace the "__name__" used in the id and name of the prototype // with a number that's unique to your emails // end name attribute looks like name="contact[emails][2]" newWidget = newWidget.replace(/__name__/g, nbrPhoto+''+Math.floor((Math.random() * 10) + 1) ); nbrPhoto++; // create a new list element and add it to the list var newLi = $('<li class="element"></li>').html(newWidget); newLi.appendTo(photoList); initEvenInput(); addTagFormDeleteLink(newLi); }); //--------------------------- suppression // Get the ul that holds the collection of tags $collectionHolder = $('#formPhoto-fields-list'); // add a delete link to all of the existing tag form li elements $collectionHolder.find('li.element').each(function(index) { if(index != 0) { addTagFormDeleteLink($(this)); } }); function addTagFormDeleteLink($tagFormLi) { var $removeFormA = $('<button class="btSupImg" type="button"><i class="fa fa-times" aria-hidden="true"></i></button>'); $tagFormLi.append($removeFormA); $removeFormA.on('click', function(e) { // prevent the link from creating a "#" on the URL e.preventDefault(); // remove the li for the tag form $tagFormLi.remove(); gestionAffichageAdd(); }); gestionAffichageAdd(); } function gestionAffichageAdd(){ if($('.element').length >= 2) { $("#add-photo").hide(); } else{ $("#add-photo").show(); } } /* ============================= AFFICHE UN APERCU D'UNE IMAGE TELECHARGER */ initEvenInput(); function initEvenInput(){ $("input[type='file']").change(function(){ var element = $(this).closest('.element'); var label = $('label', element); var fileInput = this.files[0]; var allowedTypes = ['png', 'jpg', 'jpeg', 'gif']; imgType = fileInput.name.split('.'); imgType = imgType[imgType.length - 1].toLowerCase(); if (allowedTypes.indexOf(imgType) != -1){ var reader = new FileReader(); reader.addEventListener('load', function() { remplacerImageApercu(label, reader.result, fileInput.name) }); reader.readAsDataURL(fileInput); } else { supprimerImgLabel(label); alert("Ce n'est pas une image :("); //remplacerImageApercu(imgApercu, srcImgDefaut, 'ajouter une image') } }); } function remplacerImageApercu(label, src, alt) { supprimerImgLabel(label) var img = $("<img src='"+src+"' alt='"+alt+"'>"); label.append(img); label.removeClass('lbNoFile'); /*imgApercu.hide(200, function(){ imgApercu.attr('src', src); imgApercu.attr('alt', alt); }).show(200);*/ } function supprimerImgLabel(label){ $('img', label).remove(); label.addClass('lbNoFile'); } })
mit
AJ-Moore/NMEngine
source/SceneManager.cpp
2552
//!< Author: Allan J Moore 13/ 01/ 2015 /*************************************************************************************** * Nightmare Engine, Unorthodox Game Studios * * Copyright (C) 2014, Allan J Moore * * All rights reserved * * * * See "licence.txt" included with this release for licensing information. * ***************************************************************************************/ #include "SceneManager.h" namespace NightmareEngine{ SceneManager::SceneManager(){ } //Cleans up abit SceneManager::~SceneManager(){ } //!< Adds a scene and returns the newly created scene SceneGraph* SceneManager::addScene(){ SceneGraph* scene = new SceneGraph(); if (this->addScene(scene)){ return scene; } else{ LogError("Unable to create scene - Unknown error occured"); if (scene != nullptr ) delete scene; scene = nullptr; return nullptr; } } //!< Adds a scene to the scene manager - returns false if scene has already been added. bool SceneManager::addScene(SceneGraph* GameScene){ if (GameScene == nullptr){ LogError("Null reference GameScene @ SceneManager::addScene(....)"); //throw exception? return false; } if (this->sceneRegister.find(GameScene->getID()) != this->sceneRegister.end()){ LogWarning("Game Scene Already In Scene Register!!"); return false; } else{ this->sceneRegister.insert(std::make_pair(GameScene->getID(), GameScene)); this->sceneList.push_back(GameScene); return true; } } //!< Returns the scene with the given ID returns nullptr is no scene present SceneGraph* SceneManager::getScene(U32 ID){ std::map<U32,SceneGraph*>::iterator iter = this->sceneRegister.find(ID); if (iter == this->sceneRegister.end()){ LogError("Scene could not be found"); return nullptr; } return iter->second; } bool SceneManager::load(){ return true; } void SceneManager::unload(){ } bool SceneManager::initialise(){ return true; } //<! Is called to update all scenes in the SceneManager void SceneManager::update(){ } //<! Is called to render all scene in the SceneManager void SceneManager::render(){ } }
mit
pixelballoon/pixelboost
engine/src/common/pixelboost/animation/component/timeline.cpp
1857
#include "pixelboost/animation/component/timeline.h" #include "pixelboost/animation/message/timeline.h" #include "pixelboost/animation/timeline/timeline.h" #include "pixelboost/logic/message/update.h" #include "pixelboost/logic/entity.h" using namespace pb; PB_DEFINE_COMPONENT(pb::TimelineComponent) TimelineComponent::TimelineComponent(Entity* parent) : Component(parent) { _Timeline = new Timeline(); _UseGlobalTime = false; _IsPlaying = false; _IsLooping = false; GetEntity()->RegisterMessageHandler<UpdateMessage>(MessageHandler(this, &TimelineComponent::OnUpdate)); } TimelineComponent::~TimelineComponent() { GetEntity()->UnregisterMessageHandler<UpdateMessage>(MessageHandler(this, &TimelineComponent::OnUpdate)); delete _Timeline; } Timeline* TimelineComponent::GetTimeline() { return _Timeline; } void TimelineComponent::Play() { _Timeline->Play(); } void TimelineComponent::Stop() { _Timeline->Stop(); } void TimelineComponent::SetLooping(bool looping) { _IsLooping = looping; } void TimelineComponent::SetUseGlobalTime(bool useGlobalTime) { _UseGlobalTime = useGlobalTime; } void TimelineComponent::OnUpdate(const Message& message) { auto updateMessage = message.As<UpdateMessage>(); if (_Timeline->IsPlaying() && !_IsPlaying) { _IsPlaying = true; GetEntity()->SendMessage(TimelinePlayingMessage(GetEntity(), this)); } _Timeline->Update(_UseGlobalTime ? updateMessage.GetTimeDelta() : updateMessage.GetGameDelta()); if (!_Timeline->IsPlaying() && _IsPlaying) { if (_IsLooping) { _Timeline->Reset(); _Timeline->Play(); } else { _IsPlaying = false; GetEntity()->SendMessage(TimelineStoppedMessage(GetEntity(), this)); } } }
mit
wendorf/sprout-mysql
spec/unit/install_spec.rb
685
require 'unit/spec_helper' describe 'sprout-mysql::install' do let(:runner) { ChefSpec::Runner.new } before do stub_command(/mysql /) end it 'installs mysql' do runner.converge(described_recipe) expect(runner).to install_package('mysql') end it 'uses a default root password of `password`' do runner.converge(described_recipe) expect(runner).to run_execute('mysqladmin -uroot password password') end it 'uses the specified root password' do runner.node.set['sprout']['mysql']['root_password'] = 'custompassword' runner.converge(described_recipe) expect(runner).to run_execute('mysqladmin -uroot password custompassword') end end
mit
pitsolu/strukt-framework
src/Strukt/Loader/RegenerateModuleLoader.php
1784
<?php namespace Strukt\Loader; use Strukt\Fs; use Strukt\Env; use Strukt\Generator\Parser; use Strukt\Generator\Compiler\Runner as Compiler; use Strukt\Generator\Compiler\Configuration; use Strukt\Templator; /** * Helper that generates module loader * * @author Moderator <[email protected]> */ class RegenerateModuleLoader{ /** * Module loader string * * @var string */ private $loader_output; /** * Constructor * * Resolve available module and generate class */ public function __construct(){ $root_dir = Env::get("root_dir"); $app_dir = Env::get("rel_appsrc_dir"); $loader_sgf_file = Env::get("rel_loader_sgf"); $appsrc_path = sprintf("%s/%s", $root_dir, $app_dir); if(!Fs::isPath($appsrc_path)) throw new \Exception(sprintf("Application source path [%s] does not exist!", $appsrc_path)); foreach(scandir($appsrc_path) as $srcItem) if(!preg_match("/(.\.php|\.)/", $srcItem)) $apps[] = $srcItem; foreach($apps as $app){ $app_path = sprintf("%s%s", $appsrc_path, $app); foreach(scandir($app_path) as $appItem) if(!preg_match("/(.\.php|\.)/", $appItem)) $all[$app][] = $appItem; } foreach($all as $name=>$mods) foreach($mods as $mod) if(preg_match("/[A-Za-z]+Module$/", $mod)) $register[] = sprintf("\$this->app->register(new \%s\%s\%s%s());", $name, $mod, $name, $mod); if(!Fs::isFile($loader_sgf_file)) throw new \Exception(sprintf("File [%s] was not found!", $loader_sgf_file)); $tpl_file = Fs::cat($loader_sgf_file); $this->loader_output = Templator::create($tpl_file, array( "packages"=>implode("\n\t\t\t", $register) )); } /** * Render module loader class * * @return string */ public function __toString(){ return $this->loader_output; } }
mit
BeltranGomezUlises/machineAdminAPI
src/main/java/com/auth/models/ModelUsuarioLogeado.java
1975
/* * Copyright (C) 2017 Alonso --- [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.auth.models; import com.fasterxml.jackson.annotation.JsonInclude; /** * modelo de respuesta del usuario logeado * * @author Alonso --- [email protected] */ @JsonInclude(JsonInclude.Include.NON_NULL) public class ModelUsuarioLogeado { private Integer id; private String nombre; private String correo; private Object permisos; private String telefono; private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public Object getPermisos() { return permisos; } public void setPermisos(Object permisos) { this.permisos = permisos; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } }
mit
campaignmonitor/createsend-java
src/com/createsend/util/jersey/JsonProvider.java
3687
/** * Copyright (c) 2011 Toby Brain * * 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. */ package com.createsend.util.jersey; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * An extension of the Jersey JacksonJsonProvider used to set Jackson * serialisation/deserialisation properties */ public class JsonProvider extends JacksonJsonProvider { public static final DateFormat ApiDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm") { final SimpleDateFormat ApiDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final SimpleDateFormat ApiDateFormatTz = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); @Override public Date parse(String source, ParsePosition pos) { if (source.length() - pos.getIndex() == ApiDateFormat.toPattern().length()) return ApiDateFormat.parse(source, pos); return ApiDateFormatTz.parse(source, pos); } }; @Override public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { ObjectMapper mapper = locateMapper(type, mediaType); mapper.setSerializationInclusion(Include.NON_NULL); super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream); } @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { ObjectMapper mapper = locateMapper(type, mediaType); mapper.setDateFormat(ApiDateFormat); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream); } }
mit
joshfriend/potatosalad
potatosalad/api/image.py
1564
#!/usr/bin/env python # -*- coding: utf-8 -*- from cStringIO import StringIO from flask import send_file, current_app from werkzeug.exceptions import BadRequest from potatosalad.api import endpoints from potatosalad.util import ( pick_random_image, remove_transparency, cache_control, crop_resize, ) ALLOWED_IMAGE_FORMATS = { 'jpg': 'jpeg', # Valid extension but not recognized by PIL 'jpeg': 'jpeg', 'bmp': 'bmp', 'png': 'png', } #: Formats which support alpha channel _ALPHA_FORMATS = [ 'png', ] def serve_pil_image(img, fmt): fmt = ALLOWED_IMAGE_FORMATS[fmt] mimetype = 'image/' + fmt # Replace transparency with white if not supported by target format if img.mode in ('RGBA', 'LA') and fmt not in _ALPHA_FORMATS: img = remove_transparency(img) f = StringIO() img.save(f, fmt, quality=70) f.seek(0) return send_file(f, mimetype=mimetype) @endpoints.route('/<int:w>/<int:h>.<ext>') @endpoints.route('/<int:w>/<int:h>') @cache_control('max-age=60') def placeholder_image(w, h, ext='jpg'): # Check max dimensions maxh = current_app.config['MAX_IMAGE_HEIGHT'] maxw = current_app.config['MAX_IMAGE_WIDTH'] if h > maxh or w > maxw: raise BadRequest('Image must be smaller than %ix%i' % (maxw, maxh)) if ext not in ALLOWED_IMAGE_FORMATS: raise BadRequest( 'Allowed formats are: %s' % ', '.join(ALLOWED_IMAGE_FORMATS) ) img = pick_random_image() img = crop_resize(img, (w, h)) return serve_pil_image(img, ext)
mit
DeNA/rubycf
lib/rubycf_extensions.rb
2307
# Copyright (c) 2009 ngmoco:) # # 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. # Extensions to the build in C functions module RubyCF class PList class << self alias decode parse end # Parse a plist from a file path or handle def self.parse_file file self.parse(file.is_a?(File) ? file.read : File.read(file)) end end # CF handles raw data different from strings. Ruby treats them the same. # Use RubyCF::Data objects to tell the plist encoder to treat the objects # as data. class Data attr_reader :data # Create a RubyCF::Data object from a file path or handle def self.from_file file Data.new(file.is_a?(File) ? file.read : File.read(file)) end # Create a RubyCF::Data object from a string def initialize string self.data = string end def inspect "RubyCF::Data #{@data.size} bytes" end def == other if(other.is_a?(RubyCF::Data)) return other.data == @data else return other == @data end end def data= string @data = string.to_s end end end class Object # Shorthand for RubyCF::PList.encode(object, format) def to_plist(format = :binary) RubyCF::PList.encode(self, format) end end
mit
msfrisbie/pjwd-src
AppendixBStrictMode/Functions/FunctionsExample04.js
196
// Function declaration in an if statement // Non-strict mode: Function hoisted outside of if statement // Strict mode: Throws a syntax error if (true){ function doSomething(){ // ... } }
mit
ivanknow/middleware-panfleto-movel
src/br/ufrpe/bcc/negocio/Usuario.java
489
package br.ufrpe.bcc.negocio; public class Usuario { private int id; private String login; private String senha; public Usuario(String login, String senha){ this.login = login; this.senha = senha; } public int getId(){ return this.id; } public String getLogin(){ return this.login; } public void setLogin(String login){ this.login = login; } public String getSenha(){ return this.senha; } public void setSenha(String senha){ this.senha = senha; } }
mit
tobyclemson/msci-project
vendor/poi-3.6/src/java/org/apache/poi/hssf/record/SSTRecord.java
10853
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hssf.record; import java.util.Iterator; import org.apache.poi.hssf.record.cont.ContinuableRecord; import org.apache.poi.hssf.record.cont.ContinuableRecordOutput; import org.apache.poi.util.IntMapper; import org.apache.poi.util.LittleEndianConsts; /** * Title: Static String Table Record (0x00FC)<p/> * * Description: This holds all the strings for LabelSSTRecords. * <P> * REFERENCE: PG 389 Microsoft Excel 97 Developer's Kit (ISBN: * 1-57231-498-2) * <P> * @author Andrew C. Oliver (acoliver at apache dot org) * @author Marc Johnson (mjohnson at apache dot org) * @author Glen Stampoultzis (glens at apache.org) * * @see org.apache.poi.hssf.record.LabelSSTRecord * @see org.apache.poi.hssf.record.ContinueRecord */ public final class SSTRecord extends ContinuableRecord { public static final short sid = 0x00FC; private static final UnicodeString EMPTY_STRING = new UnicodeString(""); // TODO - move these constants to test class (the only consumer) /** standard record overhead: two shorts (record id plus data space size)*/ static final int STD_RECORD_OVERHEAD = 2 * LittleEndianConsts.SHORT_SIZE; /** SST overhead: the standard record overhead, plus the number of strings and the number of unique strings -- two ints */ static final int SST_RECORD_OVERHEAD = STD_RECORD_OVERHEAD + 2 * LittleEndianConsts.INT_SIZE; /** how much data can we stuff into an SST record? That would be _max minus the standard SST record overhead */ static final int MAX_DATA_SPACE = RecordInputStream.MAX_RECORD_DATA_SIZE - 8; /** union of strings in the SST and EXTSST */ private int field_1_num_strings; /** according to docs ONLY SST */ private int field_2_num_unique_strings; private IntMapper field_3_strings; private SSTDeserializer deserializer; /** Offsets from the beginning of the SST record (even across continuations) */ int[] bucketAbsoluteOffsets; /** Offsets relative the start of the current SST or continue record */ int[] bucketRelativeOffsets; public SSTRecord() { field_1_num_strings = 0; field_2_num_unique_strings = 0; field_3_strings = new IntMapper(); deserializer = new SSTDeserializer(field_3_strings); } /** * Add a string. * * @param string string to be added * * @return the index of that string in the table */ public int addString(UnicodeString string) { field_1_num_strings++; UnicodeString ucs = ( string == null ) ? EMPTY_STRING : string; int rval; int index = field_3_strings.getIndex(ucs); if ( index != -1 ) { rval = index; } else { // This is a new string -- we didn't see it among the // strings we've already collected rval = field_3_strings.size(); field_2_num_unique_strings++; SSTDeserializer.addToStringTable( field_3_strings, ucs ); } return rval; } /** * @return number of strings */ public int getNumStrings() { return field_1_num_strings; } /** * @return number of unique strings */ public int getNumUniqueStrings() { return field_2_num_unique_strings; } /** * Get a particular string by its index * * @param id index into the array of strings * * @return the desired string */ public UnicodeString getString(int id ) { return (UnicodeString) field_3_strings.get( id ); } /** * Return a debugging string representation * * @return string representation */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append( "[SST]\n" ); buffer.append( " .numstrings = " ) .append( Integer.toHexString( getNumStrings() ) ).append( "\n" ); buffer.append( " .uniquestrings = " ) .append( Integer.toHexString( getNumUniqueStrings() ) ).append( "\n" ); for ( int k = 0; k < field_3_strings.size(); k++ ) { UnicodeString s = (UnicodeString)field_3_strings.get( k ); buffer.append( " .string_" + k + " = " ) .append( s.getDebugInfo() ).append( "\n" ); } buffer.append( "[/SST]\n" ); return buffer.toString(); } public short getSid() { return sid; } /** * Fill the fields from the data * <P> * The data consists of sets of string data. This string data is * arranged as follows: * <P> * <CODE><pre> * short string_length; // length of string data * byte string_flag; // flag specifying special string * // handling * short run_count; // optional count of formatting runs * int extend_length; // optional extension length * char[] string_data; // string data, can be byte[] or * // short[] (length of array is * // string_length) * int[] formatting_runs; // optional formatting runs (length of * // array is run_count) * byte[] extension; // optional extension (length of array * // is extend_length) * </pre></CODE> * <P> * The string_flag is bit mapped as follows: * <P> * <TABLE> * <TR> * <TH>Bit number</TH> * <TH>Meaning if 0</TH> * <TH>Meaning if 1</TH> * <TR> * <TR> * <TD>0</TD> * <TD>string_data is byte[]</TD> * <TD>string_data is short[]</TH> * <TR> * <TR> * <TD>1</TD> * <TD>Should always be 0</TD> * <TD>string_flag is defective</TH> * <TR> * <TR> * <TD>2</TD> * <TD>extension is not included</TD> * <TD>extension is included</TH> * <TR> * <TR> * <TD>3</TD> * <TD>formatting run data is not included</TD> * <TD>formatting run data is included</TH> * <TR> * <TR> * <TD>4</TD> * <TD>Should always be 0</TD> * <TD>string_flag is defective</TH> * <TR> * <TR> * <TD>5</TD> * <TD>Should always be 0</TD> * <TD>string_flag is defective</TH> * <TR> * <TR> * <TD>6</TD> * <TD>Should always be 0</TD> * <TD>string_flag is defective</TH> * <TR> * <TR> * <TD>7</TD> * <TD>Should always be 0</TD> * <TD>string_flag is defective</TH> * <TR> * </TABLE> * <P> * We can handle eating the overhead associated with bits 2 or 3 * (or both) being set, but we have no idea what to do with the * associated data. The UnicodeString class can handle the byte[] * vs short[] nature of the actual string data * * @param in the RecordInputstream to read the record from */ public SSTRecord(RecordInputStream in) { // this method is ALWAYS called after construction -- using // the nontrivial constructor, of course -- so this is where // we initialize our fields field_1_num_strings = in.readInt(); field_2_num_unique_strings = in.readInt(); field_3_strings = new IntMapper(); deserializer = new SSTDeserializer(field_3_strings); deserializer.manufactureStrings( field_2_num_unique_strings, in ); } /** * @return an iterator of the strings we hold. All instances are * UnicodeStrings */ Iterator getStrings() { return field_3_strings.iterator(); } /** * @return count of the strings we hold. */ int countStrings() { return field_3_strings.size(); } protected void serialize(ContinuableRecordOutput out) { SSTSerializer serializer = new SSTSerializer(field_3_strings, getNumStrings(), getNumUniqueStrings() ); serializer.serialize(out); bucketAbsoluteOffsets = serializer.getBucketAbsoluteOffsets(); bucketRelativeOffsets = serializer.getBucketRelativeOffsets(); } SSTDeserializer getDeserializer() { return deserializer; } /** * Creates an extended string record based on the current contents of * the current SST record. The offset within the stream to the SST record * is required because the extended string record points directly to the * strings in the SST record. * <p> * NOTE: THIS FUNCTION MUST ONLY BE CALLED AFTER THE SST RECORD HAS BEEN * SERIALIZED. * * @param sstOffset The offset in the stream to the start of the * SST record. * @return The new SST record. */ public ExtSSTRecord createExtSSTRecord(int sstOffset) { if (bucketAbsoluteOffsets == null || bucketAbsoluteOffsets == null) throw new IllegalStateException("SST record has not yet been serialized."); ExtSSTRecord extSST = new ExtSSTRecord(); extSST.setNumStringsPerBucket((short)8); int[] absoluteOffsets = bucketAbsoluteOffsets.clone(); int[] relativeOffsets = bucketRelativeOffsets.clone(); for ( int i = 0; i < absoluteOffsets.length; i++ ) absoluteOffsets[i] += sstOffset; extSST.setBucketOffsets(absoluteOffsets, relativeOffsets); return extSST; } /** * Calculates the size in bytes of the EXTSST record as it would be if the * record was serialized. * * @return The size of the ExtSST record in bytes. */ public int calcExtSSTRecordSize() { return ExtSSTRecord.getRecordSizeForStrings(field_3_strings.size()); } }
mit
carlo-/MalmoAgent
src/domain/fluents/Have.java
593
package domain.fluents; import domain.AtomicFluent; import main.Observations; public class Have implements AtomicFluent { private final String mItem; private final int mNumberOf; public Have(String item, int numberOf) { mItem = item; mNumberOf = numberOf; } public String getItem() { return mItem; } public int getmNumberOf() { return mNumberOf; } @Override public boolean test(Observations observations) { int i = observations.numberOf(mItem); boolean b = i >= mNumberOf; return b; } }
mit
mientjan/node-flump
src/core/util/LinkedList.ts
12382
/* * LinkedList * * The MIT License (MIT) * * Copyright (c) 2013 Basarat Ali Syed * Copyright (c) 2013 Mauricio Santos * Copyright (c) 2015 Mient-jan Stelling * * 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. */ export class LinkedList<T> { /** * First node in the list * @type {Object} * @private */ public firstNode:ILinkedListNode<T> = null; /** * Last node in the list * @type {Object} * @private */ private lastNode:ILinkedListNode<T> = null; /** * Number of elements in the list * @type {number} * @private */ private numberOfNodes:number = 0; /** * Creates an empty Linked List. * @class A linked list is a data structure consisting of a group of nodes * which together represent a sequence. * @constructor */ constructor() { } /** * Adds an element to this list. * @param {Object} item element to be added. * @param {number=} index optional index to add the element. If no index is specified * the element is added to the end of this list. * @return {boolean} true if the element was added or false if the index is invalid * or if the element is undefined. */ public add(item:T, index:number = this.numberOfNodes):boolean { if(index < 0 || index > this.numberOfNodes) { return false; } var newNode = this.createNode(item); if(this.numberOfNodes === 0) { // First node in the list. this.firstNode = newNode; this.lastNode = newNode; } else if(index === this.numberOfNodes) { // Insert at the end. this.lastNode.next = newNode; this.lastNode = newNode; } else if(index === 0) { // Change first node. newNode.next = this.firstNode; this.firstNode = newNode; } else { var prev = this.nodeAtIndex(index - 1); newNode.next = prev.next; prev.next = newNode; } this.numberOfNodes++; return true; } /** * Returns the first element in this list. * @return {*} the first element of the list or undefined if the list is * empty. */ public first():T { if(this.firstNode !== null) { return this.firstNode.element; } return undefined; } /** * Returns the last element in this list. * @return {*} the last element in the list or undefined if the list is * empty. */ public last():T { if(this.lastNode !== null) { return this.lastNode.element; } return undefined; } /** * Returns the element at the specified position in this list. * @param {number} index desired index. * @return {*} the element at the given index or undefined if the index is * out of bounds. */ public elementAtIndex(index:number):T { var node = this.nodeAtIndex(index); if(node === null) { return undefined; } return node.element; } /** * Returns the index in this list of the first occurrence of the * specified element, or -1 if the List does not contain this element. * <p>If the elements inside this list are * not comparable with the === operator a custom equals function should be * provided to perform searches, the function must receive two arguments and * return true if they are equal, false otherwise. Example:</p> * * <pre> * var petsAreEqualByName = function(pet1, pet2) { * return pet1.name === pet2.name; * } * </pre> * @param {Object} item element to search for. * @param {function(Object,Object):boolean=} equalsFunction Optional * function used to check if two elements are equal. * @return {number} the index in this list of the first occurrence * of the specified element, or -1 if this list does not contain the * element. */ public indexOf(item:T, equalsFunction?:(a: T, b: T) => boolean):number { var equalsF = equalsFunction || defaultEquals; var currentNode = this.firstNode; var index = 0; while(currentNode !== null) { if(equalsF(currentNode.element, item)) { return index; } index++; currentNode = currentNode.next; } return -1; } /** * Returns true if this list contains the specified element. * <p>If the elements inside the list are * not comparable with the === operator a custom equals function should be * provided to perform searches, the function must receive two arguments and * return true if they are equal, false otherwise. Example:</p> * * <pre> * var petsAreEqualByName = function(pet1, pet2) { * return pet1.name === pet2.name; * } * </pre> * @param {Object} item element to search for. * @param {function(Object,Object):boolean=} equalsFunction Optional * function used to check if two elements are equal. * @return {boolean} true if this list contains the specified element, false * otherwise. */ public contains(item:T, equalsFunction?:IEqualsFunction<T>):boolean { return (this.indexOf(item, equalsFunction) >= 0); } /** * Removes the first occurrence of the specified element in this list. * <p>If the elements inside the list are * not comparable with the === operator a custom equals function should be * provided to perform searches, the function must receive two arguments and * return true if they are equal, false otherwise. Example:</p> * * <pre> * var petsAreEqualByName = function(pet1, pet2) { * return pet1.name === pet2.name; * } * </pre> * @param {Object} item element to be removed from this list, if present. * @return {boolean} true if the list contained the specified element. */ public remove(item:T, equalsFunction?:IEqualsFunction<T>):boolean { var equalsF = equalsFunction || defaultEquals; if(this.numberOfNodes < 1) { return false; } var previous:ILinkedListNode<T> = null; var currentNode:ILinkedListNode<T> = this.firstNode; while(currentNode !== null) { if(equalsF(currentNode.element, item)) { if(currentNode === this.firstNode) { this.firstNode = this.firstNode.next; if(currentNode === this.lastNode) { this.lastNode = null; } } else if(currentNode === this.lastNode) { this.lastNode = previous; previous.next = currentNode.next; currentNode.next = null; } else { previous.next = currentNode.next; currentNode.next = null; } this.numberOfNodes--; return true; } previous = currentNode; currentNode = currentNode.next; } return false; } /** * Removes all of the elements from this list. */ public clear():void { this.firstNode = null; this.lastNode = null; this.numberOfNodes = 0; } /** * Returns true if this list is equal to the given list. * Two lists are equal if they have the same elements in the same order. * @param {LinkedList} other the other list. * @param {function(Object,Object):boolean=} equalsFunction optional * function used to check if two elements are equal. If the elements in the lists * are custom objects you should provide a function, otherwise * the === operator is used to check equality between elements. * @return {boolean} true if this list is equal to the given list. */ public equals(other:LinkedList<T>, equalsFunction?:IEqualsFunction<T>):boolean { var eqF = equalsFunction || defaultEquals; if(!(other instanceof LinkedList)) { return false; } if(this.size() !== other.size()) { return false; } return this.equalsAux(this.firstNode, other.firstNode, eqF); } /** * @private */ private equalsAux(n1:ILinkedListNode<T>, n2:ILinkedListNode<T>, eqF:IEqualsFunction<T>):boolean { while(n1 !== null) { if(!eqF(n1.element, n2.element)) { return false; } n1 = n1.next; n2 = n2.next; } return true; } /** * Removes the element at the specified position in this list. * @param {number} index given index. * @return {*} removed element or undefined if the index is out of bounds. */ public removeElementAtIndex(index:number):T { if(index < 0 || index >= this.numberOfNodes) { return undefined; } var element:T; if(this.numberOfNodes === 1) { //First node in the list. element = this.firstNode.element; this.firstNode = null; this.lastNode = null; } else { var previous = this.nodeAtIndex(index - 1); if(previous === null) { element = this.firstNode.element; this.firstNode = this.firstNode.next; } else if(previous.next === this.lastNode) { element = this.lastNode.element; this.lastNode = previous; } if(previous !== null) { element = previous.next.element; previous.next = previous.next.next; } } this.numberOfNodes--; return element; } /** * Executes the provided function once for each element present in this list in order. * @param {function(Object):*} callback function to execute, it is * invoked with one argument: the element value, to break the iteration you can * optionally return false. */ public forEach(callback:(item:T) => any):void { var currentNode = this.firstNode; while(currentNode !== null) { callback(currentNode.element) currentNode = currentNode.next; } } /** * Reverses the order of the elements in this linked list (makes the last * element first, and the first element last). */ public reverse():void { var previous:ILinkedListNode<T> = null; var current:ILinkedListNode<T> = this.firstNode; var temp:ILinkedListNode<T> = null; while(current !== null) { temp = current.next; current.next = previous; previous = current; current = temp; } temp = this.firstNode; this.firstNode = this.lastNode; this.lastNode = temp; } /** * Returns an array containing all of the elements in this list in proper * sequence. * @return {Array.<*>} an array containing all of the elements in this list, * in proper sequence. */ public toArray():T[] { var array:T[] = []; var currentNode:ILinkedListNode<T> = this.firstNode; while(currentNode !== null) { array.push(currentNode.element); currentNode = currentNode.next; } return array; } /** * Returns the number of elements in this list. * @return {number} the number of elements in this list. */ public size():number { return this.numberOfNodes; } /** * Returns true if this list contains no elements. * @return {boolean} true if this list contains no elements. */ public isEmpty():boolean { return this.numberOfNodes <= 0; } public toString():string { return this.toArray().toString(); } /** * @private */ private nodeAtIndex(index:number):ILinkedListNode<T> { if(index < 0 || index >= this.numberOfNodes) { return null; } if(index === (this.numberOfNodes - 1)) { return this.lastNode; } var node = this.firstNode; for(var i = 0; i < index; i++) { node = node.next; } return node; } /** * @private */ private createNode(item:T):ILinkedListNode<T> { return { element: item, next: null }; } } export interface ILinkedListNode<T> { element: T; next: ILinkedListNode<T>; } export class LinkedListNode<T> implements ILinkedListNode<T> { element: T; next: ILinkedListNode<T>; constructor(element:T, next?:LinkedListNode<T>){ this.element = element; this.next = next; } } /** * Function signature for checking equality */ export interface IEqualsFunction<T>{ (a: T, b: T): boolean; } export function defaultEquals<T>(a: T, b: T): boolean { return a === b; }
mit
NextLight/PokeBattle_Client
PokeBattle_Client/PokeBattle_Client/Popup.cs
1540
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace PokeBattle_Client { public class Popup : Grid { private Button btnClose; public event EventHandler Closed; // I can't use xaml because someone decided that xaml-defined controls can't be used as base for other controls (i.e. PokemonPicker) public Popup() { Loaded += Popup_Loaded; btnClose = new Button { Content = 'X', HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top, Width = Height = 25, FontSize = 16 }; btnClose.Click += btnClose_Click; Children.Add(new Rectangle { Fill = Brushes.White, Opacity = 0.8 }); Children.Add(btnClose); } private void Popup_Loaded(object sender, RoutedEventArgs e) { Height = double.NaN; // auto if (ColumnDefinitions.Count > 0) { SetColumnSpan(Children[0], ColumnDefinitions.Count); SetColumnSpan(Children[1], ColumnDefinitions.Count); } } public bool CanClose { set { btnClose.Visibility = value ? Visibility.Visible : Visibility.Hidden; } } private void btnClose_Click(object sender, RoutedEventArgs e) { Visibility = Visibility.Hidden; Closed?.Invoke(this, null); } } }
mit
aprendecondedos/learning-analytics
models/log.js
866
'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; /** * Logging Mongo Schema * event: {create, update, delete} */ var logSchema = new Schema({ //type: { // type: String, // required: true //}, //event: { // type: String, // required: true //}, //idEvent: { // type: Number, // required: true //}, //action: { // type: String //}, //user: { // type: Number //}, scope: { type: String }, event: { type: String }, data: Schema.Types.Mixed, ipAddress: { type: String, validate: { validator: function(v) { return /^(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}$/.test(v); }, message: '{VALUE} is not a valid IP' } }, time: { type: Date, default: Date.now } }); mongoose.model('Log', logSchema);
mit
Vovkasquid/compassApp
alljoyn/common/os/posix/Condition.cc
3564
/** * @file * * This file implements qcc::Condition for Posix systems */ /****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <assert.h> #include <pthread.h> #include <errno.h> #if defined(QCC_OS_DARWIN) #include <sys/time.h> #endif #include <qcc/Debug.h> #include <qcc/Condition.h> #define QCC_MODULE "CONDITION" using namespace qcc; Condition::Condition() { int ret = pthread_cond_init(&c, NULL); if (ret != 0) { QCC_LogError(ER_OS_ERROR, ("Condition::Condition(): Cannot initialize pthread condition variable (%d)", ret)); } assert(ret == 0 && "Condition::Condition(): Cannot initialize pthread condition variable"); } Condition::~Condition() { int ret = pthread_cond_destroy(&c); if (ret != 0) { QCC_LogError(ER_OS_ERROR, ("Condition::Condition(): Cannot destroy pthread condition variable (%d)", ret)); } assert(ret == 0 && "Condition::Condition(): Cannot destroy pthread condition variable"); } QStatus Condition::Wait(qcc::Mutex& m) { int ret = pthread_cond_wait(&c, &m.mutex); if (ret != 0) { QCC_LogError(ER_OS_ERROR, ("Condition::Wait(): Cannot wait on pthread condition variable (%d)", ret)); return ER_OS_ERROR; } return ER_OK; } QStatus Condition::TimedWait(qcc::Mutex& m, uint32_t ms) { struct timespec tsTimeout; tsTimeout.tv_sec = ms / 1000; tsTimeout.tv_nsec = (ms % 1000) * 1000000; struct timespec tsNow; #if defined(QCC_OS_DARWIN) struct timeval tvNow; gettimeofday(&tvNow, NULL); TIMEVAL_TO_TIMESPEC(&tvNow, &tsNow); #else clock_gettime(CLOCK_REALTIME, &tsNow); #endif tsTimeout.tv_nsec += tsNow.tv_nsec; tsTimeout.tv_sec += tsTimeout.tv_nsec / 1000000000; tsTimeout.tv_nsec %= 1000000000; tsTimeout.tv_sec += tsNow.tv_sec; int ret = pthread_cond_timedwait(&c, &m.mutex, &tsTimeout); if (ret == 0) { return ER_OK; } if (ret == ETIMEDOUT) { return ER_TIMEOUT; } QCC_LogError(ER_OS_ERROR, ("Condition::TimedWait(): Cannot wait on pthread condition variable (%d)", ret)); return ER_OS_ERROR; } QStatus Condition::Signal() { int ret = pthread_cond_signal(&c); if (ret != 0) { QCC_LogError(ER_OS_ERROR, ("Condition::Signal(): Cannot signal pthread condition variable (%d)", ret)); return ER_OS_ERROR; } return ER_OK; } QStatus Condition::Broadcast() { int ret = pthread_cond_broadcast(&c); if (ret != 0) { QCC_LogError(ER_OS_ERROR, ("Condition::Broadcast(): Cannot broadcast signal pthread condition variable (%d)", ret)); return ER_OS_ERROR; } return ER_OK; }
mit
pgherveou/lru-cache
test/index.js
8077
/* global DOMException: true, it: true, describe:true, before: true, afterEach: true, it:true */ var LRU = require('lru-cache'), lf = require('localforage'), Promise = require('promise'), chai = require('chai'), expect = chai.expect; lf.setDriver('localStorageWrapper'); /** * wait closure * * @param {Number} time * * @return Promise */ function wait(time) { return function() { return new Promise(function(resolve) { setTimeout(resolve, time); }); }; } afterEach(function () { return lf.clear(); }); describe('basic tests', function () { it('basic', function () { var cache = new LRU(); var p1 = cache .set('key', 'value') .then(function() { return cache.get('key'); }) .then(function(val) { expect(val).to.eq('value'); }); var p2 = cache .get('nada') .then(function(val) { expect(val).to.be.undefined; }); return Promise .all([p1, p2]) .then(function() { expect(cache.length).to.eq(1); }); }); it('least recently set', function () { var cache = new LRU(2); return Promise.resolve() .then(function() { return cache.set('a', 'A'); }) .then(function() { return cache.set('b', 'B'); }) .then(function() { return cache.set('c', 'C'); }) .then(function() { return cache.get('c'); }) .then(function(v) { expect(v).to.eq('C'); }) .then(function() { return cache.get('b'); }) .then(function(v) { expect(v).to.eq('B'); }) .then(function() { return cache.get('a'); }) .then(function(v) { expect(v).to.be.undefined; }); }); it('lru recently gotten', function () { var cache = new LRU(2); return Promise.resolve() .then(function() { return cache.set('a', 'A'); }) .then(function() { return cache.set('b', 'B'); }) .then(function() { return cache.get('a'); }) .then(function() { return cache.set('c', 'C'); }) .then(function() { return cache.get('c'); }) .then(function(v) { expect(v).to.eq('C'); }) .then(function() { return cache.get('b'); }) .then(function(v) { expect(v).to.be.undefined; }) .then(function() { return cache.get('a'); }) .then(function(v) { expect(v).to.eq('A'); }); }); it('del', function () { var cache = new LRU(); return Promise .resolve() .then(function() { return cache.set('a', 'A'); }) .then(function() { return cache.del('a'); }) .then(function() { return cache.get('a'); }) .then(function(v) { expect(v).to.be.undefined; }); }); it('reset', function () { var cache = new LRU(10); return Promise .resolve() .then(function() { return cache.set('a', 'A'); }) .then(function() { return cache.set('b', 'B'); }) .then(function() { return cache.reset(); }) .then(function() { expect(cache.length).to.eq(0); }) .then(function() { return cache.get('a'); }) .then(function(v) { expect(v).to.be.undefined; }) .then(function() { return cache.get('b'); }) .then(function(v) { expect(v).to.be.undefined; }); }); it('item too large', function () { var cache = new LRU({ max: 10, length: function strLength(key, value) { return key.length + value.length; } }); return Promise .resolve() .then(function() { return cache.set('key', 'I am too big to fit!!!'); }) .catch(function(err) { expect(err.message).to.eq('oversized'); }) .then(function() { return cache.get('key'); }) .then(function(v) { expect(v).to.be.undefined; expect(cache.length).to.eq(0); }); }); it('drop the old items', function() { var cache = new LRU({ maxAge: 300 }); return Promise .resolve() .then(function() { return cache.set('a', 'A'); }) .then(wait(200)) .then(function() { return cache.get('a'); }) .then(function(v) { return expect(v).to.eq('A'); }) .then(wait(400)) .then(function() { return cache.get('a'); }) .then(function(v) { return expect(v).to.be.undefined; }); }); it('lru update via set', function() { var cache = LRU({ max: 2 }); return Promise .resolve() .then( function() { return cache.set('foo', 1); }) .then( function() { return cache.set('bar', 2); }) .then( function() { return cache.del('bar'); }) .then( function() { return cache.set('baz', 3); }) .then( function() { return cache.set('quz', 4); }) .then( function() { return cache.get('foo'); }) .then( function(v) { expect(v).to.be.undefined; }) .then( function() { return cache.get('bar'); }) .then( function(v) { expect(v).to.be.undefined; }) .then( function() { return cache.get('baz'); }) .then( function(v) { expect(v).to.eq(3); }) .then( function() { return cache.get('quz'); }) .then( function(v) { expect(v).to.eq(4); }); }); it('least recently set w/ peek', function () { var cache = LRU({ max: 2 }); return Promise .resolve() .then( function() { return cache.set('a', 'A'); }) .then( function() { return cache.set('b', 'B'); }) .then( function() { return cache.peek('a'); }) .then( function(v) { expect(v).to.eq('A'); }) .then( function() { return cache.set('c', 'C'); }) .then( function() { return cache.get('c'); }) .then( function(v) { expect(v).to.eq('C'); }) .then( function() { return cache.get('b'); }) .then( function(v) { expect(v).to.eq('B'); }) .then( function() { return cache.get('a'); }) .then( function(v) { expect(v).to.be.undefined; }); }); it('should delete stuff when ls quotas reached', function () { var cache = LRU({ max: Math.Infinity }), bigString = '', i = 0; for (var j = 0 ; j <= 1000000; j++) bigString += j%9; return Promise .resolve() .then(function() { return cache.set('first', 'smallstring'); }) // store stuff in ls until it fails .then(function() { while (!localStorage.setItem(i, bigString)) i++; }) .then(function() { return cache.set('one-more', bigString); }) .catch(function(err) { expect(err.code).to.eq(DOMException.QUOTA_EXCEEDED_ERR); }) // make some space in ls and try again .then(function() { localStorage.removeItem(0); return cache.set('one-more', bigString); }) .then(function() { return cache.get('one-more'); }) .then(function(v) { expect(v).to.eq(bigString); }); }); it('keys()', function () { var cache = new LRU({ max: 5 }); var promises =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(i) { return cache.set(i.toString(), i.toString(2)); }); return Promise .all(promises) .then(function() { expect(cache.keys()).to.deep.eq(['9', '8', '7', '6', '5']); }) // get in order of most recently used .then(function() { return cache.get(6); }) .then(function() { return cache.get(8); }) .then(function() { expect(cache.keys()).to.deep.eq(['8', '6', '9', '7', '5']); }); }); }); describe('when reloading', function () { before(function() { var cache = new LRU(); return cache.set('key', 'value'); }); it('should retrieve existing values', function () { var cache = new LRU(); return cache .load() .then(function() { return cache.getEntry('key'); }) .then(function(hit) { expect(hit.key).to.eq('key'); expect(hit.value).to.eq('value'); expect(hit.lu).to.eq(0); expect(hit.age).to.eq(0); expect(cache.length).to.eq(1); }); }); }); describe('when private browsing', function () { it('should retrieve existing values', function (done) { var cache = new LRU(); return cache .load() .catch(function(err) { console.log('err:', err); expect(err).to.be.ok; }) .then(done); }); });
mit
ceolter/angular-grid
grid-packages/ag-grid-enterprise/dist/lib/setFilter/setFilter.d.ts
4012
import { IDoesFilterPassParams, ISetFilterParams, ProvidedFilter, IAfterGuiAttachedParams, AgPromise } from 'ag-grid-community'; import { SetValueModel } from './setValueModel'; import { SetFilterModel } from './setFilterModel'; export declare class SetFilter extends ProvidedFilter { static SELECT_ALL_VALUE: string; private readonly eMiniFilter; private readonly eFilterLoading; private readonly eSetFilterList; private readonly eNoMatches; private readonly valueFormatterService; private valueModel; private setFilterParams; private virtualList; private appliedModelValues; constructor(); protected updateUiVisibility(): void; protected createBodyTemplate(): string; protected handleKeyDown(e: KeyboardEvent): void; private handleKeySpace; private handleKeyEnter; protected getCssIdentifier(): string; private setModelAndRefresh; protected resetUiToDefaults(): AgPromise<void>; protected setModelIntoUi(model: SetFilterModel): AgPromise<void>; getModelFromUi(): SetFilterModel | null; getModel(): SetFilterModel; getFilterType(): string; getValueModel(): SetValueModel; protected areModelsEqual(a: SetFilterModel, b: SetFilterModel): boolean; setParams(params: ISetFilterParams): void; private applyExcelModeOptions; private checkSetFilterDeprecatedParams; private addEventListenersForDataChanges; private syncAfterDataChange; /** @deprecated since version 23.2. The loading screen is displayed automatically when the set filter is retrieving values. */ setLoading(loading: boolean): void; private showOrHideLoadingScreen; private initialiseFilterBodyUi; private initVirtualList; private getSelectAllLabel; private createSetListItem; private initMiniFilter; afterGuiAttached(params?: IAfterGuiAttachedParams): void; applyModel(): boolean; protected isModelValid(model: SetFilterModel): boolean; doesFilterPass(params: IDoesFilterPassParams): boolean; onNewRowsLoaded(): void; /** * Public method provided so the user can change the value of the filter once * the filter has been already started * @param options The options to use. */ setFilterValues(options: string[]): void; /** * Public method provided so the user can reset the values of the filter once that it has started. */ resetFilterValues(): void; refreshFilterValues(): void; onAnyFilterChanged(): void; private onMiniFilterInput; private updateUiAfterMiniFilterChange; private showOrHideResults; private resetUiToActiveModel; private onMiniFilterKeyPress; private filterOnAllVisibleValues; private focusRowIfAlive; private onSelectAll; private onItemSelected; setMiniFilter(newMiniFilter: string): void; getMiniFilter(): string; /** @deprecated since version 23.2. Please use setModel instead. */ selectEverything(): void; /** @deprecated since version 23.2. Please use setModel instead. */ selectNothing(): void; /** @deprecated since version 23.2. Please use setModel instead. */ unselectValue(value: string): void; /** @deprecated since version 23.2. Please use setModel instead. */ selectValue(value: string): void; private refresh; /** @deprecated since version 23.2. Please use getModel instead. */ isValueSelected(value: string): boolean; /** @deprecated since version 23.2. Please use getModel instead. */ isEverythingSelected(): boolean; /** @deprecated since version 23.2. Please use getModel instead. */ isNothingSelected(): boolean; /** @deprecated since version 23.2. Please use getValues instead. */ getUniqueValueCount(): number; /** @deprecated since version 23.2. Please use getValues instead. */ getUniqueValue(index: any): string; getValues(): string[]; refreshVirtualList(): void; private translateForSetFilter; private isSelectAllSelected; destroy(): void; }
mit
SuperSpyTX/MCLib
src/se/jkrau/mclib/org/objectweb/asm/tree/analysis/Subroutine.java
3122
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package se.jkrau.mclib.org.objectweb.asm.tree.analysis; import se.jkrau.mclib.org.objectweb.asm.tree.JumpInsnNode; import se.jkrau.mclib.org.objectweb.asm.tree.LabelNode; import java.util.ArrayList; import java.util.List; /** * A method subroutine (corresponds to a JSR instruction). * * @author Eric Bruneton */ class Subroutine { LabelNode start; boolean[] access; List<JumpInsnNode> callers; private Subroutine() { } Subroutine(final LabelNode start, final int maxLocals, final JumpInsnNode caller) { this.start = start; this.access = new boolean[maxLocals]; this.callers = new ArrayList<JumpInsnNode>(); callers.add(caller); } public Subroutine copy() { Subroutine result = new Subroutine(); result.start = start; result.access = new boolean[access.length]; System.arraycopy(access, 0, result.access, 0, access.length); result.callers = new ArrayList<JumpInsnNode>(callers); return result; } public boolean merge(final Subroutine subroutine) throws AnalyzerException { boolean changes = false; for (int i = 0; i < access.length; ++i) { if (subroutine.access[i] && !access[i]) { access[i] = true; changes = true; } } if (subroutine.start == start) { for (int i = 0; i < subroutine.callers.size(); ++i) { JumpInsnNode caller = subroutine.callers.get(i); if (!callers.contains(caller)) { callers.add(caller); changes = true; } } } return changes; } }
mit
jarofpencils/llamallodge
view/sidebar.php
799
<aside> <!-- These links are for testing only. Remove them from a production application. --> <h2>Links</h2> <ul> <li> <a href="<?php echo $app_path; ?>">Home</a> </li> <li> <a href="<?php echo $app_path . 'admin'; ?>">Admin</a> </li> </ul> <h2>Categories</h2> <ul> <!-- display links for all categories --> <?php foreach ($categories as $category) : ?> <li> <a href="<?php echo $app_path . 'catalog' . '?action=list_products' . '&amp;category_id=' . $category['categoryID']; ?>"> <?php echo $category['categoryName']; ?> </a> </li> <?php endforeach; ?> <li>&nbsp;</li> </ul> </aside>
mit
jfrazelle/s3server
vendor/go.opencensus.io/plugin/ochttp/server.go
6474
// Copyright 2018, OpenCensus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ochttp import ( "bufio" "context" "errors" "net" "net/http" "strconv" "sync" "time" "go.opencensus.io/stats" "go.opencensus.io/tag" "go.opencensus.io/trace" "go.opencensus.io/trace/propagation" ) // Handler is an http.Handler wrapper to instrument your HTTP server with // OpenCensus. It supports both stats and tracing. // // Tracing // // This handler is aware of the incoming request's span, reading it from request // headers as configured using the Propagation field. // The extracted span can be accessed from the incoming request's // context. // // span := trace.FromContext(r.Context()) // // The server span will be automatically ended at the end of ServeHTTP. type Handler struct { // Propagation defines how traces are propagated. If unspecified, // B3 propagation will be used. Propagation propagation.HTTPFormat // Handler is the handler used to handle the incoming request. Handler http.Handler // StartOptions are applied to the span started by this Handler around each // request. // // StartOptions.SpanKind will always be set to trace.SpanKindServer // for spans started by this transport. StartOptions trace.StartOptions // IsPublicEndpoint should be set to true for publicly accessible HTTP(S) // servers. If true, any trace metadata set on the incoming request will // be added as a linked trace instead of being added as a parent of the // current trace. IsPublicEndpoint bool // FormatSpanName holds the function to use for generating the span name // from the information found in the incoming HTTP Request. By default the // name equals the URL Path. FormatSpanName func(*http.Request) string } func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var traceEnd, statsEnd func() r, traceEnd = h.startTrace(w, r) defer traceEnd() w, statsEnd = h.startStats(w, r) defer statsEnd() handler := h.Handler if handler == nil { handler = http.DefaultServeMux } handler.ServeHTTP(w, r) } func (h *Handler) startTrace(w http.ResponseWriter, r *http.Request) (*http.Request, func()) { var name string if h.FormatSpanName == nil { name = spanNameFromURL(r) } else { name = h.FormatSpanName(r) } ctx := r.Context() var span *trace.Span sc, ok := h.extractSpanContext(r) if ok && !h.IsPublicEndpoint { ctx, span = trace.StartSpanWithRemoteParent(ctx, name, sc, trace.WithSampler(h.StartOptions.Sampler), trace.WithSpanKind(trace.SpanKindServer)) } else { ctx, span = trace.StartSpan(ctx, name, trace.WithSampler(h.StartOptions.Sampler), trace.WithSpanKind(trace.SpanKindServer), ) if ok { span.AddLink(trace.Link{ TraceID: sc.TraceID, SpanID: sc.SpanID, Type: trace.LinkTypeChild, Attributes: nil, }) } } span.AddAttributes(requestAttrs(r)...) return r.WithContext(ctx), span.End } func (h *Handler) extractSpanContext(r *http.Request) (trace.SpanContext, bool) { if h.Propagation == nil { return defaultFormat.SpanContextFromRequest(r) } return h.Propagation.SpanContextFromRequest(r) } func (h *Handler) startStats(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, func()) { ctx, _ := tag.New(r.Context(), tag.Upsert(Host, r.URL.Host), tag.Upsert(Path, r.URL.Path), tag.Upsert(Method, r.Method)) track := &trackingResponseWriter{ start: time.Now(), ctx: ctx, writer: w, } if r.Body == nil { // TODO: Handle cases where ContentLength is not set. track.reqSize = -1 } else if r.ContentLength > 0 { track.reqSize = r.ContentLength } stats.Record(ctx, ServerRequestCount.M(1)) return track, track.end } type trackingResponseWriter struct { ctx context.Context reqSize int64 respSize int64 start time.Time statusCode int statusLine string endOnce sync.Once writer http.ResponseWriter } // Compile time assertions for widely used net/http interfaces var _ http.CloseNotifier = (*trackingResponseWriter)(nil) var _ http.Flusher = (*trackingResponseWriter)(nil) var _ http.Hijacker = (*trackingResponseWriter)(nil) var _ http.Pusher = (*trackingResponseWriter)(nil) var _ http.ResponseWriter = (*trackingResponseWriter)(nil) var errHijackerUnimplemented = errors.New("ResponseWriter does not implement http.Hijacker") func (t *trackingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { hj, ok := t.writer.(http.Hijacker) if !ok { return nil, nil, errHijackerUnimplemented } return hj.Hijack() } func (t *trackingResponseWriter) CloseNotify() <-chan bool { cn, ok := t.writer.(http.CloseNotifier) if !ok { return nil } return cn.CloseNotify() } func (t *trackingResponseWriter) Push(target string, opts *http.PushOptions) error { pusher, ok := t.writer.(http.Pusher) if !ok { return http.ErrNotSupported } return pusher.Push(target, opts) } func (t *trackingResponseWriter) end() { t.endOnce.Do(func() { if t.statusCode == 0 { t.statusCode = 200 } span := trace.FromContext(t.ctx) span.SetStatus(TraceStatus(t.statusCode, t.statusLine)) m := []stats.Measurement{ ServerLatency.M(float64(time.Since(t.start)) / float64(time.Millisecond)), ServerResponseBytes.M(t.respSize), } if t.reqSize >= 0 { m = append(m, ServerRequestBytes.M(t.reqSize)) } ctx, _ := tag.New(t.ctx, tag.Upsert(StatusCode, strconv.Itoa(t.statusCode))) stats.Record(ctx, m...) }) } func (t *trackingResponseWriter) Header() http.Header { return t.writer.Header() } func (t *trackingResponseWriter) Write(data []byte) (int, error) { n, err := t.writer.Write(data) t.respSize += int64(n) return n, err } func (t *trackingResponseWriter) WriteHeader(statusCode int) { t.writer.WriteHeader(statusCode) t.statusCode = statusCode t.statusLine = http.StatusText(t.statusCode) } func (t *trackingResponseWriter) Flush() { if flusher, ok := t.writer.(http.Flusher); ok { flusher.Flush() } }
mit
litshares/litshares
src/qt/locale/bitcoin_uk.ts
123478
<?xml version="1.0" ?><!DOCTYPE TS><TS language="uk" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Litshares</source> <translation>Про Litshares</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Litshares&lt;/b&gt; version</source> <translation>Версія &lt;b&gt;Litshares&apos;a&lt;b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Це програмне забезпечення є експериментальним. Поширюється за ліцензією MIT/X11, додаткова інформація міститься у файлі COPYING, а також за адресою http://www.opensource.org/licenses/mit-license.php. Цей продукт включає в себе програмне забезпечення, розроблене в рамках проекту OpenSSL (http://www.openssl.org/), криптографічне програмне забезпечення, написане Еріком Янгом ([email protected]), та функції для роботи з UPnP, написані Томасом Бернардом.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Авторське право</translation> </message> <message> <location line="+0"/> <source>The Litshares developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресна книга</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Двічі клікніть на адресу чи назву для їх зміни</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Створити нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копіювати виділену адресу в буфер обміну</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Створити адресу</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Litshares addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Це ваші адреси для отримання платежів. Ви можете давати різні адреси різним людям, таким чином маючи можливість відслідкувати хто конкретно і скільки вам заплатив.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Скопіювати адресу</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Показати QR-&amp;Код</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Litshares address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Вилучити вибрані адреси з переліку</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Litshares address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Litshares-адресою</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Видалити</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Litshares addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Скопіювати &amp;мітку</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Редагувати</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Експортувати адресну книгу</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли відділені комами (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Помилка при експортуванні</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Назва</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(немає назви)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Діалог введення паролю</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Введіть пароль</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Новий пароль</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Повторіть пароль</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Введіть новий пароль для гаманця.&lt;br/&gt;Будь ласка, використовуйте паролі що містять &lt;b&gt;як мінімум 10 випадкових символів&lt;/b&gt;, або &lt;b&gt;як мінімум 8 слів&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Зашифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ця операція потребує пароль для розблокування гаманця.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Розблокувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ця операція потребує пароль для дешифрування гаманця.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Змінити пароль</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ввести старий та новий паролі для гаманця.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Підтвердити шифрування гаманця</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>УВАГА: Якщо ви зашифруєте гаманець і забудете пароль, ви &lt;b&gt;ВТРАТИТЕ ВСІ СВОЇ БІТКОІНИ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ви дійсно хочете зашифрувати свій гаманець?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Увага: Ввімкнено Caps Lock!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Гаманець зашифровано</translation> </message> <message> <location line="-56"/> <source>Litshares will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your corecoins from being stolen by malware infecting your computer.</source> <translation>Біткоін-клієнт буде закрито для завершення процесу шифрування. Пам&apos;ятайте, що шифрування гаманця не може повністю захистити ваші біткоіни від крадіжки, у випадку якщо ваш комп&apos;ютер буде інфіковано шкідливими програмами.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Не вдалося зашифрувати гаманець</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Виникла помилка під час шифрування гаманця. Ваш гаманець не було зашифровано.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Введені паролі не співпадають.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Не вдалося розблокувати гаманець</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Введений пароль є невірним.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Не вдалося розшифрувати гаманець</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Пароль було успішно змінено.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Підписати повідомлення...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронізація з мережею...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Огляд</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Показати загальний огляд гаманця</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>Транзакції</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Переглянути історію транзакцій</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Редагувати список збережених адрес та міток</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Показати список адрес для отримання платежів</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Вихід</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Вийти</translation> </message> <message> <location line="+4"/> <source>Show information about Litshares</source> <translation>Показати інформацію про Litshares</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Про Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Показати інформацію про Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Параметри...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифрування гаманця...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Резервне копіювання гаманця...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Змінити парол&amp;ь...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Імпорт блоків з диску...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Litshares address</source> <translation>Відправити монети на вказану адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Litshares</source> <translation>Редагувати параметри</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Резервне копіювання гаманця в інше місце</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Змінити пароль, який використовується для шифрування гаманця</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Вікно зневадження</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Відкрити консоль зневадження і діагностики</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Перевірити повідомлення...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Litshares</source> <translation>Litshares</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Litshares</source> <translation>&amp;Про Litshares</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Показати / Приховати</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Показує або приховує головне вікно</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Litshares addresses to prove you own them</source> <translation>Підтвердіть, що Ви є власником повідомлення підписавши його Вашою Litshares-адресою </translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Litshares addresses</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Litshares-адресою</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Налаштування</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Довідка</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Панель вкладок</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> <message> <location line="+47"/> <source>Litshares client</source> <translation>Litshares-клієнт</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Litshares network</source> <translation><numerusform>%n активне з&apos;єднання з мережею</numerusform><numerusform>%n активні з&apos;єднання з мережею</numerusform><numerusform>%n активних з&apos;єднань з мережею</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Оброблено %1 блоків історії транзакцій.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Синхронізовано</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Синхронізується...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Підтвердити комісію</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Надіслані транзакції</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Отримані перекази</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Дата: %1 Кількість: %2 Тип: %3 Адреса: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Обробка URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Litshares address or malformed URI parameters.</source> <translation>Неможливо обробити URI! Це може бути викликано неправильною Litshares-адресою, чи невірними параметрами URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;розблоковано&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;заблоковано&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Litshares can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Сповіщення мережі</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Редагувати адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Мітка</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Мітка, пов&apos;язана з цим записом адресної книги</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Адреса, пов&apos;язана з цим записом адресної книги. Може бути змінено тільки для адреси відправника.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Нова адреса для отримання</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Нова адреса для відправлення</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Редагувати адресу для отримання</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Редагувати адресу для відправлення</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Введена адреса «%1» вже присутня в адресній книзі.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Litshares address.</source> <translation>Введена адреса «%1» не є коректною адресою в мережі Litshares.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Неможливо розблокувати гаманець.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Не вдалося згенерувати нові ключі.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Litshares-Qt</source> <translation>Litshares-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>версія</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>параметри командного рядка</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Параметри інтерфейсу</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Встановлення мови, наприклад &quot;de_DE&quot; (типово: системна)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Запускати згорнутим</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Показувати заставку під час запуску (типово: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Параметри</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Головні</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Заплатити комісі&amp;ю</translation> </message> <message> <location line="+31"/> <source>Automatically start Litshares after logging in to the system.</source> <translation>Автоматично запускати гаманець при вході до системи.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Litshares on system login</source> <translation>&amp;Запускати гаманець при вході в систему</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Скинути всі параметри клієнта на типові.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Скинути параметри</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Мережа</translation> </message> <message> <location line="+6"/> <source>Automatically open the Litshares client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Автоматично відкривати порт для клієнту біткоін на роутері. Працює лише якщо ваш роутер підтримує UPnP і ця функція увімкнена.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Відображення порту через &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Litshares network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Підключатись до мережі Litshares через SOCKS-проксі (наприклад при використанні Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Підключатись через &amp;SOCKS-проксі:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP проксі:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-адреса проксі-сервера (наприклад 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Порт:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Порт проксі-сервера (наприклад 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS версії:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Версія SOCKS-проксі (наприклад 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Вікно</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Показувати лише іконку в треї після згортання вікна.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>Мінімізувати &amp;у трей</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Згортати замість закриття. Якщо ця опція включена, програма закриється лише після вибору відповідного пункту в меню.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Згортати замість закритт&amp;я</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Відображення</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Мова інтерфейсу користувача:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Litshares.</source> <translation>Встановлює мову інтерфейсу. Зміни набудуть чинності після перезапуску Litshares.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>В&amp;имірювати монети в:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Виберіть одиницю вимірювання монет, яка буде відображатись в гаманці та при відправленні.</translation> </message> <message> <location line="+9"/> <source>Whether to show Litshares addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Відображати адресу в списку транзакцій</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Гаразд</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Скасувати</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Застосувати</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>типово</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Підтвердження скидання параметрів</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Деякі параметри потребують перезапуск клієнта для набуття чинності.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Продовжувати?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Litshares.</source> <translation>Цей параметр набуде чинності після перезапуску Litshares.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Невірно вказано адресу проксі.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Litshares network after a connection is established, but this process has not completed yet.</source> <translation>Показана інформація вже може бути застарілою. Ваш гаманець буде автоматично синхронізовано з мережею Litshares після встановлення підключення, але цей процес ще не завершено.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непідтверджені:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавні транзакції&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Ваш поточний баланс</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Загальна сума всіх транзакцій, які ще не підтверджені, та до цих пір не враховуються в загальному балансі</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>не синхронізовано</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start corecoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Діалог QR-коду</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Запросити Платіж</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Кількість:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Мітка:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Повідомлення:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Зберегти як...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Помилка при кодуванні URI в QR-код.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Невірно введено кількість, будь ласка, перевірте.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Кінцевий URI занадто довгий, спробуйте зменшити текст для мітки / повідомлення.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Зберегти QR-код</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-зображення (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Назва клієнту</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Н/Д</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Версія клієнту</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Інформація</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Використовується OpenSSL версії</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>Мережа</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Кількість підключень</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>В тестовій мережі</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Поточне число блоків</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>Відкрити</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Параметри командного рядка</translation> </message> <message> <location line="+7"/> <source>Show the Litshares-Qt help message to get a list with possible Litshares command-line options.</source> <translation>Показати довідку Litshares-Qt для отримання переліку можливих параметрів командного рядка.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Показати</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Дата збирання</translation> </message> <message> <location line="-104"/> <source>Litshares - Debug window</source> <translation>Litshares - Вікно зневадження</translation> </message> <message> <location line="+25"/> <source>Litshares Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Файл звіту зневадження</translation> </message> <message> <location line="+7"/> <source>Open the Litshares debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Очистити консоль</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Litshares RPC console.</source> <translation>Вітаємо у консолі Litshares RPC.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Використовуйте стрілки вгору вниз для навігації по історії, і &lt;b&gt;Ctrl-L&lt;/b&gt; для очищення екрана.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Наберіть &lt;b&gt;help&lt;/b&gt; для перегляду доступних команд.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Відправити</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Відправити на декілька адрес</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Дод&amp;ати одержувача</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Видалити всі поля транзакції</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Підтвердити відправлення</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Відправити</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; адресату %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Підтвердіть відправлення</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ви впевнені що хочете відправити %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> і </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Адреса отримувача невірна, будь ласка перепровірте.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Кількість монет для відправлення повинна бути більшою 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Кількість монет для відправлення перевищує ваш баланс.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Сума перевищить ваш баланс, якщо комісія %1 буде додана до вашої транзакції.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Знайдено адресу що дублюється. Відправлення на кожну адресу дозволяється лише один раз на кожну операцію переказу.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Помилка: Не вдалося створити транзакцію!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Кількість:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Отримувач:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Введіть мітку для цієї адреси для додавання її в адресну книгу</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Мітка:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Видалити цього отримувача</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Litshares address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Litshares (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Підписи - Підпис / Перевірка повідомлення</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Litshares (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Введіть повідомлення, яке ви хочете підписати тут</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Підпис</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Копіювати поточну сигнатуру до системного буферу обміну</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Litshares address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Скинути всі поля підпису повідомлення</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Litshares (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Litshares address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Litshares-адресою</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Скинути всі поля перевірки повідомлення</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Litshares address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Litshares (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Натисніть кнопку «Підписати повідомлення», для отримання підпису</translation> </message> <message> <location line="+3"/> <source>Enter Litshares signature</source> <translation>Введіть сигнатуру Litshares</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Введена нечинна адреса.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Будь ласка, перевірте адресу та спробуйте ще.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Не вдалося підписати повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Повідомлення підписано.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Підпис не можливо декодувати.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Будь ласка, перевірте підпис та спробуйте ще.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Не вдалося перевірити повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Повідомлення перевірено.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Litshares developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/поза інтернетом</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/не підтверджено</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 підтверджень</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Статус</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Згенеровано</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Відправник</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Отримувач</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>Мітка</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Кредит</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>не прийнято</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Дебет</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Комісія за транзакцію</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Загальна сума</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Повідомлення</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Коментар</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID транзакції</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Після генерації монет, потрібно зачекати 60 блоків, перш ніж їх можна буде використати. Коли ви згенерували цей блок, його було відправлено в мережу для того, щоб він був доданий до ланцюжка блоків. Якщо ця процедура не вдасться, статус буде змінено на «не підтверджено» і ви не зможете потратити згенеровані монету. Таке може статись, якщо хтось інший згенерував блок на декілька секунд раніше.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Транзакція</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ще не було успішно розіслано</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>невідомий</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Деталі транзакції</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Даний діалог показує детальну статистику по вибраній транзакції</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Кількість</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Поза інтернетом (%1 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Непідтверджено (%1 із %2 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Підтверджено (%1 підтверджень)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Цей блок не був отриманий жодними іншими вузлами і, ймовірно, не буде прийнятий!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Згенеровано, але не підтверджено</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Отримано</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Отримано від</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Відправлено</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Відправлено собі</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Добуто</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(недоступно)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Статус транзакції. Наведіть вказівник на це поле, щоб показати кількість підтверджень.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Дата і час, коли транзакцію було отримано.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Тип транзакції.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Адреса отримувача транзакції.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Сума, додана чи знята з балансу.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Всі</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Сьогодні</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>На цьому тижні</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>На цьому місяці</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Минулого місяця</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Цього року</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Проміжок...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Отримані на</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Відправлені на</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Відправлені собі</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Добуті</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Інше</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Введіть адресу чи мітку для пошуку</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Мінімальна сума</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Скопіювати адресу</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Скопіювати мітку</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Копіювати кількість</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Редагувати мітку</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Показати деталі транзакції</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Експортувати дані транзакцій</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли, розділені комою (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Підтверджені</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Мітка</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>Ідентифікатор</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Помилка експорту</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Діапазон від:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>до</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Відправити</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Виникла помилка при спробі зберегти гаманець в новому місці.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Успішне створення резервної копії</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Данні гаманця успішно збережено в новому місці призначення.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Litshares version</source> <translation>Версія</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or corecoind</source> <translation>Відправити команду серверу -server чи демону</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Список команд</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Отримати довідку по команді</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Параметри:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: corecoin.conf)</source> <translation>Вкажіть файл конфігурації (типово: corecoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: corecoind.pid)</source> <translation>Вкажіть pid-файл (типово: corecoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Вкажіть робочий каталог</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Встановити розмір кешу бази даних в мегабайтах (типово: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Чекати на з&apos;єднання на &lt;port&gt; (типово: 9333 або тестова мережа: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Підтримувати не більше &lt;n&gt; зв&apos;язків з колегами (типово: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Поріг відключення неправильно під&apos;єднаних пірів (типово: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Максимальній розмір вхідного буферу на одне з&apos;єднання (типово: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Прослуховувати &lt;port&gt; для JSON-RPC-з&apos;єднань (типово: 9332 або тестова мережа: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Приймати команди із командного рядка та команди JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Запустити в фоновому режимі (як демон) та приймати команди</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Використовувати тестову мережу</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=corecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Litshares Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Litshares is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Увага: встановлено занадто велику комісію (-paytxfee). Комісія зніматиметься кожен раз коли ви проводитимете транзакції.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Litshares will not work properly.</source> <translation>Увага: будь ласка, перевірте дату і час на своєму комп&apos;ютері. Якщо ваш годинник йде неправильно, Litshares може працювати некоректно.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Увага: помилка читання wallet.dat! Всі ключі прочитано коректно, але дані транзакцій чи записи адресної книги можуть бути пропущені, або пошкоджені.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Увага: файл wallet.dat пошкоджено, дані врятовано! Оригінальний wallet.dat збережено як wallet.{timestamp}.bak до %s; якщо Ваш баланс чи транзакції неправильні, Ви можете відновити їх з резервної копії. </translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Спроба відновити закриті ключі з пошкодженого wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Підключитись лише до вказаного вузла</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Помилка ініціалізації бази даних блоків</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Помилка завантаження бази даних блоків</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Помилка: Мало вільного місця на диску!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Помилка: Гаманець заблокований, неможливо створити транзакцію!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Помилка: системна помилка: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Скільки блоків перевіряти під час запуску (типово: 288, 0 = всі)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Імпорт блоків з зовнішнього файлу blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Помилка в адресі -tor: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Максимальний буфер, &lt;n&gt;*1000 байт (типово: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Максимальній розмір вихідного буферу на одне з&apos;єднання, &lt;n&gt;*1000 байт (типово: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Виводити більше налагоджувальної інформації. Мається на увазі всі шнші -debug* параметри</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Доповнювати налагоджувальний вивід відміткою часу</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Litshares Wiki for SSL setup instructions)</source> <translation>Параметри SSL: (див. Litshares Wiki для налаштування SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Вибір версії socks-проксі для використання (4-5, типово: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Відсилати налагоджувальну інформацію на консоль, а не у файл debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Відсилати налагоджувальну інформацію до налагоджувача</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Встановити максимальний розмір блоку у байтах (типово: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Встановити мінімальний розмір блоку у байтах (типово: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Стискати файл debug.log під час старту клієнта (типово: 1 коли відсутутній параметр -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Вказати тайм-аут підключення у мілісекундах (типово: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Системна помилка: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Ім&apos;я користувача для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Попередження</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Увага: Поточна версія застаріла, необхідне оновлення!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat пошкоджено, відновлення не вдалося</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Пароль для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Дозволити JSON-RPC-з&apos;єднання з вказаної IP-адреси</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Відправляти команди на вузол, запущений на &lt;ip&gt; (типово: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Модернізувати гаманець до останнього формату</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Встановити розмір пулу ключів &lt;n&gt; (типово: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Пересканувати ланцюжок блоків, в пошуку втрачених транзакцій</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Використовувати OpenSSL (https) для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Файл сертифіката сервера (типово: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Закритий ключ сервера (типово: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Допустимі шифри (типово: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Дана довідка</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Підключитись через SOCKS-проксі</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Дозволити пошук в DNS для команд -addnode, -seednode та -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Завантаження адрес...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Помилка при завантаженні wallet.dat: Гаманець пошкоджено</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Litshares</source> <translation>Помилка при завантаженні wallet.dat: Гаманець потребує новішої версії Біткоін-клієнта</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Litshares to complete</source> <translation>Потрібно перезаписати гаманець: перезапустіть Біткоін-клієнт для завершення</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Помилка при завантаженні wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Помилка в адресі проксі-сервера: «%s»</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Невідома мережа вказана в -onlynet: «%s»</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Помилка у величині комісії -paytxfee=&lt;amount&gt;: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Некоректна кількість</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Недостатньо коштів</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Завантаження індексу блоків...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Додати вузол до підключення і лишити його відкритим</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Litshares is probably already running.</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері. Можливо гаманець вже запущено.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Комісія за КБ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Завантаження гаманця...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Неможливо записати типову адресу</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Сканування...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Завантаження завершене</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Ви мусите встановити rpcpassword=&lt;password&gt; в файлі конфігурації: %s Якщо файл не існує, створіть його із правами тільки для читання власником (owner-readable-only).</translation> </message> </context> </TS>
mit
MonsieurOenologue/Curriculum-vit-
cache/compiled/files/8a9c566bf90f01bb7b4098c1f1692a8b.yaml.php
7597
<?php return [ '@class' => 'Grav\\Common\\File\\CompiledYamlFile', 'filename' => 'user/plugins/admin/blueprints.yaml', 'modified' => 1448321491, 'data' => [ 'name' => 'Admin Panel', 'version' => '1.0.0-rc.6', 'description' => 'Adds an advanced administration panel to manage your site', 'icon' => 'empire', 'author' => [ 'name' => 'Team Grav', 'email' => '[email protected]', 'url' => 'http://getgrav.org' ], 'homepage' => 'https://github.com/getgrav/grav-plugin-admin', 'keywords' => 'admin, plugin, manager, panel', 'bugs' => 'https://github.com/getgrav/grav-plugin-admin/issues', 'readme' => 'https://github.com/getgrav/grav-plugin-admin/blob/develop/README.md', 'license' => 'MIT', 'dependencies' => [ 0 => 'form', 1 => 'email', 2 => 'login' ], 'form' => [ 'validation' => 'loose', 'fields' => [ 'Basics' => [ 'type' => 'section', 'title' => 'Basics', 'underline' => false ], 'enabled' => [ 'type' => 'hidden', 'label' => 'Plugin status', 'highlight' => 1, 'default' => 0, 'options' => [ 1 => 'Enabled', 0 => 'Disabled' ], 'validate' => [ 'type' => 'bool' ] ], 'route' => [ 'type' => 'text', 'label' => 'Administrator path', 'size' => 'medium', 'placeholder' => 'Default route for administrator (relative to base)', 'help' => 'If you want to change the URL for the administrator, you can provide a path here' ], 'theme' => [ 'type' => 'hidden', 'label' => 'Theme', 'default' => 'grav' ], 'edit_mode' => [ 'type' => 'select', 'label' => 'Edit mode', 'size' => 'small', 'default' => 'normal', 'options' => [ 'normal' => 'Normal', 'expert' => 'Expert' ], 'help' => 'Auto will use blueprint if available, if none found, it will use "Expert" mode.' ], 'google_fonts' => [ 'type' => 'toggle', 'label' => 'Use Google Fonts', 'highlight' => 1, 'default' => 1, 'options' => [ 1 => 'Enabled', 0 => 'Disabled' ], 'validate' => [ 'type' => 'bool' ], 'help' => 'Use Google custom fonts. Disable this to use Helvetica. Useful when using Cyrillic and other languages with unsupported characters.' ], 'show_beta_msg' => [ 'type' => 'toggle', 'label' => 'Show Beta Message', 'highlight' => 1, 'default' => 1, 'options' => [ 1 => 'Enabled', 0 => 'Disabled' ], 'validate' => [ 'type' => 'bool' ], 'help' => 'Show the beta warning message on the dashboard' ], 'enable_auto_updates_check' => [ 'type' => 'toggle', 'label' => 'Automatically check for updates', 'highlight' => 1, 'default' => 1, 'options' => [ 1 => 'Enabled', 0 => 'Disabled' ], 'validate' => [ 'type' => 'bool' ], 'help' => 'Shows an informative message, in the admin panel, when an update is available.' ], 'session.timeout' => [ 'type' => 'text', 'size' => 'small', 'label' => 'Session Timeout', 'help' => 'Sets the session timeout in seconds', 'validate' => [ 'type' => 'number', 'min' => 1 ] ], 'warnings.delete_page' => [ 'type' => 'toggle', 'label' => 'Warn on page delete', 'highlight' => 1, 'default' => 1, 'options' => [ 1 => 'Enabled', 0 => 'Disabled' ], 'validate' => [ 'type' => 'bool' ], 'help' => 'Ask the user confirmation when deleting a page' ], 'Popularity' => [ 'type' => 'section', 'title' => 'Popularity', 'underline' => true ], 'popularity.enabled' => [ 'type' => 'toggle', 'label' => 'Visitor tracking', 'highlight' => 1, 'default' => 1, 'options' => [ 1 => 'Enabled', 0 => 'Disabled' ], 'validate' => [ 'type' => 'bool' ], 'help' => 'Enable the visitors stats collecting feature' ], 'dashboard.days_of_stats' => [ 'type' => 'text', 'label' => 'Days of stats', 'size' => 'x-small', 'default' => 7, 'help' => 'Keep stats for the specified number of days, then drop them', 'validate' => [ 'type' => 'int' ] ], 'popularity.ignore' => [ 'type' => 'array', 'label' => 'Ignore', 'size' => 'large', 'help' => 'URLs to ignore', 'default' => [ 0 => '/test*', 1 => '/modular' ], 'value_only' => true, 'placeholder_value' => '/ignore-this-route' ], 'popularity.history.daily' => [ 'type' => 'hidden', 'label' => 'Daily history', 'default' => 30 ], 'popularity.history.monthly' => [ 'type' => 'hidden', 'label' => 'Monthly history', 'default' => 12 ], 'popularity.history.visitors' => [ 'type' => 'hidden', 'label' => 'Visitors history', 'default' => 20 ] ] ] ] ];
mit
joshwalawender/POCS
pocs/camera/sbigudrv.py
51519
""" Low level interface to the SBIG Unversal Driver/Library. Reproduces in Python (using ctypes) the C interface provided by SBIG's shared library, i.e. 1 function that does 72 different things selected by passing an integer as the first argument. This is basically a direct translation of the enums and structs defined in the library C-header to Python dicts and ctypes.Structures, plus a class (SBIGDriver) to load the library and call the single command function (SBIGDriver._send_command()). """ import platform import ctypes from ctypes.util import find_library import _ctypes import os import time from threading import Timer, Lock import numpy as np from numpy.ctypeslib import as_ctypes from astropy import units as u from astropy.io import fits from astropy.time import Time from .. import PanBase ################################################################################ # Main SBIGDriver class ################################################################################ class SBIGDriver(PanBase): def __init__(self, library_path=False, *args, **kwargs): """ Main class representing the SBIG Universal Driver/Library interface. On construction loads SBIG's shared library which must have already been installed (see http://archive.sbig.com/sbwhtmls/devsw.htm). The name and location of the shared library can be manually specified with the library_path argument, otherwise the ctypes.util.find_library function will be used to locate it. Args: library_path (string, optional): shared library path, e.g. '/usr/local/lib/libsbigudrv.so' Returns: `~pocs.camera.sbigudrv.SBIGDriver` """ super().__init__(*args, **kwargs) # Open library self.logger.debug('Opening SBIGUDrv library') if not library_path: library_path = find_library('sbigudrv') if library_path is None: self.logger.error('Could not find SBIG Universal Driver/Library!') raise RuntimeError('Could not find SBIG Universal Driver/Library!') # This CDLL loader will raise OSError if the library could not be loaded self._CDLL = ctypes.CDLL(library_path) # Open driver self.logger.debug('Opening SBIGUDrv driver') self._send_command('CC_OPEN_DRIVER') # Query USB bus for connected cameras, store basic camera info. self.logger.debug('Searching for connected SBIG cameras') self._camera_info = QueryUSBResults2() self._send_command('CC_QUERY_USB2', results=self._camera_info) self._send_command('CC_CLOSE_DRIVER') # Connect to each camera in turn, obtain its 'handle' and and store. self._handles = [] for i in range(self._camera_info.camerasFound): self._send_command('CC_OPEN_DRIVER') odp = OpenDeviceParams(device_type_codes['DEV_USB{}'.format(i + 1)], 0, 0) self._send_command('CC_OPEN_DEVICE', params=odp) elp = EstablishLinkParams() elr = EstablishLinkResults() self._send_command('CC_ESTABLISH_LINK', params=elp, results=elr) ghr = GetDriverHandleResults() self._send_command('CC_GET_DRIVER_HANDLE', results=ghr) self._handles.append(ghr.handle) # This seems to have the side effect of closing both device and # driver. shp = SetDriverHandleParams(INVALID_HANDLE_VALUE) self._send_command('CC_SET_DRIVER_HANDLE', params=shp) # Prepare to keep track of which handles have been assigned to Camera objects self._handle_assigned = [False] * len(self._handles) self._ccd_info = {} # Create a Lock that will used to prevent simultaneous commands from multiple # cameras. Main reason for this is preventing overlapping readouts. self._command_lock = Lock() # Reopen driver ready for next command self._send_command('CC_OPEN_DRIVER') self.logger.info('\t\t\t SBIGDriver initialised: found {} cameras'.format(self._camera_info.camerasFound)) def __del__(self): self.logger.debug('Closing SBIGUDrv driver') # Using Set Handle to do this should ensure that both device and driver are closed # regardless of current state shp = SetDriverHandleParams(INVALID_HANDLE_VALUE) self._send_command('CC_SET_DRIVER_HANDLE', params=shp) # Vain attempt to unload the shared library self.logger.debug('Closing SBIGUDrv library') _ctypes.dlclose(self._CDLL._handle) del self._CDLL def assign_handle(self, serial=None): """ Returns the next unassigned camera handle, along with basic info on the coresponding camera. If passed a serial number will attempt to assign the handle corresponding to a camera with that serial number, raising an error if one is not available. """ if serial: # Look for a connected, unassigned camera with matching serial number # List of serial numbers serials = [str(self._camera_info.usbInfo[i].serialNumber, encoding='ascii') for i in range(self._camera_info.camerasFound)] if serial not in serials: # Camera we're looking for is not connected! self.logger.error('SBIG camera serial number {} not connected!'.format(serial)) return (INVALID_HANDLE_VALUE, None) index = serials.index(serial) if self._handle_assigned[index]: # Camera we're looking for has already been assigned! self.logger.error('SBIG camera serial number {} already assigned!'.format(serial)) return (INVALID_HANDLE_VALUE, None) else: # No serial number specified, just take the first unassigned handle try: index = self._handle_assigned.index(False) except ValueError: # All handles already assigned, must be trying to intialising more cameras than are connected. self.logger.error('No connected SBIG cameras available!') return (INVALID_HANDLE_VALUE, None) handle = self._handles[index] self.logger.debug('Assigning handle {} to SBIG camera'.format(handle)) self._handle_assigned[index] = True # Get all the information from the camera self.logger.debug('Obtaining SBIG camera info from {}'.format(handle)) ccd_info = self._get_ccd_info(handle) # Serial number, name and type should match with those from Query USB Info obtained earlier camera_serial = str(self._camera_info.usbInfo[index].serialNumber, encoding='ascii') assert camera_serial == ccd_info['serial_number'], self.logger.error('Serial number mismatch!') # Keep camera info. self._ccd_info[handle] = ccd_info # Stop camera from skipping lowering of Vdd for exposures of 3 seconds of less self._disable_vdd_optimized(handle) # Return both a handle and the dictionary of camera info return (handle, ccd_info) def query_temp_status(self, handle): query_temp_params = QueryTemperatureStatusParams(temp_status_request_codes['TEMP_STATUS_ADVANCED2']) query_temp_results = QueryTemperatureStatusResults2() with self._command_lock: self._set_handle(handle) self._send_command('CC_QUERY_TEMPERATURE_STATUS', query_temp_params, query_temp_results) return query_temp_results def set_temp_regulation(self, handle, set_point): if set_point is not None: # Passed a value as set_point, turn on cooling. enable_code = temperature_regulation_codes['REGULATION_ON'] if isinstance(set_point, u.Quantity): set_point = set_point.to(u.Celsius).value else: # Passed None as set_point, turn off cooling and reset # set point to +25 C enable_code = temperature_regulation_codes['REGULATION_OFF'] set_point = 25.0 set_temp_params = SetTemperatureRegulationParams2(enable_code, set_point) # Use temperature regulation autofreeze, if available (might marginally reduce read noise). autofreeze_code = temperature_regulation_codes['REGULATION_ENABLE_AUTOFREEZE'] set_freeze_params = SetTemperatureRegulationParams2(autofreeze_code, set_point) with self._command_lock: self._set_handle(handle) self._send_command('CC_SET_TEMPERATURE_REGULATION2', params=set_temp_params) self._send_command('CC_SET_TEMPERATURE_REGULATION2', params=set_freeze_params) def take_exposure(self, handle, seconds, filename, exposure_event=None, dark=False): """ Starts an exposure and spawns thread that will perform readout and write to file when the exposure is complete. """ ccd_info = self._ccd_info[handle] # SBIG driver expects exposure time in 100ths of a second. if isinstance(seconds, u.Quantity): seconds = seconds.to(u.second).value centiseconds = int(seconds * 100) # This setting is ignored by most cameras (even if they do have ABG), only exceptions are the TC211 versions # of the Tracking CCD on the ST-7/8/etc. and the Imaging CCD of the PixCel255 if ccd_info['imaging_ABG']: # Camera supports anti-blooming, use it on medium setting? abg_command_code = abg_state_codes['ABG_CLK_MED7'] else: # Camera doesn't support anti-blooming, don't try to use it. abg_command_code = abg_state_codes['ABG_LOW7'] if not dark: # Normal exposure, will open (and close) shutter shutter_command_code = shutter_command_codes['SC_OPEN_SHUTTER'] else: # Dark frame, will keep shutter closed throughout shutter_command_code = shutter_command_codes['SC_CLOSE_SHUTTER'] # TODO: implement control of binning readout modes. # For now use standard unbinned mode. readout_mode = 'RM_1X1' readout_mode_code = readout_mode_codes[readout_mode] # TODO: implement windowed readout. # For now use full image size for unbinned mode. top = 0 left = 0 height = int(ccd_info['readout_modes'][readout_mode]['height'].value) width = int(ccd_info['readout_modes'][readout_mode]['width'].value) start_exposure_params = StartExposureParams2(ccd_codes['CCD_IMAGING'], centiseconds, abg_command_code, shutter_command_code, readout_mode_code, top, left, height, width) # Make sure there isn't already an exposure in progress on this camera. # If there is then we need to wait otherwise we'll cause a hang. # Could do this with Locks but it's more robust to directly query the hardware. query_status_params = QueryCommandStatusParams(command_codes['CC_START_EXPOSURE2']) query_status_results = QueryCommandStatusResults() with self._command_lock: self._set_handle(handle) self._send_command('CC_QUERY_COMMAND_STATUS', params=query_status_params, results=query_status_results) if query_status_results.status != status_codes['CS_IDLE']: self.logger.warning('Attempt to start exposure on {} while camera busy!'.format(handle)) # Wait until camera is idle while query_status_results.status != status_codes['CS_IDLE']: self.logger.warning('Waiting for exposure on {} to complete'.format(handle)) time.sleep(1) with self._command_lock: self._set_handle(handle) self._send_command('CC_QUERY_COMMAND_STATUS', params=query_status_params, results=query_status_results) # Assemble basic FITS header temp_status = self.query_temp_status(handle) if temp_status.coolingEnabled: if abs(temp_status.imagingCCDTemperature - temp_status.ccdSetpoint) > 0.5 or \ temp_status.imagingCCDPower == 100.0: self.logger.warning('Unstable CCD temperature in {}'.format(handle)) time_now = Time.now() header = fits.Header() header.set('INSTRUME', self._ccd_info[handle]['serial_number']) header.set('DATE-OBS', time_now.fits) header.set('EXPTIME', seconds) header.set('CCD-TEMP', temp_status.imagingCCDTemperature) header.set('SET-TEMP', temp_status.ccdSetpoint) header.set('EGAIN', self._ccd_info[handle]['readout_modes'][readout_mode]['gain'].value) header.set('XPIXSZ', self._ccd_info[handle]['readout_modes'][readout_mode]['pixel_width'].value) header.set('YPIXSZ', self._ccd_info[handle]['readout_modes'][readout_mode]['pixel_height'].value) if dark: header.set('IMAGETYP', 'Dark Frame') else: header.set('IMAGETYP', 'Light Frame') # Start exposure self.logger.debug('Starting {} second exposure on {}'.format(seconds, handle)) with self._command_lock: self._set_handle(handle) self._send_command('CC_START_EXPOSURE2', params=start_exposure_params) # Use a Timer to schedule the exposure readout and return a reference to the Timer. wait = seconds - 0.1 if seconds > 0.1 else 0.0 readout_args = (handle, centiseconds, filename, readout_mode_code, top, left, height, width, header, exposure_event) readout_thread = Timer(interval=wait, function=self._readout, args=readout_args) readout_thread.start() return readout_thread # Private methods def _readout(self, handle, centiseconds, filename, readout_mode_code, top, left, height, width, header, exposure_event=None): """ """ # Set up all the parameter and result Structures that will be needed. end_exposure_params = EndExposureParams(ccd_codes['CCD_IMAGING']) start_readout_params = StartReadoutParams(ccd_codes['CCD_IMAGING'], readout_mode_code, top, left, height, width) query_status_params = QueryCommandStatusParams(command_codes['CC_START_EXPOSURE2']) query_status_results = QueryCommandStatusResults() readout_line_params = ReadoutLineParams(ccd_codes['CCD_IMAGING'], readout_mode_code, left, width) end_readout_params = EndReadoutParams(ccd_codes['CCD_IMAGING']) # Array to hold the image data image_data = np.zeros((height, width), dtype=np.uint16) # Check for the end of the exposure. with self._command_lock: self._set_handle(handle) self._send_command('CC_QUERY_COMMAND_STATUS', params=query_status_params, results=query_status_results) # Poll if needed. while query_status_results.status != status_codes['CS_INTEGRATION_COMPLETE']: self.logger.debug('Waiting for exposure on {} to complete'.format(handle)) time.sleep(0.1) with self._command_lock: self._set_handle(handle) self._send_command('CC_QUERY_COMMAND_STATUS', params=query_status_params, results=query_status_results) self.logger.debug('Exposure on {} complete'.format(handle)) # Readout data with self._command_lock: self._set_handle(handle) self._send_command('CC_END_EXPOSURE', params=end_exposure_params) self._send_command('CC_START_READOUT', params=start_readout_params) for i in range(height): self._send_command('CC_READOUT_LINE', params=readout_line_params, results=as_ctypes(image_data[i])) self._send_command('CC_END_READOUT', params=end_readout_params) self.logger.debug('Readout on {} complete'.format(handle)) # Write to FITS file. Includes basic headers directly related to the camera only. hdu = fits.PrimaryHDU(image_data, header=header) # Create the images directory if it doesn't already exist if os.path.dirname(filename): os.makedirs(os.path.dirname(filename), mode=0o775, exist_ok=True) hdu.writeto(filename) self.logger.debug('Image written to {}'.format(filename)) # Use Event to notify that exposure has completed. if exposure_event: exposure_event.set() def _get_ccd_info(self, handle): """ Use Get CCD Info to gather all relevant info about CCD capabilities. Already have camera type, 'name' and serial number, this gets the rest. """ # 'CCD_INFO_IMAGING' will get firmware version, and a list of readout modes (binning) # with corresponding image widths, heights, gains and also physical pixel width, height. ccd_info_params0 = GetCCDInfoParams(ccd_info_request_codes['CCD_INFO_IMAGING']) ccd_info_results0 = GetCCDInfoResults0() # 'CCD_INFO_EXTENDED' will get bad column info, and whether the CCD has ABG or not. ccd_info_params2 = GetCCDInfoParams(ccd_info_request_codes['CCD_INFO_EXTENDED']) ccd_info_results2 = GetCCDInfoResults2() # 'CCD_INFO_EXTENDED2_IMAGING' will info like full frame/frame transfer, interline or not, # presence of internal frame buffer, etc. ccd_info_params4 = GetCCDInfoParams(ccd_info_request_codes['CCD_INFO_EXTENDED2_IMAGING']) ccd_info_results4 = GetCCDInfoResults4() # 'CCD_INFO_EXTENDED3' will get info like mechanical shutter or not, mono/colour, Bayer/Truesense. ccd_info_params6 = GetCCDInfoParams(ccd_info_request_codes['CCD_INFO_EXTENDED3']) ccd_info_results6 = GetCCDInfoResults6() with self._command_lock: self._set_handle(handle) self._send_command('CC_GET_CCD_INFO', params=ccd_info_params0, results=ccd_info_results0) self._send_command('CC_GET_CCD_INFO', params=ccd_info_params2, results=ccd_info_results2) self._send_command('CC_GET_CCD_INFO', params=ccd_info_params4, results=ccd_info_results4) self._send_command('CC_GET_CCD_INFO', params=ccd_info_params6, results=ccd_info_results6) # Now to convert all this ctypes stuff into Pythonic data structures. ccd_info = {'firmware_version': self._bcd_to_string(ccd_info_results0.firmwareVersion), 'camera_type': camera_types[ccd_info_results0.cameraType], 'camera_name': str(ccd_info_results0.name, encoding='ascii'), 'bad_columns': ccd_info_results2.columns[0:ccd_info_results2.badColumns], 'imaging_ABG': bool(ccd_info_results2.imagingABG), 'serial_number': str(ccd_info_results2.serialNumber, encoding='ascii'), 'frame_transfer': bool(ccd_info_results4.capabilities_b0), 'electronic_shutter': bool(ccd_info_results4.capabilities_b1), 'remote_guide_head_support': bool(ccd_info_results4.capabilities_b2), 'Biorad_TDI_support': bool(ccd_info_results4.capabilities_b3), 'AO8': bool(ccd_info_results4.capabilities_b4), 'frame_buffer': bool(ccd_info_results4.capabilities_b5), 'dump_extra': ccd_info_results4.dumpExtra, 'STXL': bool(ccd_info_results6.camera_b0), 'mechanical_shutter': not bool(ccd_info_results6.camera_b1), 'colour': bool(ccd_info_results6.ccd_b0), 'Truesense': bool(ccd_info_results6.ccd_b1)} readout_mode_info = self._parse_readout_info(ccd_info_results0.readoutInfo[0:ccd_info_results0.readoutModes]) ccd_info['readout_modes'] = readout_mode_info return ccd_info def _bcd_to_int(self, bcd, int_type='ushort'): """ Function to decode the Binary Coded Decimals returned by the Get CCD Info command. These will be integers of C types ushort or ulong, encoding decimal numbers of the form XX.XX or XXXXXX.XX, i.e. when converting to a numerical value they will need dividing by 100. """ # BCD has been automatically converted by ctypes to a Python int. Need to convert to # bytes sequence of correct length and byte order. SBIG library seems to use # big endian byte order for the BCDs regardless of platform. if int_type == 'ushort': bcd = bcd.to_bytes(ctypes.sizeof(ctypes.c_ushort), byteorder='big') elif int_type == 'ulong': bcd = bcd.to_bytes(ctypes.sizeof(ctypes.c_ulong), byteorder='big') else: self.logger.error('Unknown integer type {}!'.format(int_type)) return # Convert bytes sequence to hexadecimal string representation, which will also be the # string representation of the decoded binary coded decimal, apart from possible # leading zeros. Convert back to an int to strip the leading zeros. return int(bcd.hex()) def _bcd_to_float(self, bcd, int_type='ushort'): # Includes conversion to intended numerical value, i.e. division by 100 return self._bcd_to_int(bcd, int_type) / 100.0 def _bcd_to_string(self, bcd, int_type='ushort'): # Includes conversion to intended numerical value, i.e. division by 100 s = str(self._bcd_to_int(bcd, int_type)) return "{}.{}".format(s[:-2], s[-2:]) def _parse_readout_info(self, infos): readout_mode_info = {} for info in infos: mode = readout_modes[info.mode] gain = self._bcd_to_float(info.gain) pixel_width = self._bcd_to_float(info.pixelWidth, int_type='ulong') pixel_height = self._bcd_to_float(info.pixelHeight, int_type='ulong') readout_mode_info[mode] = {'width': info.width * u.pixel, 'height': info.height * u.pixel, 'gain': gain * u.electron / u.adu, 'pixel_width': pixel_width * u.um, 'pixel_height': pixel_height * u.um} return readout_mode_info def _disable_vdd_optimized(self, handle): """ There are many driver control parameters, almost all of which we would not want to change from their default values. The one exception is DCP_VDD_OPTIMIZED. From the SBIG manual: The DCP_VDD_OPTIMIZED parameter defaults to TRUE which lowers the CCD’s Vdd (which reduces amplifier glow) only for images 3 seconds and longer. This was done to increase the image throughput for short exposures as raising and lowering Vdd takes 100s of milliseconds. The lowering and subsequent raising of Vdd delays the image readout slightly which causes short exposures to have a different bias structure than long exposures. Setting this parameter to FALSE stops the short exposure optimization from occurring. The default behaviour will improve image throughput for exposure times of 3 seconds or less but at the penalty of altering the bias structure between short and long exposures. This could cause systematic errors in bias frames, dark current measurements, etc. It's probably not worth it. """ set_driver_control_params = SetDriverControlParams(driver_control_codes['DCP_VDD_OPTIMIZED'], 0) self.logger.debug('Disabling DCP_VDD_OPTIMIZE on {}'.format(handle)) with self._command_lock: self._set_handle(handle) self._send_command('CC_SET_DRIVER_CONTROL', params=set_driver_control_params) def _set_handle(self, handle): set_handle_params = SetDriverHandleParams(handle) self._send_command('CC_SET_DRIVER_HANDLE', params=set_handle_params) def _send_command(self, command, params=None, results=None): """ Function for sending a command to the SBIG Universal Driver/Library. Args: command (string): Name of command to send params (ctypes.Structure, optional): Subclass of Structure containing command parameters results (ctypes.Structure, optional): Subclass of Structure to store command results Returns: int: return code from SBIG driver Raises: KeyError: Raised if command not in SBIG command list RuntimeError: Raised if return code indicates a fatal error, or is not recognised """ # Look up integer command code for the given command string, raises # KeyError if no matches found. try: command_code = command_codes[command] except KeyError: raise KeyError("Invalid SBIG command '{}'!".format(command)) # Send the command to the driver. Need to pass pointers to params, # results structs or None (which gets converted to a null pointer). return_code = self._CDLL.SBIGUnivDrvCommand(command_code, (ctypes.byref(params) if params else None), (ctypes.byref(results) if results else None)) # Look up the error message for the return code, raises Error is no # match found. try: error = errors[return_code] except KeyError: raise RuntimeError("SBIG Driver returned unknown error code '{}'".format(return_code)) # Raise a RuntimeError exception if return code is not 0 (no error). # This is probably excessively cautious and will need to be relaxed, # there are likely to be situations where other return codes don't # necessarily indicate a fatal error. if error != 'CE_NO_ERROR': raise RuntimeError("SBIG Driver returned error '{}'!".format(error)) return error ################################################################################# # Commands and error messages ################################################################################# # Camera command codes. Doesn't include the 'SBIG only" commands. command_codes = {'CC_NULL': 0, 'CC_START_EXPOSURE': 1, 'CC_END_EXPOSURE': 2, 'CC_READOUT_LINE': 3, 'CC_DUMP_LINES': 4, 'CC_SET_TEMPERATURE_REGULATION': 5, 'CC_QUERY_TEMPERATURE_STATUS': 6, 'CC_ACTIVATE_RELAY': 7, 'CC_PULSE_OUT': 8, 'CC_ESTABLISH_LINK': 9, 'CC_GET_DRIVER_INFO': 10, 'CC_GET_CCD_INFO': 11, 'CC_QUERY_COMMAND_STATUS': 12, 'CC_MISCELLANEOUS_CONTROL': 13, 'CC_READ_SUBTRACT_LINE': 14, 'CC_UPDATE_CLOCK': 15, 'CC_READ_OFFSET': 16, 'CC_OPEN_DRIVER': 17, 'CC_CLOSE_DRIVER': 18, 'CC_TX_SERIAL_BYTES': 19, 'CC_GET_SERIAL_STATUS': 20, 'CC_AO_TIP_TILT': 21, 'CC_AO_SET_FOCUS': 22, 'CC_AO_DELAY': 23, 'CC_GET_TURBO_STATUS': 24, 'CC_END_READOUT': 25, 'CC_GET_US_TIMER': 26, 'CC_OPEN_DEVICE': 27, 'CC_CLOSE_DEVICE': 28, 'CC_SET_IRQL': 29, 'CC_GET_IRQL': 30, 'CC_GET_LINE': 31, 'CC_GET_LINK_STATUS': 32, 'CC_GET_DRIVER_HANDLE': 33, 'CC_SET_DRIVER_HANDLE': 34, 'CC_START_READOUT': 35, 'CC_GET_ERROR_STRING': 36, 'CC_SET_DRIVER_CONTROL': 37, 'CC_GET_DRIVER_CONTROL': 38, 'CC_USB_AD_CONTROL': 39, 'CC_QUERY_USB': 40, 'CC_GET_PENTIUM_CYCLE_COUNT': 41, 'CC_RW_USB_I2C': 42, 'CC_CFW': 43, 'CC_BIT_IO': 44, 'CC_USER_EEPROM': 45, 'CC_AO_CENTER': 46, 'CC_BTDI_SETUP': 47, 'CC_MOTOR_FOCUS': 48, 'CC_QUERY_ETHERNET': 49, 'CC_START_EXPOSURE2': 50, 'CC_SET_TEMPERATURE_REGULATION2': 51, 'CC_READ_OFFSET2': 52, 'CC_DIFF_GUIDER': 53, 'CC_COLUMN_EEPROM': 54, 'CC_CUSTOMER_OPTIONS': 55, 'CC_DEBUG_LOG': 56, 'CC_QUERY_USB2': 57, 'CC_QUERY_ETHERNET2': 58} # Reversed dictionary, just in case you ever need to look up a command given a # command code. commands = {code: command for command, code in command_codes.items()} # Camera error messages errors = {0: 'CE_NO_ERROR', 1: 'CE_CAMERA_NOT_FOUND', 2: 'CE_EXPOSURE_IN_PROGRESS', 3: 'CE_NO_EXPOSURE_IN_PROGRESS', 4: 'CE_UNKNOWN_COMMAND', 5: 'CE_BAD_CAMERA_COMMAND', 6: 'CE_BAD_PARAMETER', 7: 'CE_TX_TIMEOUT', 8: 'CE_RX_TIMEOUT', 9: 'CE_NAK_RECEIVED', 10: 'CE_CAN_RECEIVED', 11: 'CE_UNKNOWN_RESPONSE', 12: 'CE_BAD_LENGTH', 13: 'CE_AD_TIMEOUT', 14: 'CE_KBD_ESC', 15: 'CE_CHECKSUM_ERROR', 16: 'CE_EEPROM_ERROR', 17: 'CE_SHUTTER_ERROR', 18: 'CE_UNKNOWN_CAMERA', 19: 'CE_DRIVER_NOT_FOUND', 20: 'CE_DRIVER_NOT_OPEN', 21: 'CE_DRIVER_NOT_CLOSED', 22: 'CE_SHARE_ERROR', 23: 'CE_TCE_NOT_FOUND', 24: 'CE_AO_ERROR', 25: 'CE_ECP_ERROR', 26: 'CE_MEMORY_ERROR', 27: 'CE_DEVICE_NOT_FOUND', 28: 'CE_DEVICE_NOT_OPEN', 29: 'CE_DEVICE_NOT_CLOSED', 30: 'CE_DEVICE_NOT_IMPLEMENTED', 31: 'CE_DEVICE_DISABLED', 32: 'CE_OS_ERROR', 33: 'CE_SOCK_ERROR', 34: 'CE_SERVER_NOT_FOUND', 35: 'CE_CFW_ERROR', 36: 'CE_MF_ERROR', 37: 'CE_FIRMWARE_ERROR', 38: 'CE_DIFF_GUIDER_ERROR', 39: 'CE_RIPPLE_CORRECTION_ERROR', 40: 'CE_EZUSB_RESET', 41: 'CE_NEXT_ERROR'} # Reverse dictionary, just in case you ever need to look up an error code given # an error name error_codes = {error: error_code for error_code, error in errors.items()} ################################################################################# # Query USB Info related. ################################################################################# class QueryUSBInfo(ctypes.Structure): """ ctypes (Sub-)Structure used to hold details of individual cameras returned by 'CC_QUERY_USB' command """ # Rather than use C99 _Bool type SBIG library uses 0 = False, 1 = True _fields_ = [('cameraFound', ctypes.c_ushort), ('cameraType', ctypes.c_ushort), ('name', ctypes.c_char * 64), ('serialNumber', ctypes.c_char * 10)] class QueryUSBResults(ctypes.Structure): """ ctypes Structure used to hold the results from 'CC_QUERY_USB' command """ _fields_ = [('camerasFound', ctypes.c_ushort), ('usbInfo', QueryUSBInfo * 4)] class QueryUSBResults2(ctypes.Structure): """ ctypes Structure used to hold the results from 'CC_QUERY_USB2' command """ _fields_ = [('camerasFound', ctypes.c_ushort), ('usbInfo', QueryUSBInfo * 8)] # Camera type codes, returned by Query USB Info, Establish Link, Get CCD Info, etc. camera_types = {4: "ST7_CAMERA", 5: "ST8_CAMERA", 6: "ST5C_CAMERA", 7: "TCE_CONTROLLER", 8: "ST237_CAMERA", 9: "STK_CAMERA", 10: "ST9_CAMERA", 11: "STV_CAMERA", 12: "ST10_CAMERA", 13: "ST1K_CAMERA", 14: "ST2K_CAMERA", 15: "STL_CAMERA", 16: "ST402_CAMERA", 17: "STX_CAMERA", 18: "ST4K_CAMERA", 19: "STT_CAMERA", 20: "STI_CAMERA", 21: "STF_CAMERA", 22: "NEXT_CAMERA", 0xFFFF: "NO_CAMERA"} # Reverse dictionary camera_type_codes = {camera: code for code, camera in camera_types.items()} ################################################################################# # Open Device, Establish Link, Get Link status related ################################################################################# # Device types by code. Used with Open Device, etc. device_types = {0: "DEV_NONE", 1: "DEV_LPT1", 2: "DEV_LPT2", 3: "DEV_LPT3", 0x7F00: "DEV_USB", 0x7F01: "DEV_ETH", 0x7F02: "DEV_USB1", 0x7F03: "DEV_USB2", 0x7F04: "DEV_USB3", 0x7F05: "DEV_USB4", 0x7F06: "DEV_USB5", 0x7F07: "DEV_USB6", 0x7F08: "DEV_USB7", 0x7F09: "DEV_USB8"} # Reverse dictionary device_type_codes = {device: code for code, device in device_types.items()} class OpenDeviceParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Open Device command. """ _fields_ = [('deviceType', ctypes.c_ushort), ('lptBaseAddress', ctypes.c_ushort), ('ipAddress', ctypes.c_ulong)] class EstablishLinkParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Establish Link command. """ _fields_ = [('sbigUseOnly', ctypes.c_ushort)] class EstablishLinkResults(ctypes.Structure): """ ctypes Structure to hold the results from the Establish Link command. """ _fields_ = [('cameraType', ctypes.c_ushort)] class GetLinkStatusResults(ctypes.Structure): """ ctypes Structure to hold the results from the Get Link Status command. """ _fields_ = [('linkEstablished', ctypes.c_ushort), ('baseAddress', ctypes.c_ushort), ('cameraType', ctypes.c_ushort), ('comTotal', ctypes.c_ulong), ('comFailed', ctypes.c_ulong)] ################################################################################# # Get Driver Handle, Set Driver Handle related ################################################################################# class GetDriverHandleResults(ctypes.Structure): """ ctypes Structure to hold the results from the Get Driver Handle command. The handle is the camera ID used when switching control between connected cameras with the Set Driver Handle command. """ _fields_ = [('handle', ctypes.c_short)] # Used to disconnect from a camera in order to get the handle for another # Had to google to find this value, it is NOT in sbigudrv.h or the # SBIG Universal Driver docs. INVALID_HANDLE_VALUE = -1 class SetDriverHandleParams(ctypes.Structure): """ ctypes Structure to hold the parameter for the Set Driver Handle command. """ _fields_ = [('handle', ctypes.c_short)] ################################################################################# # Temperature and cooling control related ################################################################################# class QueryTemperatureStatusParams(ctypes.Structure): """ ctypes Structure used to hold the parameters for the Query Temperature Status command. """ _fields_ = [('request', ctypes.c_ushort)] temp_status_requests = {0: 'TEMP_STATUS_STANDARD', 1: 'TEMP_STATUS_ADVANCED', 2: 'TEMP_STATUS_ADVANCED2'} temp_status_request_codes = {request: code for code, request in temp_status_requests.items()} class QueryTemperatureStatusResults(ctypes.Structure): """ ctypes Structure used to hold the results from the Query Temperature Status command (standard version). """ _fields_ = [('enabled', ctypes.c_ushort), ('ccdSetpoint', ctypes.c_ushort), ('power', ctypes.c_ushort), ('ccdThermistor', ctypes.c_ushort), ('ambientThermistor', ctypes.c_ushort)] class QueryTemperatureStatusResults2(ctypes.Structure): """ ctypes Structure used to hold the results from the Query Temperature Status command (extended version). """ _fields_ = [('coolingEnabled', ctypes.c_ushort), ('fanEnabled', ctypes.c_ushort), ('ccdSetpoint', ctypes.c_double), ('imagingCCDTemperature', ctypes.c_double), ('trackingCCDTemperature', ctypes.c_double), ('externalTrackingCCDTemperature', ctypes.c_double), ('ambientTemperature', ctypes.c_double), ('imagingCCDPower', ctypes.c_double), ('trackingCCDPower', ctypes.c_double), ('externalTrackingCCDPower', ctypes.c_double), ('heatsinkTemperature', ctypes.c_double), ('fanPower', ctypes.c_double), ('fanSpeed', ctypes.c_double), ('trackingCCDSetpoint', ctypes.c_double)] temperature_regulations = {0: "REGULATION_OFF", 1: "REGULATION_ON", 2: "REGULATION_OVERRIDE", 3: "REGULATION_FREEZE", 4: "REGULATION_UNFREEZE", 5: "REGULATION_ENABLE_AUTOFREEZE", 6: "REGULATION_DISABLE_AUTOFREEZE"} temperature_regulation_codes = {regulation: code for code, regulation in temperature_regulations.items()} class SetTemperatureRegulationParams(ctypes.Structure): """ ctypes Structure used to hold the parameters for the Set Temperature Regulation command. """ _fields_ = [('regulation', ctypes.c_ushort), ('ccdSetpoint', ctypes.c_ushort)] class SetTemperatureRegulationParams2(ctypes.Structure): """ ctypes Structure used to hold the parameters for the Set Temperature Regulation 2 command. """ _fields_ = [('regulation', ctypes.c_ushort), ('ccdSetpoint', ctypes.c_double)] ################################################################################ # Get CCD Info related ################################################################################ class GetCCDInfoParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Get CCD Info command, used obtain the details & capabilities of the connected camera. """ _fields_ = [('request', ctypes.c_ushort)] ccd_info_requests = {0: 'CCD_INFO_IMAGING', 1: 'CCD_INFO_TRACKING', 2: 'CCD_INFO_EXTENDED', 3: 'CCD_INFO_EXTENDED_5C', 4: 'CCD_INFO_EXTENDED2_IMAGING', 5: 'CCD_INFO_EXTENDED2_TRACKING', 6: 'CCD_INFO_EXTENDED3'} ccd_info_request_codes = {request: code for code, request in ccd_info_requests.items()} class ReadoutInfo(ctypes.Structure): """ ctypes Structure to store details of an individual readout mode. An array of up to 20 of these will be returned as part of the GetCCDInfoResults0 struct when the Get CCD Info command is used with request 'CCD_INFO_IMAGING'. The gain field is a 4 digit Binary Coded Decimal (yes, really) of the form XX.XX, in units of electrons/ADU. The pixel_width and pixel_height fields are 6 digit Binary Coded Decimals for the form XXXXXX.XX in units of microns, helpfully supporting pixels up to 1 metre across. """ _fields_ = [('mode', ctypes.c_ushort), ('width', ctypes.c_ushort), ('height', ctypes.c_ushort), ('gain', ctypes.c_ushort), ('pixelWidth', ctypes.c_ulong), ('pixelHeight', ctypes.c_ulong)] class GetCCDInfoResults0(ctypes.Structure): """ ctypes Structure to hold the results from the Get CCD Info command when used with requests 'CCD_INFO_IMAGING' or 'CCD_INFO_TRACKING'. The firmwareVersion field is 4 digit binary coded decimal of the form XX.XX. """ _fields_ = [('firmwareVersion', ctypes.c_ushort), ('cameraType', ctypes.c_ushort), ('name', ctypes.c_char * 64), ('readoutModes', ctypes.c_ushort), ('readoutInfo', ReadoutInfo * 20)] class GetCCDInfoResults2(ctypes.Structure): """ ctypes Structure to hold the results from the Get CCD Info command when used with request 'CCD_INFO_EXTENDED'. """ _fields_ = [('badColumns', ctypes.c_ushort), ('columns', ctypes.c_ushort * 4), ('imagingABG', ctypes.c_ushort), ('serialNumber', ctypes.c_char * 10)] class GetCCDInfoResults4(ctypes.Structure): """ ctypes Structure to hold the results from the Get CCD Info command when used with requests 'CCD_INFO_EXTENDED2_IMAGING' or 'CCD_INFO_EXTENDED2_TRACKING'. The capabilitiesBits is a bitmask, yay. """ _fields_ = [('capabilities_b0', ctypes.c_int, 1), ('capabilities_b1', ctypes.c_int, 1), ('capabilities_b2', ctypes.c_int, 1), ('capabilities_b3', ctypes.c_int, 1), ('capabilities_b4', ctypes.c_int, 1), ('capabilities_b5', ctypes.c_int, 1), ('capabilities_unusued', ctypes.c_int, ctypes.sizeof(ctypes.c_ushort) * 8 - 6), ('dumpExtra', ctypes.c_ushort)] class GetCCDInfoResults6(ctypes.Structure): """ ctypes Structure to hold the results from the Get CCD Info command when used with the request 'CCD_INFO_EXTENDED3'. The sbigudrv.h C header says there should be three bitmask fields, each of type ulong, which would be 64 bits on this platform (OS X), BUT trial and error has determined they're actually 32 bits long. """ _fields_ = [('camera_b0', ctypes.c_int, 1), ('camera_b1', ctypes.c_int, 1), ('camera_unused', ctypes.c_int, 30), ('ccd_b0', ctypes.c_int, 1), ('ccd_b1', ctypes.c_int, 1), ('ccd_unused', ctypes.c_int, 30), ('extraBits', ctypes.c_int, 32)] ################################################################################# # Get Driver Control, Set Driver Control related ################################################################################# driver_control_params = {i: param for i, param in enumerate(('DCP_USB_FIFO_ENABLE', 'DCP_CALL_JOURNAL_ENABLE', 'DCP_IVTOH_RATIO', 'DCP_USB_FIFO_SIZE', 'DCP_USB_DRIVER', 'DCP_KAI_RELGAIN', 'DCP_USB_PIXEL_DL_ENABLE', 'DCP_HIGH_THROUGHPUT', 'DCP_VDD_OPTIMIZED', 'DCP_AUTO_AD_GAIN', 'DCP_NO_HCLKS_FOR_INTEGRATION', 'DCP_TDI_MODE_ENABLE', 'DCP_VERT_FLUSH_CONTROL_ENABLE', 'DCP_ETHERNET_PIPELINE_ENABLE', 'DCP_FAST_LINK', 'DCP_OVERSCAN_ROWSCOLS', 'DCP_PIXEL_PIPELINE_ENABLE', 'DCP_COLUMN_REPAIR_ENABLE', 'DCP_WARM_PIXEL_REPAIR_ENABLE', 'DCP_WARM_PIXEL_REPAIR_COUNT', 'DCP_LAST'))} driver_control_codes = {param: code for code, param in driver_control_params.items()} class GetDriverControlParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Get Driver Control command, used to query the value of a specific driver control parameter. """ _fields_ = [('controlParameter', ctypes.c_ushort), ] class GetDriverControlResults(ctypes.Structure): """ ctypes Structure to hold the result from the Get Driver Control command, used to query the value of a specific driver control parameter """ _fields_ = [('controlValue', ctypes.c_ulong), ] class SetDriverControlParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Set Driver Control command, used to set the value of a specific driver control parameter """ _fields_ = [('controlParameter', ctypes.c_ushort), ('controlValue', ctypes.c_ulong)] ################################################################################# # Start Exposure, Query Command Status, End Exposure related ################################################################################# class StartExposureParams2(ctypes.Structure): """ ctypes Structure to hold the parameters for the Start Exposure 2 command. (The Start Exposure command is deprecated.) """ _fields_ = [('ccd', ctypes.c_ushort), ('exposureTime', ctypes.c_ulong), ('abgState', ctypes.c_ushort), ('openShutter', ctypes.c_ushort), ('readoutMode', ctypes.c_ushort), ('top', ctypes.c_ushort), ('left', ctypes.c_ushort), ('height', ctypes.c_ushort), ('width', ctypes.c_ushort)] # CCD selection for cameras with built in or connected tracking CCDs ccds = {0: 'CCD_IMAGING', 1: 'CCD_TRACKING', 2: 'CCD_EXT_TRACKING'} ccd_codes = {ccd: code for code, ccd in ccds.items()} # Anti-Blooming Gate states abg_states = {0: 'ABG_LOW7', 1: 'ABG_CLK_LOW7', 2: 'ABG_CLK_MED7', 3: 'ABG_CLK_HI7'} abg_state_codes = {abg: code for code, abg in abg_states.items()} # Shutter mode commands shutter_commands = {0: 'SC_LEAVE_SHUTTER', 1: 'SC_OPEN_SHUTTER', 2: 'SC_CLOSE_SHUTTER', 3: 'SC_INITIALIZE_SHUTTER', 4: 'SC_OPEN_EXP_SHUTTER', 5: 'SC_CLOSE_EXT_SHUTTER'} shutter_command_codes = {command: code for code, command in shutter_commands.items()} # Readout binning modes readout_modes = {0: 'RM_1X1', 1: 'RM_2X2', 2: 'RM_3X3', 3: 'RM_NX1', 4: 'RM_NX2', 5: 'RM_NX3', 6: 'RM_1X1_VOFFCHIP', 7: 'RM_2X2_VOFFCHIP', 8: 'RM_3X3_VOFFCHIP', 9: 'RM_9X9', 10: 'RM_NXN'} readout_mode_codes = {mode: code for code, mode in readout_modes.items()} # Command status codes and corresponding messages as returned by # Query Command Status statuses = {0: "CS_IDLE", 1: "CS_IN_PROGRESS", 2: "CS_INTEGRATING", 3: "CS_INTEGRATION_COMPLETE"} # Reverse dictionary status_codes = {status: code for code, status in statuses.items()} class QueryCommandStatusParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Query Command Status command. """ _fields_ = [('command', ctypes.c_ushort)] class QueryCommandStatusResults(ctypes.Structure): """ ctypes Structure to hold the results from the Query Command Status command. """ _fields_ = [('status', ctypes.c_ushort)] class EndExposureParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the End Exposure command. """ _fields_ = [('ccd', ctypes.c_ushort)] ################################################################################# # Start Readout, Readout Line, End Readout related ################################################################################# class StartReadoutParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Start Readout command. """ _fields_ = [('ccd', ctypes.c_ushort), ('readoutMode', ctypes.c_ushort), ('top', ctypes.c_ushort), ('left', ctypes.c_ushort), ('height', ctypes.c_ushort), ('width', ctypes.c_ushort)] class ReadoutLineParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the Readout Line command. """ _fields_ = [('ccd', ctypes.c_ushort), ('readoutMode', ctypes.c_ushort), ('pixelStart', ctypes.c_ushort), ('pixelLength', ctypes.c_ushort)] class EndReadoutParams(ctypes.Structure): """ ctypes Structure to hold the parameters for the End Readout Params. """ _fields_ = [('ccd', ctypes.c_ushort)] ################################################################################# # Get Driver Info related ################################################################################# # Requests relevant to Get Driver Info command driver_requests = {0: "DRIVER_STD", 1: "DRIVER_EXTENDED", 2: "DRIVER_USB_LOADER"} # Reverse dictionary driver_request_codes = {request: code for code, request in driver_requests.items()} class GetDriverInfoParams(ctypes.Structure): """ ctypes Structure used to hold the parameters for the Get Driver Info command """ _fields_ = [('request', ctypes.c_ushort)] class GetDriverInfoResults0(ctypes.Structure): """ ctypes Structure used to hold the results from the Get Driver Info command """ _fields_ = [('version', ctypes.c_ushort), ('name', ctypes.c_char * 64), ('maxRequest', ctypes.c_ushort)]
mit
EcoGame/Eco
src/eco/game/Game.java
2812
package eco.game; import eco.render.FPSCounter; import eco.render.Render; import eco.ui.*; import org.lwjgl.opengl.Display; /** * A class that contains various methods to run the game * * @author phil */ public final class Game { public static void gameLoop(PlayerCountry playerCountry) { init(playerCountry); while (!Main.shouldQuit) { Command.update(); if (Display.isCloseRequested()) { if (!Main.gameOver) { SaveUtil.createSave(playerCountry); } Util.quit(0); } if (Main.gameOver) { gameOverLoop(); } else if (!Main.paused) { gameUpdate(playerCountry); FPSCounter.tick(); Display.update(); Display.sync(60); } else { pausedLoop(); } } cleanup(playerCountry); Menu.mainMenu(); } private static void init(PlayerCountry playerCountry){ PlayerCountry.playerCountry = playerCountry; Country.init(); Main.shouldBeInMenu = false; } private static void cleanup(PlayerCountry playerCountry){ if (!Main.gameOver) { SaveUtil.createSave(playerCountry); } PlayerCountry.playerCountry = null; } private static void gameUpdate(PlayerCountry playerCountry){ Main.frame++; if (Main.frame >= Main.framesPerTick && !Main.paused && PlayerCountry.year < PlayerCountry.ticks) { PlayerCountry.year++; Country.globalTick(); if (playerCountry.farmer.getPop() <= 0 && playerCountry.warrior.getPop() <= 0) { Main.gameOver = true; } Main.frame = 0; } UIManager.update(); InputManager.gameInput.update(); Typer.type("", InputManager.gameInput); if (!Main.skipFrame) { Render.draw(); } else { Main.skipFrame = false; } } private static void pausedLoop(){ Render.drawPaused(); InputManager.pausedInput.update(); Typer.type("", InputManager.pausedInput); UIManager.renderPause(); UIManager.renderPause2(); UIManager.updatePaused(); FPSCounter.tick(); Display.update(); Display.sync(60); } private static void gameOverLoop(){ Render.drawGameOver(); FPSCounter.tick(); InputManager.gameOverInput.update(); Typer.type("", InputManager.gameOverInput); UIManager.updateGameOver(); UIManager.renderGameOver(); UIManager.renderGameOver2(); Display.update(); Display.sync(60); } }
mit
salsabielac/pokoman
application/views/uas/volly.php
1403
<!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('http://localhost:8080/codein/uas/img/volly.jpg')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="page-heading"> <h1>Volly</h1> </div> </div> </div> </div> </header> <!-- Post Content --> <article> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <P class="text-justify"> Bola voli adalah olahraga permainan yang dimainkan oleh dua grup berlawanan. Masing-masing grup memiliki enam orang pemain. Terdapat pula variasi permainan bola voli pantai yang masing-masing grup hanya memiliki dua orang pemain. Olahraga Bola Voli dinaungi FIVB (Federation Internationale de Volleyball) sebagai induk organisasi internasional, sedangkan di Indonesia dinaungi oleh PBVSI (Persatuan Bola Voli Seluruh Indonesia). </P> <blockquote>I've worked too hard and too long to let anything stand in the way of my goals. I will not let my teammates down and I will not let my self down.<br>-- Mia Hamm --</blockquote>
mit
spacexnice/ctlplane
Godeps/_workspace/src/github.com/google/cadvisor/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/setns_init_linux.go
1272
// +build linux package libcontainer import ( "os" "github.com/opencontainers/runc/libcontainer/apparmor" "github.com/opencontainers/runc/libcontainer/label" "github.com/opencontainers/runc/libcontainer/seccomp" "github.com/opencontainers/runc/libcontainer/system" ) // linuxSetnsInit performs the container's initialization for running a new process // inside an existing container. type linuxSetnsInit struct { config *initConfig } func (l *linuxSetnsInit) Init() error { if err := setupRlimits(l.config.Config); err != nil { return err } if err := setOomScoreAdj(l.config.Config.OomScoreAdj); err != nil { return err } if l.config.Config.Seccomp != nil { if err := seccomp.InitSeccomp(l.config.Config.Seccomp); err != nil { return err } } if err := finalizeNamespace(l.config); err != nil { return err } if err := apparmor.ApplyProfile(l.config.Config.AppArmorProfile); err != nil { return err } if l.config.Config.ProcessLabel != "" { if err := label.SetProcessLabel(l.config.Config.ProcessLabel); err != nil { return err } } return system.Execv(l.config.Args[0], l.config.Args[0:], os.Environ()) }
mit
githubmoros/myclinicsoft
arrowchat/includes/functions/integrations/functions_ipboard.php
8725
<?php /* || #################################################################### || || # ArrowChat # || || # ---------------------------------------------------------------- # || || # Copyright ©2010-2012 ArrowSuites LLC. All Rights Reserved. # || || # This file may not be redistributed in whole or significant part. # || || # ---------------- ARROWCHAT IS NOT FREE SOFTWARE ---------------- # || || # NULLED BY DARKGOTH | NCP TEAM 2015 # || || #################################################################### || */ /** * This function returns the user ID of the logged in user on your site. Technical support will not * help you with this for stand-alone installations. You must purchase the professional installation * if you are having trouble. * * Suggestion: Check out the other integration files in the functions/integrations directory for * many examples of how this can be done. The easiest way is to get the user ID through a cookie. * * @return the user ID of the logged in user or NULL if not logged in */ function get_user_id() { global $db; $userid = NULL; foreach ($_COOKIE as $key => $val) { if (preg_match("/member_id/", $key)) { $cookie_name = $key; } if (preg_match("/pass_hash/", $key)) { $cookie_pass = $key; } } if (isset($_COOKIE[$cookie_name]) AND !empty($_COOKIE[$cookie_name])) { $result = $db->execute(" SELECT " . DB_USERTABLE_USERID . " userid FROM " . TABLE_PREFIX . DB_USERTABLE . " WHERE member_id = '" . $db->escape_string($_COOKIE[$cookie_name]) . "' AND member_login_key = '" . $db->escape_string($_COOKIE[$cookie_pass]) . "' "); if ($row = $db->fetch_array($result)) { if (!empty($row['userid'])) $userid = $row['userid']; } } return $userid; } /** * This function returns the SQL statement for the buddylist of the user. You should retrieve * all ONLINE friends that the user is friends with. Do not retrieve offline users. You can use * global $online_timeout to get the online timeout. * ex: AND (arrowchat_status.session_time + 60 + " . $online_timeout . ") > " . time() . " * * @param userid the user ID of the person receiving the buddylist * @param the time of the buddylist request * @return the SQL statement to retrieve the user's friend list */ function get_friend_list($userid, $time) { global $db; global $online_timeout; $sql = (" SELECT DISTINCT " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " userid, " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_NAME . " username, arrowchat_status.session_time lastactivity, " . TABLE_PREFIX . "profile_portal." . DB_USERTABLE_AVATAR . " avatar, CONCAT(" . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . ",'-'," . TABLE_PREFIX . DB_USERTABLE . ".members_seo_name) link, arrowchat_status.is_admin, arrowchat_status.status FROM " . TABLE_PREFIX . DB_FRIENDSTABLE . " JOIN " . TABLE_PREFIX . DB_USERTABLE . " ON " . TABLE_PREFIX . DB_FRIENDSTABLE . "." . DB_FRIENDSTABLE_FRIENDID . " = " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " LEFT JOIN arrowchat_status ON " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " = arrowchat_status.userid LEFT JOIN " . TABLE_PREFIX . "profile_portal ON " . TABLE_PREFIX . "profile_portal.pp_member_id = " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " WHERE " . TABLE_PREFIX . DB_FRIENDSTABLE . "." . DB_FRIENDSTABLE_USERID . " = '" . $db->escape_string($userid) . "' AND " . TABLE_PREFIX . DB_FRIENDSTABLE . "." . DB_FRIENDSTABLE_FRIENDS . " = '1' AND (arrowchat_status.session_time + 60 + " . $online_timeout . ") > " . time() . " ORDER BY " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_NAME . " ASC "); return $sql; } /** * This function returns the SQL statement for all online users. You should retrieve * all ONLINE users regardless of friend status. Do not retrieve offline users. You can use * global $online_timeout to get the online timeout. * ex: AND (arrowchat_status.session_time + 60 + " . $online_timeout . ") > " . time() . " * * @param userid the user ID of the person receiving the buddylist * @param the time of the buddylist request * @return the SQL statement to retrieve all online users */ function get_online_list($userid, $time) { global $db; global $online_timeout; $sql = (" SELECT DISTINCT " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " userid, " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_NAME . " username, arrowchat_status.session_time lastactivity, " . TABLE_PREFIX . "profile_portal." . DB_USERTABLE_AVATAR . " avatar, CONCAT(" . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . ",'-'," . TABLE_PREFIX . DB_USERTABLE . ".members_seo_name) link, arrowchat_status.is_admin, arrowchat_status.status FROM " . TABLE_PREFIX . DB_USERTABLE . " JOIN arrowchat_status ON " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " = arrowchat_status.userid LEFT JOIN " . TABLE_PREFIX . "profile_portal ON " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " = " . TABLE_PREFIX . "profile_portal.pp_member_id WHERE ('" . time() . "'-arrowchat_status.session_time - 60 < '" . $online_timeout . "') AND " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " != '" . $db->escape_string($userid) . "' ORDER BY " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_NAME . " ASC "); return $sql; } /** * This function returns the SQL statement to get the user details of a specific user. You should * get the user's ID, username, last activity time in unix, link to their profile, avatar, and status. * * @param userid the user ID to get the details of * @return the SQL statement to retrieve the user's defaults */ function get_user_details($userid) { global $db; $sql = (" SELECT " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " userid, " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_NAME . " username, arrowchat_status.session_time lastactivity, CONCAT(" . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . ",'-'," . TABLE_PREFIX . DB_USERTABLE . ".members_seo_name) link, " . TABLE_PREFIX . "profile_portal." . DB_USERTABLE_AVATAR . " avatar, arrowchat_status.is_admin, arrowchat_status.status FROM " . TABLE_PREFIX . DB_USERTABLE . " LEFT JOIN arrowchat_status ON " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " = arrowchat_status.userid LEFT JOIN " . TABLE_PREFIX . "profile_portal ON " . TABLE_PREFIX . "profile_portal.pp_member_id = " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " WHERE " . TABLE_PREFIX . DB_USERTABLE . "." . DB_USERTABLE_USERID . " = '" . $db->escape_string($userid) . "' "); return $sql; } /** * This function returns the profile link of the specified user ID. * * @param userid the user ID to get the profile link of * @return the link of the user ID's profile */ function get_link($link, $user_id) { global $base_url; return $base_url . '../index.php?/user/' . $link; } /** * This function returns the URL of the avatar of the specified user ID. * * @param userid the user ID of the user * @param image if the image includes more than just a user ID, this param is passed * in from the avatar row in the buddylist and get user details functions. * @return the link of the user ID's profile */ function get_avatar($image, $user_id) { global $base_url; if (!empty($image)) { return $base_url . '../uploads/' . $image; } else { return $base_url . '../public/style_images/master/profile/default_thumb.png'; } } /** * This function returns the name of the logged in user. You should not need to * change this function. * * @param userid the user ID of the user * @return the name of the user */ function get_username($userid) { global $db; global $language; global $show_full_username; $users_name = $language[83]; $result = $db->execute(" SELECT " . DB_USERTABLE_NAME . " name FROM " . TABLE_PREFIX . DB_USERTABLE . " WHERE " . DB_USERTABLE_USERID . " = '" . $db->escape_string($userid) . "' "); if ($result AND $db->count_select() > 0) { $row = $db->fetch_array($result); $users_name = $row['name']; } $pieces = explode(" ", $users_name); if ($show_full_username == 1) { return $users_name; } else { return $pieces[0]; } } ?>
mit
micromasterandroid/androidadvanced
Lesson 2/TwitterClientApp/app/src/main/java/edu/galileo/android/twitterclient/main/ui/adapters/MainSectionsPagerAdapter.java
857
package edu.galileo.android.twitterclient.main.ui.adapters; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; /** * Created by ykro. */ public class MainSectionsPagerAdapter extends FragmentPagerAdapter { private String[] titles; private Fragment[] fragments; public MainSectionsPagerAdapter(FragmentManager fm, String[] titles, Fragment[] fragments) { super(fm); this.titles = titles; this.fragments = fragments; } @Override public Fragment getItem(int position) { return this.fragments[position]; } @Override public CharSequence getPageTitle(int position) { return this.titles[position]; } @Override public int getCount() { return this.fragments.length; } }
mit
zeroleaf/com.zeroleaf
ProgressBar/src/main/java/com/zeroleaf/tools/progressbar/renderings/TotalRendering.java
513
package com.zeroleaf.tools.progressbar.renderings; import com.zeroleaf.tools.progressbar.Config; import com.zeroleaf.tools.progressbar.Progress; /** * * * @author zeroleaf */ public class TotalRendering implements Rendering { public static final String TOTAL_TOKEN = ":total"; @Override public String getToken() { return TOTAL_TOKEN; } @Override public String render(Config config, Progress progress) { return String.format("%d", progress.getTotalStep()); } }
mit
DFEAGILEDEVOPS/gender-pay-gap
Beta/GenderPayGap.WebJob/Functions/Functions.StorageSnapshots.cs
11496
using System; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using GenderPayGap.Extensions; using GenderPayGap.Core; using System.Collections.Generic; using static GenderPayGap.Extensions.Web; using System.Security.Cryptography; using Microsoft.Azure.WebJobs; using GenderPayGap.Extensions.AspNetCore; using System.IO.Compression; using Microsoft.Extensions.Logging; namespace GenderPayGap.WebJob { public partial class Functions { public async Task TakeSnapshotAsync([TimerTrigger(typeof(MidnightSchedule))]TimerInfo timer, ILogger log) { try { var azureStorageConnectionString = Config.GetConnectionString("AzureStorage"); if (azureStorageConnectionString.Equals("UseDevelopmentStorage=true")) return; var connectionString = azureStorageConnectionString.ConnectionStringToDictionary(); var azureStorageAccount = connectionString["AccountName"]; var azureStorageKey = connectionString["AccountKey"]; var azureStorageShareName = Config.GetAppSetting("AzureStorageShareName"); //Take the snapshot await TakeSnapshotAsync(azureStorageAccount, azureStorageKey, azureStorageShareName); //Get the list of snapshots var response = await ListSnapshotsAsync(azureStorageAccount, azureStorageKey, azureStorageShareName); int count = 0; if (!string.IsNullOrWhiteSpace(response)) { var xml = XElement.Parse(response); var snapshots = xml.Descendants().Where(e => e.Name.LocalName.EqualsI("Snapshot")).Select(e => e.Value).ToList(); //var snapshots = snapshots.Where(e => e.EqualsI("Snapshot")).Select(e=>e.Value).ToList(); var deadline = VirtualDateTime.Now.AddDays(0 - Config.GetAppSetting("MaxSnapshotDays").ToInt32(35)); foreach (var snapshot in snapshots) { var date = DateTime.Parse(snapshot); if (date > deadline) continue; await DeleteSnapshotAsync(log, azureStorageAccount, azureStorageKey, azureStorageShareName, snapshot); count++; } } log.LogDebug($"Executed {nameof(TakeSnapshotAsync)} successfully and deleted {count} stale snapshots"); } catch (Exception ex) { var message = $"Failed webjob:{nameof(TakeSnapshotAsync)}:{ex.Message}"; //Send Email to GEO reporting errors await _Messenger.SendGeoMessageAsync("GPG - WEBJOBS ERROR", message); //Rethrow the error throw; } } public async Task TakeSnapshotAsync(ILogger log) { try { var azureStorageConnectionString = Config.GetConnectionString("AzureStorage"); if (azureStorageConnectionString.Equals("UseDevelopmentStorage=true")) return; var connectionString = azureStorageConnectionString.ConnectionStringToDictionary(); var azureStorageAccount = connectionString["AccountName"]; var azureStorageKey = connectionString["AccountKey"]; var azureStorageShareName = Config.GetAppSetting("AzureStorageShareName"); //Take the snapshot await TakeSnapshotAsync(azureStorageAccount, azureStorageKey, azureStorageShareName); log.LogDebug($"Executed {nameof(TakeSnapshotAsync)} successfully"); } catch (Exception ex) { log.LogError(ex, $"Failed webjob:{nameof(TakeSnapshotAsync)}:{ex.Message}"); throw; } } private static async Task<string> TakeSnapshotAsync(string storageAccount, string storageKey, string shareName) { string version = "2017-04-17"; var comp = "snapshot"; var restype = "share"; DateTime dt = VirtualDateTime.UtcNow; string StringToSign = "PUT\n" + "\n" // content encoding + "\n" // content language + "\n" // content length + "\n" // content md5 + "\n" // content type + "\n" // date + "\n" // if modified since + "\n" // if match + "\n" // if none match + "\n" // if unmodified since + "\n" // range + "x-ms-date:" + dt.ToString("R") + "\nx-ms-version:" + version + "\n" // headers + $"/{storageAccount}/{shareName}\ncomp:{comp}\nrestype:{restype}"; var signature = SignAuthHeader(StringToSign, storageKey, storageAccount); var authorizationHeader = $"SharedKey {storageAccount}:{signature}"; var url = $"https://{storageAccount}.file.core.windows.net/{shareName}?restype={restype}&comp={comp}"; var headers = new Dictionary<string, string>(); headers.Add("x-ms-date", dt.ToString("R")); headers.Add("x-ms-version", version); headers.Add("Authorization", authorizationHeader); var json = await CallApiAsync(GenderPayGap.Extensions.Web.HttpMethods.Put, url, headers: headers); return headers["x-ms-snapshot"]; } private static async Task<string> ListSnapshotsAsync(string storageAccount, string storageKey, string shareName) { string version = "2017-04-17"; var comp = "list"; DateTime dt = VirtualDateTime.UtcNow; string StringToSign = "GET\n" + "\n" // content encoding + "\n" // content language + "\n" // content length + "\n" // content md5 + "\n" // content type + "\n" // date + "\n" // if modified since + "\n" // if match + "\n" // if none match + "\n" // if unmodified since + "\n" // range + "x-ms-date:" + dt.ToString("R") + "\nx-ms-version:" + version + "\n" // headers + $"/{storageAccount}/\ncomp:{comp}\ninclude:snapshots\nprefix:{shareName}"; var signature = SignAuthHeader(StringToSign, storageKey, storageAccount); var authorizationHeader = $"SharedKey {storageAccount}:{signature}"; var url = $"https://{storageAccount}.file.core.windows.net/?comp={comp}&prefix={shareName}&include=snapshots"; var headers = new Dictionary<string, string>(); headers.Add("x-ms-date", dt.ToString("R")); headers.Add("x-ms-version", version); headers.Add("Authorization", authorizationHeader); var response = await Web.CallApiAsync(GenderPayGap.Extensions.Web.HttpMethods.Get, url, headers: headers); return response; } private static async Task<string> DeleteSnapshotAsync(ILogger log, string storageAccount, string storageKey, string shareName, string snapshot) { string version = "2017-04-17"; var restype = "share"; DateTime dt = VirtualDateTime.UtcNow; string StringToSign = "DELETE\n" + "\n" // content encoding + "\n" // content language + "\n" // content length + "\n" // content md5 + "\n" // content type + "\n" // date + "\n" // if modified since + "\n" // if match + "\n" // if none match + "\n" // if unmodified since + "\n" // range + "x-ms-date:" + dt.ToString("R") + "\nx-ms-version:" + version + "\n" // headers + $"/{storageAccount}/{shareName}\nrestype:{restype}\nsharesnapshot:{snapshot}"; var signature = SignAuthHeader(StringToSign, storageKey, storageAccount); var authorizationHeader = $"SharedKey {storageAccount}:{signature}"; var url = $"https://{storageAccount}.file.core.windows.net/{shareName}?sharesnapshot={snapshot}&restype={restype}"; var headers = new Dictionary<string, string>(); headers.Add("x-ms-date", dt.ToString("R")); headers.Add("x-ms-version", version); headers.Add("Authorization", authorizationHeader); var response = await Web.CallApiAsync(Web.HttpMethods.Delete, url, headers: headers); log.LogDebug($"{nameof(DeleteSnapshotAsync)}: successfully deleted snapshot:{snapshot}"); return headers["x-ms-request-id"]; } private static string SignAuthHeader(string canonicalizedString, string key, string account) { byte[] unicodeKey = Convert.FromBase64String(key); using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey)) { Byte[] dataToHmac = Encoding.UTF8.GetBytes(canonicalizedString); return Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac)); } } public static async Task ArchiveAzureStorageAsync() { const string logZipDir = @"\Archive\"; //Ensure the archive directory exists if (!await Global.FileRepository.GetDirectoryExistsAsync(logZipDir)) await Global.FileRepository.CreateDirectoryAsync(logZipDir); //Create the zip file path using todays date string logZipFilePath = Path.Combine(logZipDir,$"{VirtualDateTime.Now.ToString("yyyyMMdd")}.zip"); //Dont zip if we have one for today if (await Global.FileRepository.GetFileExistsAsync(logZipFilePath)) return; var zipDir = Url.UrlToDirSeparator(Path.Combine(Global.FileRepository.RootDir, logZipDir)); using (MemoryStream fileStream = new MemoryStream()) { int files = 0; using (var zipStream = new ZipArchive(fileStream, ZipArchiveMode.Create, true)) { foreach (var dir in await Global.FileRepository.GetDirectoriesAsync("\\", null, true)) { if (Url.UrlToDirSeparator($"{dir}\\").StartsWithI(zipDir)) continue; foreach (var file in await Global.FileRepository.GetFilesAsync(dir, "*.*", false)) { var dirFile = Url.UrlToDirSeparator(file); // prevents stdout_ logs if (dirFile.ContainsI("stdout_")) continue; var entry = zipStream.CreateEntry(dirFile); using (var entryStream = entry.Open()) { await Global.FileRepository.ReadAsync(dirFile, entryStream); files++; } } } } if (files == 0) return; fileStream.Position = 0; await Global.FileRepository.WriteAsync(logZipFilePath, fileStream); } } } }
mit
baishancloud/lua-acid
lib/test_tableutil.lua
37069
local tableutil = require("acid.tableutil") local time = require('acid.time') local test = _G.test local dd = test.dd function test.nkeys(t) local cases = { {0, { }, 'nkeys of empty'}, {1, {0 }, 'nkeys of 1'}, {2, {0, nil, 1 }, 'nkeys of 0, nil and 1'}, {2, {0, 1 }, 'nkeys of 2'}, {2, {0, 1, nil }, 'nkeys of 0, 1 and nil'}, {1, {a=0, nil }, 'nkeys of a=1'}, {2, {a=0, b=2, nil }, 'nkeys of a=1'}, } for ii, c in ipairs(cases) do local n, tbl = t:unpack(c) local msg = 'case: ' .. tostring(ii) .. '-th ' dd(msg, c) local rst = tableutil.nkeys(tbl) t:eq(n, rst, msg) rst = tableutil.get_len(tbl) t:eq(n, rst, msg) end end function test.keys(t) t:eqdict( {}, tableutil.keys({}) ) t:eqdict( {1}, tableutil.keys({1}) ) t:eqdict( {1, 'a'}, tableutil.keys({1, a=1}) ) t:eqdict( {1, 2, 'a'}, tableutil.keys({1, 3, a=1}) ) end function test.duplist(t) local du = tableutil.duplist local a = { 1 } local b = tableutil.duplist( a ) a[ 2 ] = 2 t:eq( nil, b[ 2 ], "dup not affected" ) t:eqdict( {1}, du( { 1, nil, 2 } ) ) t:eqdict( {1}, du( { 1, a=3 } ) ) t:eqdict( {1}, du( { 1, [3]=3 } ) ) t:eqdict( {}, du( { a=1, [3]=3 } ) ) a = { { 1, 2, 3, a=4 } } a[2] = a[1] b = du(a) t:eqdict({ { 1, 2, 3, a=4 }, { 1, 2, 3, a=4 } }, b) t:eq( b[1], b[2] ) end function test.sub(t) local a = { a=1, b=2, c={} } t:eqdict( {}, tableutil.sub( a, nil ) ) t:eqdict( {}, tableutil.sub( a, {} ) ) t:eqdict( {b=2}, tableutil.sub( a, {"b"} ) ) t:eqdict( {a=1, b=2}, tableutil.sub( a, {"a", "b"} ) ) local b = tableutil.sub( a, {"a", "b", "c"} ) t:neq( b, a ) t:eq( b.c, a.c, "reference" ) -- explicitly specify to sub() as a table b = tableutil.sub( a, {"a", "b", "c"}, 'table' ) t:neq( b, a ) t:eq( b.c, a.c, "reference" ) -- sub list local cases = { {{1, 2, 3}, {}, {}}, {{1, 2, 3}, {2, 3}, {2, 3}}, {{1, 2, 3}, {2, 3, 4}, {2, 3}}, {{1, 2, 3}, {3, 4, 2}, {3, 2}}, } for ii, c in ipairs(cases) do local tbl, ks, expected = t:unpack(c) local msg = 'case: ' .. tostring(ii) .. '-th ' dd(msg, c) local rst = tableutil.sub(tbl, ks, 'list') t:eqdict(expected, rst) end end function test.dup(t) local a = { a=1, 10, x={ y={z=3} } } a.self = a a.selfref = a a.x2 = a.x local b = tableutil.dup( a ) b.a = 'b' t:eq( 1, a.a, 'dup not affected' ) t:eq( 10, a[ 1 ], 'a has 10' ) t:eq( 10, b[ 1 ], 'b inherit 10' ) b[ 1 ] = 11 t:eq( 10, a[ 1 ], 'a has still 10' ) a.x.y.z = 4 t:eq( 4, b.x.y.z, 'no deep' ) local deep = tableutil.dup( a, true ) a.x.y.z = 5 t:eq( 4, deep.x.y.z, 'deep dup' ) t:eq( deep, deep.self, 'loop reference' ) t:eq( deep, deep.selfref, 'loop reference should be dup only once' ) t:eq( deep.x, deep.x2, 'dup only once' ) t:neq( a.x, deep.x, 'dup-ed x' ) t:eq( deep.x.y, deep.x2.y ) end function test.contains(t) local c = tableutil.contains t:eq( true, c( nil, nil ) ) t:eq( true, c( 1, 1 ) ) t:eq( true, c( "", "" ) ) t:eq( true, c( "a", "a" ) ) t:eq( false, c( 1, 2 ) ) t:eq( false, c( 1, nil ) ) t:eq( false, c( nil, 1 ) ) t:eq( false, c( {}, 1 ) ) t:eq( false, c( {}, "" ) ) t:eq( false, c( "", {} ) ) t:eq( false, c( 1, {} ) ) t:eq( true, c( {}, {} ) ) t:eq( true, c( {1}, {} ) ) t:eq( true, c( {1}, {1} ) ) t:eq( true, c( {1, 2}, {1} ) ) t:eq( true, c( {1, 2}, {1, 2} ) ) t:eq( true, c( {1, 2, a=3}, {1, 2} ) ) t:eq( true, c( {1, 2, a=3}, {1, 2, a=3} ) ) t:eq( false, c( {1, 2, a=3}, {1, 2, b=3} ) ) t:eq( false, c( {1, 2 }, {1, 2, b=3} ) ) t:eq( false, c( {1}, {1, 2, b=3} ) ) t:eq( false, c( {}, {1, 2, b=3} ) ) t:eq( true, c( {1, 2, a={ x=1 }}, {1, 2} ) ) t:eq( true, c( {1, 2, a={ x=1, y=2 }}, {1, 2, a={}} ) ) t:eq( true, c( {1, 2, a={ x=1, y=2 }}, {1, 2, a={x=1}} ) ) t:eq( true, c( {1, 2, a={ x=1, y=2 }}, {1, 2, a={x=1, y=2}} ) ) t:eq( false, c( {1, 2, a={ x=1 }}, {1, 2, a={x=1, y=2}} ) ) -- self reference local a = { x=1 } local b = { x=1 } a.self = { x=1 } b.self = {} t:eq( true, c( a, b ) ) t:eq( false, c( b, a ) ) a.self = a b.self = nil t:eq( true, c( a, b ) ) t:eq( false, c( b, a ) ) a.self = a b.self = b t:eq( true, c( a, b ) ) t:eq( true, c( b, a ) ) a.self = { self=a } b.self = nil t:eq( true, c( a, b ) ) t:eq( false, c( b, a ) ) a.self = { self=a, x=1 } b.self = b t:eq( true, c( a, b ) ) a.self = { self={ self=a, x=1 }, x=1 } b.self = { self=b } t:eq( true, c( a, b ) ) -- cross reference a.self = { x=1 } b.self = { x=1 } a.self.self = b b.self.self = a t:eq( true, c( a, b ) ) t:eq( true, c( b, a ) ) end function test.eq(t) local c = tableutil.eq t:eq( true, c( nil, nil ) ) t:eq( true, c( 1, 1 ) ) t:eq( true, c( "", "" ) ) t:eq( true, c( "a", "a" ) ) t:eq( false, c( 1, 2 ) ) t:eq( false, c( 1, nil ) ) t:eq( false, c( nil, 1 ) ) t:eq( false, c( {}, 1 ) ) t:eq( false, c( {}, "" ) ) t:eq( false, c( "", {} ) ) t:eq( false, c( 1, {} ) ) t:eq( true, c( {}, {} ) ) t:eq( true, c( {1}, {1} ) ) t:eq( true, c( {1, 2}, {1, 2} ) ) t:eq( true, c( {1, 2, a=3}, {1, 2, a=3} ) ) t:eq( false, c( {1, 2}, {1} ) ) t:eq( false, c( {1, 2, a=3}, {1, 2} ) ) t:eq( false, c( {1, 2, a=3}, {1, 2, b=3} ) ) t:eq( false, c( {1, 2 }, {1, 2, b=3} ) ) t:eq( false, c( {1}, {1, 2, b=3} ) ) t:eq( false, c( {}, {1, 2, b=3} ) ) t:eq( true, c( {1, 2, a={ x=1, y=2 }}, {1, 2, a={x=1, y=2}} ) ) t:eq( false, c( {1, 2, a={ x=1 }}, {1, 2, a={x=1, y=2}} ) ) -- self reference local a = { x=1 } local b = { x=1 } a.self = { x=1 } b.self = {} t:eq( false, c( a, b ) ) a.self = { x=1 } b.self = { x=1 } t:eq( true, c( a, b ) ) a.self = a b.self = nil t:eq( false, c( b, a ) ) a.self = a b.self = b t:eq( true, c( a, b ) ) t:eq( true, c( b, a ) ) a.self = { self=a } b.self = nil t:eq( false, c( a, b ) ) a.self = { self=a, x=1 } b.self = b t:eq( true, c( a, b ) ) a.self = { self={ self=a, x=1 }, x=1 } b.self = { self=b, x=1 } t:eq( true, c( a, b ) ) -- cross reference a.self = { x=1 } b.self = { x=1 } a.self.self = b b.self.self = a t:eq( true, c( a, b ) ) t:eq( true, c( b, a ) ) end function test.cmp_list(t) for _, a, b, desc in t:case_iter(2, { {nil, nil, }, {1, true, }, {1, '', }, {true, true, }, {true, nil, }, {{}, 1, }, {{}, true, }, {{'a'}, {1}, }, {{{'a'}}, {{1}}, }, {function()end, function()end, }, {function()end, 1, }, }) do t:err(function() tableutil.cmp_list(a, b) end, desc) end for _, a, b, expected, desc in t:case_iter(3, { {0, 0, 0 }, {1, 0, 1 }, {2, 0, 1 }, {2, 2, 0 }, {2, 3, -1 }, {'', '', 0 }, {'a', 'b', -1 }, {'c', 'b', 1 }, {'foo', 'foo', 0 }, {{}, {}, 0 }, {{1}, {}, 1 }, {{1}, {1}, 0 }, {{1,0}, {1}, 1 }, {{1,0}, {1,0}, 0 }, {{1,0}, {1,0,0}, -1 }, {{'a'}, {'a',1}, -1 }, {{'a',1,1}, {'a',1}, 1 }, {{'a',1,{'b'}}, {'a',1,{'b'}}, 0 }, {{'a',1,{'c'}}, {'a',1,{'b'}}, 1 }, {{'a',1,{'c',1}}, {'a',1,{'c',1}}, 0 }, {{'a',1,{'c',1,1}}, {'a',1,{'c',1}}, 1 }, {{'a',1,{'c',1}}, {'a',1,{'c',1,1}}, -1 }, {{'a',1,{'c',1}}, {'a',1,{'c',2}}, -1 }, {{'a',1,{'c',2}}, {'a',1,{'c',1}}, 1 }, }) do local rst = tableutil.cmp_list(a, b) dd('rst: ', rst) t:eq(expected, rst, desc) end end function test.intersection(t) local a = { a=1, 10 } local b = { 11, 12 } local c = tableutil.intersection( { a, b }, true ) t:eq( 1, tableutil.nkeys( c ), 'c has 1' ) t:eq( true, c[ 1 ] ) local d = tableutil.intersection( { a, { a=20 } }, true ) t:eq( 1, tableutil.nkeys( d ) ) t:eq( true, d.a, 'intersection a' ) local e = tableutil.intersection( { { a=1, b=2, c=3, d=4 }, { b=2, c=3 }, { b=2, d=5 } }, true ) t:eq( 1, tableutil.nkeys( e ) ) t:eq( true, e.b, 'intersection of 3' ) end function test.union(t) local a = tableutil.union( { { a=1, b=2, c=3 }, { a=1, d=4 } }, 0 ) t:eqdict( { a=0, b=0, c=0, d=0 }, a ) end function test.mergedict(t) t:eqdict( { a=1, b=2, c=3 }, tableutil.merge( { a=1, b=2, c=3 } ) ) t:eqdict( { a=1, b=2, c=3 }, tableutil.merge( {}, { a=1, b=2 }, { c=3 } ) ) t:eqdict( { a=1, b=2, c=3 }, tableutil.merge( { a=1 }, { b=2 }, { c=3 } ) ) t:eqdict( { a=1, b=2, c=3 }, tableutil.merge( { a=0 }, { a=1, b=2 }, { c=3 } ) ) local a = { a=1 } local b = { b=2 } local c = tableutil.merge( a, b ) t:eq( true, a==c ) a.x = 10 t:eq( 10, c.x ) end function test.depth_iter(t) for _, _ in tableutil.depth_iter({}) do t:err( "should not get any keys" ) end for ks, v in tableutil.depth_iter({1}) do t:eqdict( {1}, ks ) t:eq( 1, v ) end for ks, v in tableutil.depth_iter({a="x"}) do t:eqdict( {{"a"}, "x"}, {ks, v} ) end local a = { 1, 2, 3, { 1, 2, 3, 4 }, a=1, c=100000, d=1, x={ 1, { 1, 2 }, y={ a=1, b=2 } }, ['fjklY*(']={ x=1, b=3, }, [100]=33333 } a.z = a.x local r = { { {1}, 1 }, { {100}, 33333 }, { {2}, 2 }, { {3}, 3 }, { {4,1}, 1 }, { {4,2}, 2 }, { {4,3}, 3 }, { {4,4}, 4 }, { {"a"}, 1 }, { {"c"}, 100000 }, { {"d"}, 1 }, { {"fjklY*(","b"}, 3 }, { {"fjklY*(","x"}, 1 }, { {"x",1}, 1 }, { {"x",2,1}, 1 }, { {"x",2,2}, 2 }, { {"x","y","a"}, 1 }, { {"x","y","b"}, 2 }, { {"z",1}, 1 }, { {"z",2,1}, 1 }, { {"z",2,2}, 2 }, { {"z","y","a"}, 1 }, { {"z","y","b"}, 2 }, } local i = 0 for ks, v in tableutil.depth_iter(a) do i = i + 1 t:eqdict( r[i], {ks, v} ) end end function test.has(t) local cases = { {nil, {}, true}, {1, {1}, true}, {1, {1, 2}, true}, {1, {1, 2, 'x'}, true}, {'x', {1, 2, 'x'}, true}, {1, {x=1}, true}, {'x', {x=1}, false}, {"x", {1}, false}, {"x", {1, 2}, false}, {1, {}, false}, } for ii, c in ipairs(cases) do local val, tbl, expected = t:unpack(c) local msg = 'case: ' .. tostring(ii) .. '-th ' dd(msg, c) t:eq(expected, tableutil.has(tbl, val)) end end function test.remove_value(t) local t1 = {} local cases = { {{}, nil, {}, nil}, {{1, 2, 3}, 2, {1, 3}, 2}, {{1, 2, 3, x=4}, 2, {1, 3, x=4}, 2}, {{1, 2, 3}, 3, {1, 2}, 3}, {{1, 2, 3, x=4}, 3, {1, 2, x=4}, 3}, {{1, 2, 3, x=4}, 4, {1, 2, 3}, 4}, {{1, 2, 3, x=t1}, t1, {1, 2, 3}, t1}, {{1, 2, t1, x=t1}, t1, {1, 2, x=t1}, t1}, } for i, case in ipairs(cases) do local tbl, val, expected_tbl, expected_rst = case[1], case[2], case[3], case[4] local rst = tableutil.remove_value(tbl, val) t:eqdict(expected_tbl, tbl, i .. 'th tbl') t:eq(expected_rst, rst, i .. 'th rst') end end function test.remove_all(t) local t1 = {} local cases = { {{}, nil, {}, 0}, {{1,2,3}, 2, {1, 3}, 1}, {{1,2,3,x=4}, 2, {1, 3, x=4}, 1}, {{1,2,3,x=2}, 2, {1, 3}, 2}, {{1,2,3}, 3, {1, 2}, 1}, {{1,2,3,x=4}, 3, {1, 2, x=4}, 1}, {{1,2,3,4,x=4}, 4, {1, 2, 3}, 2}, {{1,t1,3,x=t1,y=t1}, t1, {1, 3}, 3}, {{1,2,t1,x=t1}, t1, {1, 2}, 2}, } for i, case in ipairs(cases) do local tbl, val, expected_tbl, expected_rst = case[1], case[2], case[3], case[4] local rst = tableutil.remove_all(tbl, val) t:eqdict(expected_tbl, tbl, i .. 'th tbl') t:eq(expected_rst, rst, i .. 'th rst') end end function test.get_random_elements(t) local cases = { {1, nil, 1}, {'123', 2, '123'}, {{}, nil, {}}, {{1}, nil, {1}}, } for ii, c in ipairs(cases) do local tbl, n, expected = t:unpack(c) local msg = 'case: ' .. tostring(ii) .. '-th ' dd(msg, c) local rst = tableutil.random(tbl, n) t:eqdict(expected, rst, msg) end -- random continuous local expected = { {1, 2, 3}, {2, 3, 1}, {3, 1, 2} } local rst = tableutil.random({1, 2, 3}, nil) t:eqdict(expected[rst[1]], rst, 'rand {1, 2, 3}, nil') end function test.list_len(t) for _, tbl, kind, expected, desc in t:case_iter(3, { { {1, 2, 3, 4, {5, 6}, foo={1, 2, 3}}, nil, 5, }, { {1, 2, 3, 4, {5, 6}, foo={1, 2, 3}}, 'max_index', 5, }, { {1, 2, 3, 4, {5, 6}, foo={1, 2, 3}}, 'size', 5, }, { {1, 2, 3, 4, {5, 6}, foo={1, 2, 3}}, 'end_by_nil', 5, }, { {nil, 2, 3, [999]=999, ['1000']=1000}, 'end_by_nil', 0, }, { {nil, 2, 3, [999]=999, ['1000']=1000}, nil, 0, }, { {nil, 2, 3, [998]=998, [999]=999, ['1000']=1000}, 'size', 3, }, { {nil, 2, 3, [998]=998, [999]=999, ['1000']=1000}, 'max_index', 999, }, { {1, {}, '2', nil, [998]=998, ['1000']=1000}, nil, 3, }, { {1, {}, '2', nil, [998]=998, ['1000']=1000}, 'size', 3, }, { {1, {}, '2', nil, [998]=998, ['1000']=1000}, 'max_index', 998, }, { {1, 2, 3, 4, nil, 6}, 'end_by_nil', 4, }, { {1, 2, 3, 4, nil, 6}, 'size', 6, }, { {1, 2, 3, 4, nil, nil}, 'size', 4, }, }) do local r = tableutil.list_len(tbl, kind) t:eq(expected, r, desc) end end function test.test_reverse(t) for _, tbl, opts, expected, desc in t:case_iter(3, { { {1, '2', 3, nil, {5, 6}, [8]=8, foo={1, 2, 3}}, nil, {3, '2', 1}, }, { {1, '2', 3, nil, {5, 6}, [8]=8, foo={1, 2, 3}}, {array_len_kind='max_index'}, {8, nil, nil, {5, 6}, nil, 3, '2', 1}, }, { {1, '2', 3, nil, {5, 6}, [8]=8, foo={1, 2, 3}}, {array_len_kind='max_index', recursive='array'}, {8, nil, nil, {6, 5}, nil, 3, '2', 1}, }, { {1, '2', 3, nil, {5, 6}, [8]=8, foo={1, 2, 3}}, {array_len_kind='max_index', recursive='hash'}, {8, nil, nil, {5, 6}, nil, 3, '2', 1}, }, { {1, '2', 3, nil, {5, 6}, [8]=8, foo={1, 2, 3}}, {array_len_kind='max_index', recursive='hash', hash='keep'}, {8, nil, nil, {5, 6}, nil, 3, '2', 1, foo={3, 2, 1}}, }, { {1, '2', 3, nil, {5, 6}, [8]=8, foo={1, 2, 3}}, {array_len_kind='max_index', recursive='array', hash='keep'}, {8, nil, nil, {6, 5}, nil, 3, '2', 1, foo={1, 2, 3}}, }, { {1, 2, {3, 4, foo={1, 2}}, foo={1, 2, {3, 4}, bar={1, 2}}}, nil, {{3, 4, foo={1, 2}}, 2, 1}, }, { {1, 2, {3, 4, foo={1, 2}}, foo={1, 2, {3, 4}, bar={1, 2}}}, {hash='keep'}, {{3, 4, foo={1, 2}}, 2, 1, foo={1, 2, {3, 4}, bar={1, 2}}}, }, { {1, 2, {3, 4, foo={1, 2}}, foo={1, 2, {3, 4}, bar={1, 2}}}, {hash='keep', recursive='array'}, {{4, 3, foo={1, 2}}, 2, 1, foo={1, 2, {3, 4}, bar={1, 2}}}, }, { {1, 2, {3, 4, foo={1, 2}}, foo={1, 2, {3, 4}, bar={1, 2}}}, {hash='keep', recursive='hash'}, {{3, 4, foo={1, 2}}, 2, 1, foo={{3, 4}, 2, 1, bar={2, 1}}}, }, { {1, 2, {3, 4, foo={1, 2}}, foo={1, 2, {3, 4}, bar={1, 2}}}, {hash='keep', recursive='all'}, {{4, 3, foo={2, 1}}, 2, 1, foo={{4, 3}, 2, 1, bar={2, 1}}}, }, { {1, 2, 3, 4, foo={bar={}}}, {hash='keep'}, {4, 3, 2, 1, foo={bar={}}}, }, { {1, 2, 3, 4, foo={bar={}}}, {hash='discard'}, {4, 3, 2, 1}, }, { {}, {hash='keep', recursive='all', array_len_kind='max_index'}, {}, }, { {[1001]=1001, [1005]=1005}, {hash='keep', recursive='all', array_len_kind='max_index'}, {1005, nil, nil, nil, 1001}, }, }) do local r = tableutil.reverse(tbl, opts) t:eqdict(expected, r, desc) end end function test.test_reverse_time(t) local large_index = 1024 * 1024 * 1024 local tbl = {[large_index] = 'foo', [large_index + 1]='bar'} local start_ms = time.get_ms() local r = tableutil.reverse(tbl, {array_len_kind='max_index'}) local time_used = time.get_ms() - start_ms t:eqdict({'bar', 'foo'}, r) test.dd(string.format('reverse with large index time_used: %d ms', time_used)) t:eq(true, time_used < 10) end function test.extends(t) for _, a, b, desc in t:case_iter(2, { {{'a'}, 1, }, {{'a'}, 'a', }, {{'a'}, function()end, }, }) do t:err(function() tableutil.extends(a, b) end, desc) end for _, a, b, expected, desc in t:case_iter(3, { {{1,2}, {3,4}, {1,2,3,4} }, {{1,2}, {3}, {1,2,3} }, {{1,2}, {nil}, {1,2} }, {{1,2}, {}, {1,2} }, {{}, {1,2}, {1,2} }, {nil, {1}, nil }, {{1,{2,3}}, {4,5}, {1,{2,3},4,5} }, {{1}, {{2,3},4,5}, {1,{2,3},4,5} }, {{"xx",2}, {3,"yy"}, {"xx",2,3,"yy"}}, {{1,2}, {3,nil,4}, {1,2,3} }, {{1,nil,2}, {3,4}, {1,3,2,4} }, }) do local rst = tableutil.extends(a, b) dd('rst: ', rst) t:eqdict(expected, rst, desc) end end function test.is_empty(t) local cases = { {{} , true}, {{1} , false}, {{key='val'} , false}, } for ii, c in ipairs(cases) do local tbl, expected = t:unpack(c) local msg = 'case: ' .. tostring(ii) .. '-th ' dd(msg, c) local rst = tableutil.is_empty(tbl) t:eq(expected, rst) end t:eq(false, tableutil.is_empty()) end function test.get(t) local table_key = {} local cases = { {nil, '', nil, 'NotFound'}, {nil, {''}, nil, 'NotFound'}, {nil, 'a', nil, 'NotFound'}, {nil, {'a'}, nil, 'NotFound'}, {{}, 'a', nil, nil}, {{}, {'a'}, nil, nil}, {{}, 'a.b', nil, 'NotFound'}, {{}, {'a','b'}, nil, 'NotFound'}, {{a=1}, '', nil, nil}, {{a=1}, {''}, nil, nil}, {{a=1}, 'a', 1, nil}, {{a=1}, {'a'}, 1, nil}, {{a=1}, 'a.b', nil, 'NotTable'}, {{a=1}, {'a','b'}, nil, 'NotTable'}, {{a=true}, 'a.b', nil, 'NotTable'}, {{a=true}, {'a','b'}, nil, 'NotTable'}, {{a=""}, 'a.b', nil, 'NotTable'}, {{a=""}, {'a','b'}, nil, 'NotTable'}, {{a={b=1}}, 'a.b', 1, nil}, {{a={b=1}}, {'a','b'}, 1, nil}, {{a={b=1}}, 'a.b.cc', nil, 'NotTable' }, {{a={b=1}}, {'a','b','cc'}, nil, 'NotTable' }, {{a={b=1}}, 'a.b.cc.dd', nil, 'NotTable' }, {{a={b=1}}, {'a','b','cc','dd'}, nil, 'NotTable' }, {{a={b=1}}, 'a.x.cc', nil, 'NotFound' }, {{a={b=1}}, {'a','x','cc'}, nil, 'NotFound' }, {{[table_key]=1}, { table_key }, 1, nil}, {{[table_key]=1}, {{}}, nil, nil}, {{[table_key]=1}, {{},{}}, nil, 'NotFound'}, {{[table_key]=1}, { table_key, table_key }, nil, 'NotTable'}, {{[table_key]={[table_key]=1}}, { table_key, table_key }, 1, nil}, {{[table_key]={[table_key]=1}}, {{},{}}, nil, 'NotFound'}, {{[table_key]={[table_key]=1}}, { table_key, table_key, table_key }, nil, 'NotTable'}, } for ii, c in ipairs(cases) do local tbl, key_path, expected_rst, expected_err = t:unpack(c) local msg = 'case: ' .. tostring(ii) .. '-th ' dd(msg, c) local rst, err = tableutil.get(tbl, key_path) t:eq(expected_rst, rst) t:eq(expected_err, err) end end function test.set(t) local table_key = {} for _, tbl, key_path, value, opts, exp_r, exp_err, desc in t:case_iter(6, { { nil, nil, 'foo', nil, nil, 'NotTable', }, { nil, '', 'foo', {}, nil, 'NotTable', }, { nil, {''}, 'foo', {}, nil, 'NotTable', }, { nil, 'foo.bar', 123, nil, nil, 'NotTable', }, { nil, {'foo','bar'}, 123, nil, nil, 'NotTable', }, { 'foo', 'foo.bar', 123, nil, nil, 'NotTable', }, { 'foo', {'foo','bar'}, 123, nil, nil, 'NotTable', }, { {}, 'foo', 123, nil, {foo=123}, nil, }, { {}, {'foo'}, 123, nil, {foo=123}, nil, }, { {}, 'foo.bar', 123, nil, {foo={bar=123}}, nil, }, { {}, {'foo','bar'}, 123, nil, {foo={bar=123}}, nil, }, { {foo='abc'}, 'foo.bar', 123, nil, nil, 'NotTable', }, { {foo='abc'}, {'foo','bar'}, 123, nil, nil, 'NotTable', }, { {foo='abc'}, 'foo.bar', 123, {override=true}, {foo={bar=123}}, nil, }, { {foo='abc'}, {'foo','bar'}, 123, {override=true}, {foo={bar=123}}, nil, }, { {foo={foo=123}}, 'foo.bar', 123, {override=true}, {foo={foo=123, bar=123}}, nil, }, { {foo={foo=123}}, {'foo','bar'}, 123, {override=true}, {foo={foo=123, bar=123}}, nil, }, { {a={b={c=1}}}, 'a.b.c', 123, {override=true}, {a={b={c=123}}}, nil, }, { {a={b={c=1}}}, {'a','b','c'}, 123, {override=true}, {a={b={c=123}}}, nil, }, { {a={b={c=1}}}, 'a.b.c', 123, {}, nil, 'KeyPathExist', }, { {a={b={c=1}}}, {'a','b','c'}, 123, {}, nil, 'KeyPathExist', }, { {a={b={c=1}}}, 'a.b.c.d', 123, {override=true}, {a={b={c={d=123}}}}, nil, }, { {a={b={c=1}}}, {'a','b','c','d'}, 123, {override=true}, {a={b={c={d=123}}}}, nil, }, { {a={b={c=1}}}, 'a.b.c.d', 123, {}, nil, 'NotTable', }, { {a={b={c=1}}}, {'a','b','c','d'}, 123, {}, nil, 'NotTable', }, { {a={b={c=1}}}, 'a.b.c.d', {e=123}, {override=true}, {a={b={c={d={e=123}}}}}, nil, }, { {a={b={c=1}}}, {'a','b','c','d'}, {e=123}, {override=true}, {a={b={c={d={e=123}}}}}, nil, }, { {a={b={c=1}}}, 'a.b.e.f', {g=123}, {}, {a={b={c=1, e={f={g=123}}}}}, nil, }, { {a={b={c=1}}}, {'a','b','e','f'}, {g=123}, {}, {a={b={c=1, e={f={g=123}}}}}, nil, }, { {[table_key]=1}, {table_key, table_key}, 2, {override=true}, {[table_key]={[table_key]=2}}, nil }, { {[table_key]={[table_key]=1}}, {table_key}, 2, {}, nil, 'KeyPathExist' }, { {[table_key]={[table_key]=1}}, {table_key}, 2, {override=true}, {[table_key]=2}, nil }, { {[table_key]={[table_key]=1}}, {table_key, table_key}, 2, {override=true}, {[table_key]={[table_key]=2}}, nil }, { {[table_key]={[table_key]=1}}, {table_key, table_key, table_key}, 2, {}, nil, 'NotTable' }, { {}, {table_key}, 1, {}, {[table_key]=1}, nil }, { {}, {table_key, table_key}, 1, {}, {[table_key]={[table_key]=1}}, nil }, { {[table_key]=1}, {table_key}, 2, {}, nil, 'KeyPathExist' }, { {[table_key]=1}, {table_key}, 2, {override=true}, {[table_key]=2}, nil }, { {[table_key]=1}, {table_key, table_key}, 2, {}, nil, 'NotTable' }, }) do local r, err, errmsg = tableutil.set(tbl, key_path, value, opts) t:eqdict(exp_r, r, string.format('%s %s %s', desc, err, errmsg)) t:eq(exp_err, err, desc) end end function test.updatedict(t) local cases = { {{}, {}, nil, {} }, {{a=1}, {}, nil, {a=1} }, {{a=1}, {a=2}, nil, {a=2} }, {{a=1}, {a=1,b=2}, nil, {a=1,b=2} }, {{}, {a={b={c=1}}}, nil, {a={b={c=1}}} }, {{a='foo'}, {a={b={c=1}}}, nil, {a={b={c=1}}} }, {{a={}}, {a={b={c=1}}}, nil, {a={b={c=1}}} }, {{1}, {a={b={c=1}}}, nil, {1,a={b={c=1}}} }, {{b=1}, {a={b={c=1}}}, nil, {b=1,a={b={c=1}}} }, {{a=1}, {a=2}, {force=false}, {a=1} }, {{a={b=1}}, {a={b=2}}, {force=false}, {a={b=1}} }, {{a={b=1}}, {a=2}, {force=false}, {a={b=1}} }, {{a={b={c=1}}}, {a=2}, {recursive=false}, {a=2} }, {{a={b={c=1}}}, {a={}}, {recursive=false}, {a={}} }, {{a=1}, {a={}}, {recursive=false}, {a={}} }, } for ii, c in ipairs(cases) do local tbl, src, opts, expected_rst = t:unpack(c) local msg = 'case: ' .. tostring(ii) .. '-th ' dd(msg, c) local rst = tableutil.update(tbl, src, opts) dd('rst:', rst) t:eqdict(expected_rst, rst) end local a = {} a.a1 = a a.a2 = a local b = tableutil.update({}, a) t:eq(b.a1, b.a1.a1, 'test loop reference') t:eq(b.a1, b.a2, 'two loop references should be equal') t:neq(a, b.a1) end function test.make_setter(t) local function make_v(current_val) return 'made: ' .. tostring(current_val) end for _, dst, k, v, mode, expected, desc in t:case_iter(5, { {{}, 'x', 2, nil, {x=2}}, {{}, 'x', 2, 'keep', {x=2}}, {{}, 'x', 2, 'replace', {x=2}}, {{x=1}, 'x', 2, nil, {x=2}}, {{x=1}, 'x', 2, 'keep', {x=1}}, {{x=1}, 'x', 2, 'replace', {x=2}}, {{x=1}, {x=2,y=3}, nil, nil, {x=2,y=3}}, {{x=1}, {x=2,y=3}, nil, 'keep', {x=1,y=3}}, {{x=1}, {x=2,y=3}, nil, 'replace', {x=2,y=3}}, {{x=1}, {x=make_v,y=3}, nil, nil, {x='made: 1',y=3}}, {{x=1}, {x=make_v,y=3}, nil, 'keep', {x=1,y=3}}, {{x=1}, {x=make_v,y=3}, nil, 'replace', {x='made: 1',y=3}}, }) do local setter = tableutil.make_setter(k, v, mode) setter(dst) local rst = dst dd('rst: ', rst) t:eqdict(expected, rst, desc) end end function test.make_setter_invalid_arg(t) for _, mode, expected, desc in t:case_iter(2, { {nil, true }, {'replace', true }, {'keep', true }, {'foo', false }, {0, false }, {true, false }, {function()end, false }, {{}, false }, }) do if expected then tableutil.make_setter(1, 1, mode) else t:err(function() tableutil.make_setter(1, 1, mode) end, desc) end end end function test.default_setter(t) local function make_v() return 'vv' end for _, dst, k, v, expected, desc in t:case_iter(4, { {{}, 'x', 2, {x=2}}, {{x=1}, 'x', 2, {x=1}}, {{x=1}, {x=2,y=3}, nil, {x=1,y=3}}, {{x=1}, {x=make_v,y=make_v}, nil, {x=1,y='vv'}}, }) do local setter = tableutil.default_setter(k, v) setter(dst) local rst = dst dd('rst: ', rst) t:eqdict(expected, rst, desc) end end function test.combine_and_add(t) local opts_default = nil local opts_recursive = { recursive = true } local opts_default_value = { default = 1 } local opts_recursive_default_value = { recursive = true, default = 1} local opts_recursive_default_value_exclude = { recursive = true, default = 1, exclude={a={b={c={d=true}}},g=true} } local cases_recursive = { {opts_default, {x=1,y=true,z=3}, {x=1,y=2,z=true}, {x=2,y=true,z=3}}, {opts_default, {x=1,y=2,z=3}, {x=1,y=2,z=3}, {x=2,y=4,z=6}}, {opts_default, {x=1,y=2,z=3}, {x=1,z=3}, {x=2,y=2,z=6}}, {opts_default, {x=1,z=3}, {x=1,y=2,z=3}, {x=2,z=6}}, {opts_default, {}, {x=1,y=2,z=3}, {}}, {opts_default, {x=1,y=2,z=3}, {}, {x=1,y=2,z=3}}, {opts_default, {x=1,y=2,z=3}, {x={x1=1}}, {x=1,y=2,z=3}}, {opts_recursive, {x={y={z=1}},c=1}, {x={y={z=1}},c=1}, {x={y={z=2}},c=2}}, {opts_recursive, {x={y={z=1}},c=1,z={}}, {x={y={z=1}},c=1,z=1,d=1}, {x={y={z=2}},c=2,z={}}}, {opts_recursive, {x={y={z=1}},c=1,z={}}, {x={y={z=1}},c=1,z=1}, {x={y={z=2}},c=2,z={}} }, {opts_recursive, {x={y=1},c=1}, {x={z=1},c=1}, {x={y=1},c=2}}, {opts_default_value, {x=1,y=2,z=3}, {x=1,z=3}, {x=2,y=2,z=6}}, {opts_default_value, {x=1,z=3}, {x=1,y=2,z=3}, {x=2,y=3,z=6}}, {opts_default_value, {}, {x=1,y=2,z=3}, {x=2,y=3,z=4}}, {opts_default_value, {x=1,y=2,z=3}, {}, {x=1,y=2,z=3}}, {opts_default_value, {x=1,y=2,z=3}, {x={x1=1}}, {x=1,y=2,z=3}}, {opts_default_value, {c=1}, {x={z=1},c=1}, {c=2}}, {opts_recursive_default_value, {c=1}, {x={z=1},c=1}, {x={z=2},c=2}}, {opts_recursive_default_value, {x={y={z=1}},c=1}, {x={y={z=1}},c=1}, {x={y={z=2}},c=2}}, {opts_recursive_default_value, {x={y={z=1}},c=1,z={}}, {x={y={z=1}},c=1,z=1,d=1}, {x={y={z=2}},c=2,z={},d=2}}, {opts_recursive_default_value, {x={y={z=1}},c=1,z={}}, {x={y={z=1,d=1}},c=1,z=1}, {x={y={z=2,d=2}},c=2,z={}}}, {opts_recursive_default_value, {x={y=1},c=1}, {x={z=1},c=1}, {x={y=1,z=2},c=2}}, {opts_recursive_default_value_exclude, {a={b={c={d=1},e=1}},f=1,g=1}, {a={b={c={d=1},e=1}},f=2,e=1,g=1}, {a={b={c={d=1},e=2}},f=3,e=2,g=1}}, } for ii, case in ipairs(cases_recursive) do local opts, a, b, expected = t:unpack(case) local rst = tableutil.combine(a, b, function(a, b) return a + b end, opts) t:eqdict(expected, rst) local copy_a = tableutil.dup(a, true) tableutil.combineto(copy_a, b, function(a, b) return a + b end, opts) t:eqdict(expected, copy_a) local rst = tableutil.add(a, b, opts) t:eqdict(expected, rst) local copy_a = tableutil.dup(a, true) tableutil.addto(copy_a, b, opts) t:eqdict(expected, copy_a) end end
mit
CHBMB/docker-containers
cloudflare/cf-dns-ip.py
1080
#!/usr/bin/env python # set ENV: # CFKEY=API-key # CFUSER=username(email) # CFZONE=zone-name # CFDNIP=x.x.x.x # CFHOST=host1-you-want-to-change,host2-you-want-to-change # CFTYPE=A,CNAME # effect rec type from cloudflare import CloudFlare import os cfkey = os.getenv("CFKEY", "") cfuser = os.getenv("CFUSER", "") cfzone = os.getenv("CFZONE", "") cfdnip = os.getenv("CFDNIP", "") cfhost = os.getenv("CFHOST", "").split(",") cftype = os.getenv("CFTYPE", "") if cftype == "": cftype = "A,CNAME" cftype = cftype.split(",") def filter_rec(rec): return rec["name"] in cfhost and rec["type"] in cftype cfapi = CloudFlare(cfuser, cfkey) recobjs = cfapi.rec_load_all(cfzone)["response"]["recs"]["objs"] recs = list(filter(filter_rec, recobjs)) for rec in recs: res = cfapi.rec_edit( z=cfzone, _type=rec["type"], _id=rec["rec_id"], name=rec["name"], content=cfdnip, service_mode=rec["service_mode"], ttl=rec["ttl"]) if res["msg"] == None: print(rec["name"], "update", cfdnip, res["result"]) else: print(rec["name"], "update", cfdnip, res["result"], res["msg"])
mit
TimPetricola/blueskies
app/routes/home.rb
2622
module BlueSkies module Routes class Home < Base get '/' do erb :form, locals: form_locals(form: Forms::Recipient.new(params)) end post '/subscriptions' do form = Forms::Recipient.new(params) return erb(:form, locals: form_locals(form: form)) unless form.valid? if Models::Recipient.exists?(email: form.email) return erb :already_subscribed end recipient = Models::Recipient.create(email: form.email) now = Time.now recipient.update_schedule( week_days: form.biweekly? ? [:wednesday, :sunday] : [:sunday], time: Time.new(now.year, now.month, now.day, 9, 0, 0, form.timezone * 3600).utc ) form.interests_ids.each do |id| interest = Models::Interest[id] next unless interest recipient.add_interest(interest) end Workers::NewRecipientNotify.perform_async(recipient.id) erb :subscribe_confirm, locals: { recipient: recipient, next_digest_at: recipient.schedule.next_occurrence.to_time } end get '/subscriptions/:token/unsubscribe' do recipient = Models::Recipient.find(token: params[:token]) error 404 unless recipient recipient.delete erb :unsubscribe_confirm end get '/links.json' do interests_ids = params.fetch('interests') do Models::Interest.published.select(:id) end links = Models::Link.ranked(interests: interests_ids) content_type :json links.map do |link| { id: link.id, title: link.title, url: link.url, description: link.description, image: link.image && link.image.resized(width: 600, height: 267).to_h } end.to_json end get '/digests/sample' do interests_ids = params.fetch('interests') do Models::Interest.published.select(:id) end digest = Models::Digest.new(created_at: Time.now) links = Models::Link.ranked(interests: interests_ids).all digest.links.concat(links) delivery = Delivery.new(digest, sample: true, unsubscribe: false) delivery.html end get '/digests/:id' do digest = Models::Digest[params[:id]] error 404 unless digest delivery = Delivery.new(digest, unsubscribe: false) delivery.html end def form_locals(form:) { interests: Models::Interest.published, form: form } end end end end
mit
MaoRodriguesJ/INE5408
t1/library/ListaEnc.hpp
11366
// Copyright Bruno Marques <2016.1> #ifndef LISTAENC_HPP #define LISTAENC_HPP #include <stdexcept> #include "Elemento.hpp" //! Classe da estrutura de dado: Lista Encadeada. /*! Implementação da estruturda de dado Lista Encadeada, * realizada na disciplina de Estrutura de Dados - INE5408 * como quarto trabalho prático do semestre. * \author Bruno Marques do Nascimento * \since 13/04/2016 * \version 1.0 */ template<typename T> class ListaEnc { private: Elemento<T>* head; /*!< Ponteiro para o primeiro elemento da estrutura */ int size; /*!< Inteiro que guarda o tamanho da Lista Encadeada */ public: //! Contrutor padrão. /*! Sempre que usado, este construtor criará uma * lista encadeada de tamanho zero, * e com o ponteiro "head" sendo um ponteiro nulo. */ ListaEnc(); //! Destrutor. /*! Tem a função de destruir todos * os nós da lista encadeada. */ ~ListaEnc(); //! Função adicionaNoInicio, insere um dado no inicio da lista encadeada. /*! * \param dado argumento do tipo T, que será adicionado na lista encadeada. * \sa ListaEnc() */ void adicionaNoInicio(const T& dado); //! Função retiraDoInicio, retira o dado da posição inicial da lista encadeada. /*! * \return o dado retirado da lista encadeada do tipo T. * \sa listaVazia() and ListaEnc() */ T retiraDoInicio(); //! Função eliminaDoInicio, elimina o dado do inicio da lista encadeada. /*! * \sa listaVazia() and ListaEnc() */ void eliminaDoInicio(); //! Função adicionaNaPosicao, insere um dado na posicao definida. /*! * \param dado argumento do tipo T, que será adicionado na lista encadeada. * \param pos posição de inserção desejada * \sa ListaEnc() */ void adicionaNaPosicao(const T& dado, int pos); //! Função posicao, informa a posição de um dado na lista encadeada. /*! * \param dado argumento do tipo T, que será procurado na lista encadeada. * \return um inteiro que informa a posição do dado na lista encadeada. * \sa listaVazia() and ListaEnc() */ int posicao(const T& dado) const; //! Função posicaoMem, informa a posição de memória de um dado da lista encad. /*! * \param dado argumento do tipo T, que será procurado na lista encadeada. * \return um ponteiro que informa a posição do dado na memória. * \sa listaVazia() and ListaEnc() */ T* posicaoMem(const T& dado) const; //! Função contem, informa a presença de um dado na lista encadeada. /*! * \param dado argumento do tipo T, que será procurado na lista encadeada. * \return um boolean que informa a presença do dado na lista encadeada. * \sa listaVazia() and ListaEnc() */ bool contem(const T& dado); //! Função retiraDaPosicao, retira um dado de uma posição escolhida. /*! * \param pos posição de retirada de um dado. * \return o dado retirado da lista encadeada do tipo T. * \sa listaVazia() and ListaEnc() */ T retiraDaPosicao(int pos); //! Função adiciona, insere um novo dado no fim da lista encadeada. /*! * \param dado argumento do tipo T, que será adicionado na lista encadeada. * \sa ListaEnc() */ void adiciona(const T& dado); //! Função retira, retira um dado do final da lista encadeada. /*! * \return o dado retirado da lista encadeada do tipo T. * \sa listaVazia() and ListaEnc() */ T retira(); //! Função retiraEspecifico, retira um dado específico da lista encadeada. /*! * \param dado argumento do tipo T, que será retirado da lista encadeada. * \return o dado retirado da lista encadeada do tipo T. * \sa listaVazia() and ListaEnc() */ T retiraEspecifico(const T& dado); //! Função adicionaEmOrdem insere o dado na lista encadeada em ordem crescente. /*! * \param dado argumento do tipo T, que será adicionado na lista encadeada. * \sa ListaEnc() */ void adicionaEmOrdem(const T& data); //! Função listaVazia, informa se a lista encadeada está vazia /*! * \return um boolean que informa se a lista encadeada está vazia ou não. * \sa ListaEnc() */ bool listaVazia() const; //! Função igual, informa se os dados são iguais. /*! * \param dado1 argumento do tipo T, que será comparado com dado2. * \param dado2 argumento do tipo T, que será comparado com dado1. * \return um boolean que informa se dado1 é igual ao dado2. * \sa ListaEnc() */ bool igual(T dado1, T dado2) const; //! Função maior, informa se um dado é maior que o outro. /*! * \param dado1 argumento do tipo T, que será comparado com dado2. * \param dado2 argumento do tipo T, que será comparado com dado1. * \return um boolean que informa se dado1 é maior que dado2. * \sa ListaEnc() */ virtual bool maior(T dado1, T dado2); //! Função menor, informa se um dado é menor que o outro. /*! * \param dado1 argumento do tipo T, que será comparado com dado2. * \param dado2 argumento do tipo T, que será comparado com dado1. * \return um boolean que informa se dado1 é menor que dado2. * \sa ListaEnc() */ bool menor(T dado1, T dado2); //! Função destroiLista, zera a lista encadeada descartando seus dados /*! * \sa ListaEnc() */ void destroiLista(); //! Função getHead, retorna o ponteiro que aponta para primeiro elemento. /*! * \return um ponteiro que aponta para o primeiro elemento. * \sa ListaEnc() */ Elemento<T>* getHead(); //! Função tamanho, retorna o tamanho da lista encadeada. /*! * \return um inteiro que informa o tamanho da lista encadeada. * \sa ListaEnc() */ int tamanho(); //! Função mostra, mostra um dado em uma posição escolhida. /*! * \param pos um inteiro com a posição desejada. * \return um ponteiro que aponta para o primeiro elemento. * \sa ListaEnc() */ T mostra(int pos); }; template<typename T> ListaEnc<T>::ListaEnc() { size = 0; head = nullptr; } template<typename T> ListaEnc<T>::~ListaEnc() { destroiLista(); } template<typename T> int ListaEnc<T>::tamanho() { return size; } template<typename T> T ListaEnc<T>::mostra(int pos) { if (listaVazia()) { throw std::runtime_error("Lista Vazia"); } else { if (pos > size-1 || pos < 0) { throw std::runtime_error("Erro Posição"); } else { Elemento<T>* anterior = head; for (int i = 0; i < pos-1; i++) { anterior = anterior->getProximo(); } return anterior->getInfo(); } } } template<typename T> void ListaEnc<T>::adicionaNoInicio(const T& dado) { Elemento<T>* novo = new Elemento<T>(dado, head); if (novo == nullptr) { throw std::runtime_error("Lista Vazia"); } else { head = novo; ++size; } } template<typename T> T ListaEnc<T>::retiraDoInicio() { if (listaVazia()) { throw std::runtime_error("Lista Vazia"); } else { T info = head->getInfo(); Elemento<T>* temp = getHead()->getProximo(); delete head; head = temp; --size; return info; } } template<typename T> void ListaEnc<T>::eliminaDoInicio() { if(listaVazia()) { throw std::runtime_error("Lista Vazia"); } else { Elemento<T>* temp = head->getProximo(); delete head; head = temp; --size; } } template<typename T> void ListaEnc<T>::adicionaNaPosicao(const T& dado, int pos) { if (pos > size || pos < 0) { throw std::runtime_error("Erro Posição"); } else { if (pos == 0) { adicionaNoInicio(dado); return; } else { Elemento<T>* novo = new Elemento<T>(dado, nullptr); if (novo == nullptr) { throw std::runtime_error("Lista Cheia"); } else { Elemento<T>* anterior = head; for (int i = 0; i < pos-1; ++i) { anterior = anterior->getProximo(); } novo -> setProximo(anterior->getProximo()); anterior->setProximo(novo); ++size; } } } } template<typename T> int ListaEnc<T>::posicao(const T& dado) const { if (listaVazia()) { throw std::runtime_error("Lista Vazia"); } else { Elemento<T>* aux = head; for (int i = 0; i < size; ++i) { if (igual(dado, (aux->getInfo()))) { return i; } aux = aux->getProximo(); } throw std::runtime_error("Não Contém"); } } template<typename T> T* ListaEnc<T>::posicaoMem(const T& dado) const { if (listaVazia()) { throw std::runtime_error("Lista Vazia"); } else { Elemento<T>* aux = head; for (int i = 0; i < size; ++i) { if (igual(dado, aux->getInfo())) { return aux; } aux = aux->getProximo(); } throw std::runtime_error("Não Contém"); } } template<typename T> bool ListaEnc<T>::contem(const T& dado) { if (listaVazia()) { throw "ErroListaVazia"; } else { Elemento<T>* aux = head; for (int i = 0; i < size; ++i) { if (igual(dado, aux->getInfo())) { return true; } aux = aux->getProximo(); } return false; } } template<typename T> T ListaEnc<T>::retiraDaPosicao(int pos) { if (listaVazia()) { throw std::runtime_error("Lista Vazia"); } else { if (pos > size-1 || pos < 0) { throw std::runtime_error("Erro Posição"); } else { if (pos == 0) { return retiraDoInicio(); } else { Elemento<T>* anterior = head; Elemento<T>* eliminar; for (int i = 0; i < pos-1; ++i) { anterior = anterior->getProximo(); } eliminar = anterior->getProximo(); anterior->setProximo(eliminar->getProximo()); --size; T dado = eliminar->getInfo(); delete eliminar; return dado; } } } } template<typename T> void ListaEnc<T>::adiciona(const T& dado) { adicionaNaPosicao(dado, size); } template<typename T> T ListaEnc<T>::retira() { return retiraDaPosicao(size-1); } template<typename T> T ListaEnc<T>::retiraEspecifico(const T& dado) { if (listaVazia()) { throw std::runtime_error("Lista Vazia"); } else { return retiraDaPosicao(posicao(dado)); } } template<typename T> void ListaEnc<T>::adicionaEmOrdem(const T& data) { Elemento<T>* anterior = head; int posicao = 0; while (posicao < size && maior(data, anterior->getInfo())) { anterior = anterior->getProximo(); ++posicao; } Elemento<T>* novo = new Elemento<T>(data, nullptr); if (posicao == 0) { adicionaNoInicio(data); ++size; } else { novo -> setProximo(anterior->getProximo()); anterior->setProximo(novo); ++size; } } template<typename T> bool ListaEnc<T>::listaVazia() const { return size == 0; } template<typename T> bool ListaEnc<T>::igual(T dado1, T dado2) const { return dado1 == dado2; } template<typename T> bool ListaEnc<T>::maior(T dado1, T dado2) { return dado1 > dado2; } template<typename T> bool ListaEnc<T>::menor(T dado1, T dado2) { return dado1 < dado2; } template<typename T> void ListaEnc<T>::destroiLista() { Elemento<T>* temp = head; while (head != nullptr) { temp = head->getProximo(); delete head; head = temp; } size = 0; } template<typename T> Elemento<T>* ListaEnc<T>::getHead() { return head; } #endif
mit
yosymfony/ConfigServiceProvider
src/Yosymfony/Silex/ConfigServiceProvider/Loaders/JsonLoader.php
2517
<?php /* * This file is part of the Yosymfony\ConfigurationServiceProvider. * * (c) YoSymfony <http://github.com/yosymfony> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Yosymfony\Silex\ConfigServiceProvider\Loaders; use Yosymfony\Silex\ConfigServiceProvider\ConfigFileLoader; use Yosymfony\Silex\ConfigServiceProvider\ConfigRepository; /** * JSON file loader * * @author Victor Puertas <[email protected]> */ class JsonLoader extends ConfigFileLoader { /** * {@inheritdoc} */ public function load($resource, $type = null) { if(null === $type) { $resource = $this->getLocation($resource); $data = $this->loadFile($resource); } else { $data = $resource; } $parsed = $this->parseResource($data); $errorMsg = $this->getLastErrorMessage(json_last_error()); if($errorMsg) { $msg = $type ? sprintf("JSON parse error: %s", $errorMsg) : sprintf("JSON parse error: %s at %s", $errorMsg, $resource); throw new \RuntimeException($msg); } $repository = new ConfigRepository(); $repository->load($parsed ? $parsed : array()); return $repository; } /** * {@inheritdoc} */ public function supports($resource, $type = null) { return 'json' === $type || (is_string($resource) && preg_match('#\.json(\.dist)?$#', $resource)); } private function parseResource($resource) { return json_decode($resource, true); } private function loadFile($resource) { return file_get_contents($resource); } private function getLastErrorMessage($errorCode) { $errors = array( JSON_ERROR_NONE => null, JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', ); return array_key_exists($errorCode, $errors) ? $errors[$errorCode] : sprintf('Unknown error code: %s', $errorCode); } }
mit
ddollar/heroku-sql-console
lib/heroku-sql-console.rb
66
require 'heroku/command/sql' require 'heroku-sql-console/version'
mit
WeTransfer/apiculture
lib/apiculture/method_documentation.rb
4023
require 'builder' require 'rdiscount' # Generates Markdown/HTML documentation about a single API action. # # Formats route parameters and request/QS parameters as a neat HTML # table, listing types, requirements and descriptions. # # Is used by AppDocumentation to compile a document on the entire app's API # structure in one go. class Apiculture::MethodDocumentation def initialize(action_definition, mountpoint = '') @definition = action_definition @mountpoint = mountpoint end # Compose a Markdown definition of the action def to_markdown m = MDBuf.new m << "## #{@definition.http_verb.upcase} #{@mountpoint}#{@definition.path}" m << @definition.description m << route_parameters_table m << request_parameters_table m << possible_responses_table m.to_s end # Compose an HTML string by converting the result of +to_markdown+ def to_html_fragment markdown_string_to_html(to_markdown) end private def markdown_string_to_html(str) RDiscount.new(str.to_s).to_html end class StringBuf #:nodoc: def initialize; @blocks = []; end def <<(block); @blocks << block.to_s; self; end def to_s; @blocks.join; end end class MDBuf < StringBuf #:nodoc: def to_s; @blocks.join("\n\n"); end end def _route_parameters_table return '' unless @definition.defines_route_params? m = MDBuf.new b = StringBuf.new m << '### URL parameters' html = Builder::XmlMarkup.new(:target => b) html.table(class: 'apiculture-table') do html.tr do html.th 'Name' html.th 'Description' end @definition.route_parameters.each do | param | html.tr do html.td { html.tt(':%s' % param.name) } html.td { html << markdown_string_to_html(param.description) } end end end m << b.to_s end def body_example(for_response_definition) if for_response_definition.no_body? '(empty)' else begin JSON.pretty_generate(for_response_definition.jsonable_object_example) rescue JSON::GeneratorError # pretty_generate refuses to generate scalars # it wants objects or arrays. For bare JSON values .dump will do JSON.dump(for_response_definition.jsonable_object_example) end end end def possible_responses_table return '' unless @definition.defines_responses? m = MDBuf.new b = StringBuf.new m << '### Possible responses' html = Builder::XmlMarkup.new(:target => b) html.table(class: 'apiculture-table') do html.tr do html.th('HTTP status code') html.th('What happened') html.th('Example response body') end @definition.responses.each do | resp | html.tr do html.td { html.b(resp.http_status_code) } html.td { html << markdown_string_to_html(resp.description) } html.td { html.pre { html.code(body_example(resp)) }} end end end m << b.to_s end def request_parameters_table return '' unless @definition.defines_request_params? m = MDBuf.new m << '### Request parameters' m << parameters_table(@definition.parameters).to_s end def route_parameters_table return '' unless @definition.defines_route_params? m = MDBuf.new m << '### URL parameters' m << parameters_table(@definition.route_parameters).to_s end private def parameters_table(parameters) b = StringBuf.new html = Builder::XmlMarkup.new(:target => b) html.table(class: 'apiculture-table') do html.tr do html.th 'Name' html.th 'Required' html.th 'Type after cast' html.th 'Description' end parameters.each do | param | html.tr do html.td { html.tt(param.name.to_s) } html.td(param.required ? 'Yes' : 'No') html.td(param.matchable.inspect) html.td { html << markdown_string_to_html(param.description) } end end end b end end
mit
brad-jones/ppm
src/Ppm/Contracts/IReNameVisitor.php
159
<?php namespace Brads\Ppm\Contracts; use PhpParser\NodeVisitor; interface IRenameVisitor extends NodeVisitor { public function rename($fromNs, $toNs); }
mit
CooperLuan/devops.notes
taobao/top/api/rest/AreasGetRequest.py
294
''' Created by auto_sdk on 2014-12-17 17:22:51 ''' from top.api.base import RestApi class AreasGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.fields = None def getapiname(self): return 'taobao.areas.get'
mit
gamonoid/icehrm
core/lib/composer/vendor/google/apiclient-services/src/Google/Service/CloudVideoIntelligence/GoogleCloudVideointelligenceV1p2beta1PersonDetectionAnnotation.php
1437
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed 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. */ class Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p2beta1PersonDetectionAnnotation extends Google_Collection { protected $collection_key = 'tracks'; protected $tracksType = 'Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p2beta1Track'; protected $tracksDataType = 'array'; public $version; /** * @param Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p2beta1Track */ public function setTracks($tracks) { $this->tracks = $tracks; } /** * @return Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p2beta1Track */ public function getTracks() { return $this->tracks; } public function setVersion($version) { $this->version = $version; } public function getVersion() { return $this->version; } }
mit
dragonwong/rnx-ui
Example/src/page/CardView/index.js
4573
import React, { Component, } from 'react'; import { StyleSheet, Dimensions, View, Text, } from 'react-native'; import All from 'rnx-ui/All'; import Btn from 'rnx-ui/Btn'; import { NavBar, } from 'BizComponent'; import Router from 'BizRouter'; import CardView from 'rnx-ui/CardView'; // let flag = true; function makeRandomData() { const len = 3 + Math.floor(Math.random() * 3); // const len = flag ? 2 : 4; // flag = !flag; const data = []; for (let i = 0; i < len; i += 1) { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); const color = `rgb(${r},${g},${b})`; data.push(color); } return data; } const styles = StyleSheet.create({ cardView: { height: 200, }, cardViewContainer: { paddingVertical: 30, }, card: { flex: 1, alignItems: 'center', justifyContent: 'center', }, activeCard: { borderColor: 'red', borderWidth: 2, }, cardText: { color: '#fff', fontSize: 30, }, btns: { paddingHorizontal: 10, }, btn: { marginBottom: 5, }, }); class Page extends Component { static section = 'Data Display'; constructor(props) { super(props); this.state = { cards: [], // 当前可访问的最大题目序号 // cardViewMaxIndex: 1, }; this.width = Dimensions.get('window').width; this.cardWidth = this.width - 100; this.currentCardIndex = 0; this.getCardView = this.getCardView.bind(this); this.onChange = this.onChange.bind(this); this.goNext = this.goNext.bind(this); this.goPrev = this.goPrev.bind(this); this.goThird = this.goThird.bind(this); this.refresh = this.refresh.bind(this); // this.test = this.test.bind(this); this.onEndReached = this.onEndReached.bind(this); } componentDidMount() { this.updateCards(); } onCardPress() { /* eslint-disable */ alert('Pressed!'); /* eslint-enable */ } onChange(index) { this.currentCardIndex = index; } onPass(index) { /* eslint-disable */ console.log('Passed:', index); /* eslint-enable */ } onStartReached() { /* eslint-disable */ alert('onStartReached!'); /* eslint-enable */ } onEndReached() { /* eslint-disable */ alert('onEndReached!'); /* eslint-enable */ // this.test(); } getCardView(cardView) { this.cardView = cardView; } // 更新卡片数据 updateCards() { const arr = []; const data = makeRandomData(); data.forEach((item, index) => { arr.push({ key: index, card: ( <View style={[styles.card, { backgroundColor: item, }]} > <Text style={styles.cardText} onPress={this.onCardPress} > {index} </Text> </View> ), }); }); this.setState({ cards: arr, }); } goNext() { if (this.cardView) { this.cardView.scrollTo(this.currentCardIndex + 1); } } goPrev() { if (this.cardView) { this.cardView.scrollTo(this.currentCardIndex - 1); } } goThird() { if (this.cardView) { this.cardView.scrollTo(2); } } refresh() { this.updateCards(); } // test() { // this.updateCards(); // setTimeout(() => { // this.cardView.scrollTo(0, false); // }, 0); // } render() { return ( <All> <NavBar title="CardView" /> <CardView getEl={this.getCardView} style={styles.cardView} activeCardStyle={styles.activeCard} contentContainerStyle={styles.cardViewContainer} cards={this.state.cards} cardWidth={this.cardWidth} cardGap={20} onChange={this.onChange} onPass={this.onPass} minGestureDistance={50} maxIndex={this.state.cardViewMaxIndex} onStartReached={this.onStartReached} onEndReached={this.onEndReached} /> <View style={styles.btns}> <Btn style={styles.btn} onPress={this.goNext}> 下一个 </Btn> <Btn style={styles.btn} onPress={this.goPrev}> 上一个 </Btn> <Btn style={styles.btn} onPress={this.goThird}> 第三个 </Btn> <Btn style={styles.btn} onPress={this.refresh}> 刷新卡片 </Btn> </View> </All> ); } } Router.register('CardView', Page); export default Page;
mit
attilacsanyi/material2
src/lib/core/overlay/scroll/block-scroll-strategy.ts
2407
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ScrollStrategy} from './scroll-strategy'; import {ViewportRuler} from '../position/viewport-ruler'; /** * Strategy that will prevent the user from scrolling while the overlay is visible. */ export class BlockScrollStrategy implements ScrollStrategy { private _previousHTMLStyles = { top: null, left: null }; private _previousScrollPosition: { top: number, left: number }; private _isEnabled = false; constructor(private _viewportRuler: ViewportRuler) { } attach() { } enable() { if (this._canBeEnabled()) { const root = document.documentElement; this._previousScrollPosition = this._viewportRuler.getViewportScrollPosition(); // Cache the previous inline styles in case the user had set them. this._previousHTMLStyles.left = root.style.left; this._previousHTMLStyles.top = root.style.top; // Note: we're using the `html` node, instead of the `body`, because the `body` may // have the user agent margin, whereas the `html` is guaranteed not to have one. root.style.left = `${-this._previousScrollPosition.left}px`; root.style.top = `${-this._previousScrollPosition.top}px`; root.classList.add('cdk-global-scrollblock'); this._isEnabled = true; } } disable() { if (this._isEnabled) { this._isEnabled = false; document.documentElement.style.left = this._previousHTMLStyles.left; document.documentElement.style.top = this._previousHTMLStyles.top; document.documentElement.classList.remove('cdk-global-scrollblock'); window.scroll(this._previousScrollPosition.left, this._previousScrollPosition.top); } } private _canBeEnabled(): boolean { // Since the scroll strategies can't be singletons, we have to use a global CSS class // (`cdk-global-scrollblock`) to make sure that we don't try to disable global // scrolling multiple times. if (document.documentElement.classList.contains('cdk-global-scrollblock') || this._isEnabled) { return false; } const body = document.body; const viewport = this._viewportRuler.getViewportRect(); return body.scrollHeight > viewport.height || body.scrollWidth > viewport.width; } }
mit
themoonofendor/blog
db/schema.rb
2600
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20170825171823) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "articles", force: :cascade do |t| t.string "title" t.text "text" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "comments", force: :cascade do |t| t.string "author" t.text "body" t.integer "article_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "comments", ["article_id"], name: "index_comments_on_article_id", using: :btree create_table "contacts", force: :cascade do |t| t.string "email" t.string "message" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.inet "current_sign_in_ip" t.inet "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "username" end add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree add_foreign_key "comments", "articles" end
mit
hacor/pkgcloud
lib/pkgcloud/openstack/metering/client/index.js
697
/* * index.js: Openstack Ceilometer client * * (C) 2015 Hans Cornelis * MIT LICENSE * */ var util = require('util'), urlJoin = require('url-join'), openstack = require('../../client'), _ = require('underscore'); var Client = exports.Client = function (options) { openstack.Client.call(this, options); _.extend(this, require('./meters')); _.extend(this, require('./samples')); this.serviceType = 'metering'; }; util.inherits(Client, openstack.Client); Client.prototype._getUrl = function (options) { options = options || {}; return urlJoin(this._serviceUrl, typeof options === 'string' ? options : options.path); };
mit