text
stringlengths
2
1.04M
meta
dict
#include <stdio.h> #include <string.h> /* * Forward declarations. */ static void processInput(FILE *stream, FILE *outstream); static int parseRule(char *line); static void generateCode(FILE *stream); static void generateHeader(FILE *stream); static void generateFooter(FILE *stream); int main(int argc, char *argv[]) { generateHeader(stdout); processInput(stdin, stdout); generateFooter(stdout); return 0; } /* * Read a single line from an input stream and handle continuations. */ static int readLine(char *buffer, FILE *stream) { int left = BUFSIZ; int len; while(fgets(buffer, left, stream)) { len = strlen(buffer); while(len > 0 && (buffer[len - 1] == '\n' || buffer[len - 1] == '\r')) { --len; } buffer[len] = '\0'; if(len > 0 && buffer[len - 1] == ':') { buffer += len; left -= len; } else if(len > 0 && buffer[len - 1] == '\\') { --len; buffer[len] = '\0'; buffer += len; left -= len; } else { return 1; } } return 0; } /* * Process input from a stream. */ static void processInput(FILE *stream, FILE *outstream) { char buffer[BUFSIZ]; while(readLine(buffer, stream)) { if(parseRule(buffer)) { generateCode(outstream); } } } /* * Determine if a string ends in a specific tail. */ static int endsIn(const char *str1, const char *str2) { int len1 = strlen(str1); int len2 = strlen(str2); if(len1 > len2 && !strncmp(str1 + len1 - len2, str2, len2)) { return 1; } else { return 0; } } /* * Parsed contents of a rule. */ static char *name; static char *parent; static char *contentType[16]; static char *contentName[16]; static int contentIsParams[16]; static int contentIsOptional[16]; static int specialConstructors; static int numContents; /* * Parse a rule line from an input stream. Rules look like this: * * CodeBinaryOperatorExpression: * CodeExpression<Left> CodeBinaryOperatorType<Operator> \ * CodeExpression<Right> */ static int parseRule(char *line) { int implicit; char *contents; /* Clear the rule information */ name = ""; parent = ""; numContents = 0; specialConstructors = 1; /* Skip leading white space */ while(*line != '\0' && (*line == ' ' || *line == '\t' || *line == '\r' || *line == '\n')) { ++line; } if(*line == '\0' || *line == '#') { /* Comment line */ return 0; } /* Extract the rule name */ name = line; while(*line != '\0' && *line != '-' && *line != ':') { ++line; } /* Extract the parent class, if it isn't implicit */ if(*line == '-') { *line++ = '\0'; parent = line; while(*line != '\0' && *line != ':') { ++line; } if(*line == ':') { *line++ = '\0'; } implicit = 0; } else if(*line == ':') { *line++ = '\0'; implicit = 1; } else { implicit = 1; } if(implicit) { if(endsIn(name, "Expression")) { parent = "CodeExpression"; } else if(endsIn(name, "Statement")) { parent = "CodeStatement"; } else if(endsIn(name, "Collection")) { parent = "CollectionBase"; } else { parent = "CodeObject"; } } /* Extract the contents of the rule */ while(*line != '\0') { if(*line == ' ' || *line == '\t' || *line == '\r' || *line == '\n') { *line++ = '\0'; } else { /* Extract the contents entry */ contents = line; while(*line != '\0' && *line != ' ' && *line != '\t' && *line != '\r' && *line != '\n') { ++line; } if(*line != '\0') { *line++ = '\0'; } /* Parse the entry into "type<name>" */ if(*contents == '$') { specialConstructors = 0; ++contents; } if(*contents == '?') { contentIsOptional[numContents] = 1; ++contents; } else { contentIsOptional[numContents] = 0; } if(*contents == '*') { contentIsParams[numContents] = 1; ++contents; } else if(*contents == '@') { contentIsParams[numContents] = 2; ++contents; } else { contentIsParams[numContents] = 0; } contentType[numContents] = contents; while(*contents != '\0' && *contents != '<') { ++contents; } if(*contents == '<') { *contents++ = '\0'; contentName[numContents] = contents; while(*contents != '\0' && *contents != '>') { ++contents; } *contents = '\0'; } else { contentName[numContents] = ""; } ++numContents; } } /* Done */ return 1; } /* * Generate code for a collection class. */ static void generateCollectionCode(FILE *stream) { char *member = contentType[0]; /* Output the constructors */ fprintf(stream, "\t// Constructors.\n"); fprintf(stream, "\tpublic %s()\n", name); fprintf(stream, "\t{\n\t}\n"); fprintf(stream, "\tpublic %s(%s[] value)\n", name, member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tAddRange(value);\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic %s(%s value)\n", name, name); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tAddRange(value);\n"); fprintf(stream, "\t}\n\n"); /* Output the properties */ fprintf(stream, "\t// Properties.\n"); fprintf(stream, "\tpublic %s this[int index]\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tget\n"); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\treturn (%s)(List[index]);\n", member); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t\tset\n"); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\tList[index] = value;\n"); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t}\n\n"); /* Output the methods */ fprintf(stream, "\t// Methods.\n"); fprintf(stream, "\tpublic int Add(%s value)\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\treturn List.Add(value);\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic void AddRange(%s[] value)\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tforeach(%s e in value)\n", member); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\tList.Add(e);\n"); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic void AddRange(%s value)\n", name); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tforeach(%s e in value)\n", member); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\tList.Add(e);\n"); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic bool Contains(%s value)\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\treturn List.Contains(value);\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic void CopyTo(%s[] array, int index)\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tList.CopyTo(array, index);\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic int IndexOf(%s value)\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\treturn List.IndexOf(value);\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic void Insert(int index, %s value)\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tList.Insert(index, value);\n"); fprintf(stream, "\t}\n"); fprintf(stream, "\tpublic void Remove(%s value)\n", member); fprintf(stream, "\t{\n"); fprintf(stream, "\t\tint index = List.IndexOf(value);\n"); fprintf(stream, "\t\tif(index < 0)\n"); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\tthrow new ArgumentException(S._(\"Arg_NotCollMember\"), \"value\");\n"); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t\tList.RemoveAt(index);\n"); fprintf(stream, "\t}\n\n"); /* Output the class footer */ fprintf(stream, "}; // class %s\n\n", name); } /* * Generate code for a specific constructor, if enabled. */ static void generateConstructor(FILE *stream, unsigned mask) { int posn; int needComma; /* Determine if this constructor is enabled */ for(posn = 0; posn < numContents; ++posn) { if(!(contentIsOptional[posn]) && (mask & (1 << posn)) == 0) { return; } } /* Generate the constructor */ fprintf(stream, "\tpublic %s(", name); needComma = 0; for(posn = 0; posn < numContents; ++posn) { if((mask & (1 << posn)) == 0) { continue; } if(needComma) { fputs(", ", stream); } if(contentIsParams[posn] == 1) { fprintf(stream, "params %s[] _%s", contentType[posn], contentName[posn]); } else if(contentIsParams[posn] == 2) { fprintf(stream, "%s[] _%s", contentType[posn], contentName[posn]); } else { fprintf(stream, "%s _%s", contentType[posn], contentName[posn]); } needComma = 1; } fprintf(stream, ")\n\t{\n"); for(posn = 0; posn < numContents; ++posn) { if((mask & (1 << posn)) == 0) { continue; } if(contentIsParams[posn]) { fprintf(stream, "\t\tthis.%s.AddRange(_%s);\n", contentName[posn], contentName[posn]); } else { fprintf(stream, "\t\tthis._%s = _%s;\n", contentName[posn], contentName[posn]); } } fprintf(stream, "\t}\n"); } /* * Generate code for a rule class. */ static void generateCode(FILE *stream) { int posn; unsigned mask, maxMask; /* Output the class header */ fprintf(stream, "[Serializable]\n"); fprintf(stream, "#if CONFIG_COM_INTEROP\n"); fprintf(stream, "[ClassInterface(ClassInterfaceType.AutoDispatch)]\n"); fprintf(stream, "[ComVisible(true)]\n"); fprintf(stream, "#endif\n"); fprintf(stream, "public class %s : %s\n", name, parent); fprintf(stream, "{\n"); fprintf(stream, "\n"); /* We need to use a different algorithm if this is a collection */ if(!strcmp(parent, "CollectionBase")) { generateCollectionCode(stream); return; } /* Output the instance fields */ if(numContents > 0) { fprintf(stream, "\t// Internal state.\n"); for(posn = 0; posn < numContents; ++posn) { if(contentIsParams[posn]) { fprintf(stream, "\tprivate %sCollection _%s;\n", contentType[posn], contentName[posn]); } else { fprintf(stream, "\tprivate %s _%s;\n", contentType[posn], contentName[posn]); } } fprintf(stream, "\n"); } /* Output the constructors */ fprintf(stream, "\t// Constructors.\n"); fprintf(stream, "\tpublic %s()\n", name); fprintf(stream, "\t{\n\t}\n"); if(numContents > 0 && specialConstructors) { maxMask = (unsigned)(1 << numContents); for(mask = 0; mask < maxMask; ++mask) { generateConstructor(stream, mask); } } fprintf(stream, "\n"); /* Output the property accessors */ if(numContents > 0) { fprintf(stream, "\t// Properties.\n"); for(posn = 0; posn < numContents; ++posn) { if(!specialConstructors && endsIn(contentType[posn], "Collection")) { fprintf(stream, "\tpublic %s %s\n", contentType[posn], contentName[posn]); fprintf(stream, "\t{\n\t\tget\n"); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\tif(_%s == null)\n", contentName[posn]); fprintf(stream, "\t\t\t{\n"); fprintf(stream, "\t\t\t\t_%s = new %s();\n", contentName[posn], contentType[posn]); fprintf(stream, "\t\t\t}\n"); fprintf(stream, "\t\t\treturn _%s;\n", contentName[posn]); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t}\n"); } else if(contentIsParams[posn]) { fprintf(stream, "\tpublic %sCollection %s\n", contentType[posn], contentName[posn]); fprintf(stream, "\t{\n\t\tget\n"); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\tif(_%s == null)\n", contentName[posn]); fprintf(stream, "\t\t\t{\n"); fprintf(stream, "\t\t\t\t_%s = new %sCollection();\n", contentName[posn], contentType[posn]); fprintf(stream, "\t\t\t}\n"); fprintf(stream, "\t\t\treturn _%s;\n", contentName[posn]); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t}\n"); } else { fprintf(stream, "\tpublic %s %s\n", contentType[posn], contentName[posn]); fprintf(stream, "\t{\n\t\tget\n"); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\treturn _%s;\n", contentName[posn]); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t\tset\n"); fprintf(stream, "\t\t{\n"); fprintf(stream, "\t\t\t_%s = value;\n", contentName[posn]); fprintf(stream, "\t\t}\n"); fprintf(stream, "\t}\n"); } } fprintf(stream, "\n"); } /* Output the class footer */ fprintf(stream, "}; // class %s\n\n", name); } /* * Standard copyright message to add to the front of the output. */ static char const COPYRIGHT_MSG[] = "/*\n" " * This file is generated from rules.txt using gencdom - do not edit.\n" " *\n" " * Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd.\n" " *\n" " * This program is free software; you can redistribute it and/or modify\n" " * it under the terms of the GNU General Public License as published by\n" " * the Free Software Foundation; either version 2 of the License, or\n" " * (at your option) any later version.\n" " *\n" " * This program is distributed in the hope that it will be useful,\n" " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " * GNU General Public License for more details.\n" " *\n" " * You should have received a copy of the GNU General Public License\n" " * along with this program; if not, write to the Free Software\n" " * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" " */\n\n"; /* * Generate the standard file header. */ static void generateHeader(FILE *stream) { fputs(COPYRIGHT_MSG, stream); fprintf(stream, "namespace System.CodeDom\n{\n"); fprintf(stream, "\n"); fprintf(stream, "#if CONFIG_CODEDOM\n"); fprintf(stream, "\n"); fprintf(stream, "using System.Runtime.InteropServices;\n"); fprintf(stream, "using System.Collections;\n"); fprintf(stream, "using System.Collections.Specialized;\n"); fprintf(stream, "\n"); } /* * Generate the standard file footer. */ static void generateFooter(FILE *stream) { fprintf(stream, "#endif // CONFIG_CODEDOM\n"); fprintf(stream, "\n"); fprintf(stream, "}; // namespace System.CodeDom\n"); }
{ "content_hash": "9515f1f6553d559f55838884197ad9ad", "timestamp": "", "source": "github", "line_count": 578, "max_line_length": 96, "avg_line_length": 23.941176470588236, "alnum_prop": 0.5974129209423327, "repo_name": "jjenki11/blaze-chem-rendering", "id": "f64cfaaa45205662233913cebbb709c441d2cb2a", "size": "14689", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "qca_designer/lib/pnetlib-0.8.0/System/CodeDom/gencdom.c", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "2476" } ], "symlink_target": "" }
from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/clothing/shared_clothing_armor_padded_bracer_l.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
{ "content_hash": "ab1933827bce142ec323e49d6d81da2f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 94, "avg_line_length": 24.846153846153847, "alnum_prop": 0.7027863777089783, "repo_name": "anhstudios/swganh", "id": "75e8648cae63f77b8d2e8a586c90cb0688c576a9", "size": "468", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "data/scripts/templates/object/draft_schematic/clothing/shared_clothing_armor_padded_bracer_l.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "11887" }, { "name": "C", "bytes": "7699" }, { "name": "C++", "bytes": "2357839" }, { "name": "CMake", "bytes": "41264" }, { "name": "PLSQL", "bytes": "42065" }, { "name": "Python", "bytes": "7503510" }, { "name": "SQLPL", "bytes": "42770" } ], "symlink_target": "" }
public class PokemonGame { public static void main(String[] args) { // Pokemon[] pokemon = new Pokemon[10]; Pokemon poke = new Pokemon(); poke = assignBaseStats(); System.out.println("Pokemon #0"); System.out.println("Species = " + poke.speciesName); System.out.println("Max HP = " + poke.maxHP); System.out.println("Current HP = " + poke.currentHP); System.out.println("Speed = " + poke.speed); System.out.println("Attack = " + poke.attack); System.out.println("Defense = " + poke.defense); } public static Pokemon assignBaseStats() { Pokemon pokemonassign = new Pokemon(); // if (type == "Charmander") { pokemonassign.speed = 10; pokemonassign.attack = Pokemon.Charmander.baseAttack; pokemonassign.defense = Pokemon.Charmander.baseDefense; pokemonassign.maxHP = Pokemon.Charmander.baseMaxHP; pokemonassign.speciesName = "Charmander"; pokemonassign.currentHP = pokemonassign.maxHP; // } return pokemonassign; } }
{ "content_hash": "c586d6052dd1f8ba54816bb57bf0c06d", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 59, "avg_line_length": 26.289473684210527, "alnum_prop": 0.6756756756756757, "repo_name": "edrak1/Pokemon-Text-Adventure", "id": "0ea59fe78077d4f24dffd4bbc3a45ac52bc3d8be", "size": "999", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PokemonGame.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1677" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: bezimienny * Date: 21.08.15 * Time: 13:55 */ namespace Acme\Bundle\EventManagerBundle\Model; use Doctrine\ORM\EntityManager; class ApiRequestHandler { private $entityManager; private $queryBuilder; public function __construct(EntityManager $entityManager) { $this->entityManager = $entityManager; $this->queryBuilder = $this->entityManager->createQueryBuilder(); } /** * @param string $searchTerm * @param int $limit * @param string $order * @return array */ public function searchForCountries($searchTerm, $limit, $order) { $query = $this->queryBuilder->select('country.name') ->from('AcmeEventManagerBundle:Country', 'country') ->where( $this->queryBuilder->expr() ->like('country.name', ':countryName') ) ->orderBy('country.name', $order) ->setParameter('countryName', '%' . $searchTerm . '%') ->setMaxResults($limit) ->getQuery(); $rawResults = $query->getArrayResult(); $results = array(); foreach ($rawResults as $country) { $results[] = $country['name']; } return $results; } /** * @param string $searchTerm * @param int $limit * @param string $order * @return array */ public function searchForFaculties($searchTerm, $limit, $order) { $query = $this->queryBuilder->select('faculty.name') ->from('AcmeEventManagerBundle:Faculty', 'faculty') ->where( $this->queryBuilder->expr() ->like('faculty.name', ':facultyName') ) ->orderBy('faculty.name', $order) ->setParameter('facultyName', '%' . $searchTerm . '%') ->setMaxResults($limit) ->getQuery(); $rawResults = $query->getArrayResult(); $results = array(); foreach ($rawResults as $faculty) { $results[] = $faculty['name']; } return $results; } /** * @param string $searchTerm * @param int $limit * @param string $order * @return array */ public function searchForUniversities($searchTerm, $limit, $order) { $query = $this->queryBuilder->select('university.name, university.address') ->from('AcmeEventManagerBundle:University', 'university') ->where( $this->queryBuilder->expr() ->like('university.name', ':universityName') ) ->orderBy('university.name', $order) ->setParameter('universityName', '%' . $searchTerm . '%') ->setMaxResults($limit) ->getQuery(); $rawResults = $query->execute(); $results = array(); foreach ($rawResults as $university) { $temporaryArray = array(); $temporaryArray['value'] = $university['name']; $temporaryArray['address'] = $university['address']; $results[] = $temporaryArray; } return $results; } }
{ "content_hash": "20f520d28216616d6a379faeb2898d7b", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 83, "avg_line_length": 28.419642857142858, "alnum_prop": 0.5366006911718505, "repo_name": "michalSolarz/EMW-Platform", "id": "02f8502687c420dc35aeb6a6a312e3b115d6fa2b", "size": "3183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Acme/Bundle/EventManagerBundle/Model/ApiRequestHandler.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3297" }, { "name": "HTML", "bytes": "70639" }, { "name": "JavaScript", "bytes": "6665" }, { "name": "PHP", "bytes": "239605" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <title>Uses of Class org.eclipse.emf.cdo.security.provider.UserItemProvider (CDO Model Repository Documentation)</title> <meta name="date" content=""> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.eclipse.emf.cdo.security.provider.UserItemProvider (CDO Model Repository Documentation)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/eclipse/emf/cdo/security/provider/UserItemProvider.html" title="class in org.eclipse.emf.cdo.security.provider">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/eclipse/emf/cdo/security/provider/class-use/UserItemProvider.html" target="_top">Frames</a></li> <li><a href="UserItemProvider.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.eclipse.emf.cdo.security.provider.UserItemProvider" class="title">Uses of Class<br>org.eclipse.emf.cdo.security.provider.UserItemProvider</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/eclipse/emf/cdo/security/provider/UserItemProvider.html" title="class in org.eclipse.emf.cdo.security.provider">UserItemProvider</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.eclipse.emf.cdo.security.provider">org.eclipse.emf.cdo.security.provider</a></td> <td class="colLast"> <div class="block">The generated EMF edit support of the CDO security model.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.eclipse.emf.cdo.security.provider"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/eclipse/emf/cdo/security/provider/UserItemProvider.html" title="class in org.eclipse.emf.cdo.security.provider">UserItemProvider</a> in <a href="../../../../../../../org/eclipse/emf/cdo/security/provider/package-summary.html">org.eclipse.emf.cdo.security.provider</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../../org/eclipse/emf/cdo/security/provider/package-summary.html">org.eclipse.emf.cdo.security.provider</a> declared as <a href="../../../../../../../org/eclipse/emf/cdo/security/provider/UserItemProvider.html" title="class in org.eclipse.emf.cdo.security.provider">UserItemProvider</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../../../org/eclipse/emf/cdo/security/provider/UserItemProvider.html" title="class in org.eclipse.emf.cdo.security.provider">UserItemProvider</a></code></td> <td class="colLast"><span class="typeNameLabel">SecurityItemProviderAdapterFactory.</span><code><span class="memberNameLink"><a href="../../../../../../../org/eclipse/emf/cdo/security/provider/SecurityItemProviderAdapterFactory.html#userItemProvider">userItemProvider</a></span></code> <div class="block">This keeps track of the one adapter used for all <a href="../../../../../../../org/eclipse/emf/cdo/security/User.html" title="interface in org.eclipse.emf.cdo.security"><code>User</code></a> instances</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/eclipse/emf/cdo/security/provider/UserItemProvider.html" title="class in org.eclipse.emf.cdo.security.provider">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/eclipse/emf/cdo/security/provider/class-use/UserItemProvider.html" target="_top">Frames</a></li> <li><a href="UserItemProvider.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><i>Copyright (c) 2011-2015 Eike Stepper (Berlin, Germany) and others.</i></small></p> </body> </html>
{ "content_hash": "dab53858c7d9c6bdc322878ed8436e08", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 386, "avg_line_length": 43.796407185628745, "alnum_prop": 0.6423297785069729, "repo_name": "kribe48/wasp-mbse", "id": "1a0ab374eda8ef72bd34748881102a4d22fd4c16", "size": "7314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WASP-turtlebot-DSL/.metadata/.plugins/org.eclipse.pde.core/Eclipse Application/org.eclipse.osgi/142/0/.cp/javadoc/org/eclipse/emf/cdo/security/provider/class-use/UserItemProvider.html", "mode": "33188", "license": "mit", "language": [ { "name": "CMake", "bytes": "6732" }, { "name": "CSS", "bytes": "179891" }, { "name": "GAP", "bytes": "163745" }, { "name": "HTML", "bytes": "1197667" }, { "name": "Java", "bytes": "1369191" }, { "name": "JavaScript", "bytes": "1555" }, { "name": "Python", "bytes": "11033" }, { "name": "Roff", "bytes": "303" }, { "name": "Xtend", "bytes": "13981" } ], "symlink_target": "" }
ο»Ώusing System; using System.Collections.Generic; using Backgammon.Framework.Constants; using Backgammon.Framework.Exceptions; using Backgammon.Framework.Interfaces; namespace Backgammon.Framework { public class Player : IPlayer { private static readonly Random Random = new Random(); private readonly IArrow _arrow; public Player(IBoard board, ConsoleColor colorOfCheckers) { ColorOfCheckers = colorOfCheckers; MovementOptions = Movement.RollDice; Dice = new[] {0, 0, 0, 0}; _arrow = new Arrow(board, this); } public ConsoleColor ColorOfCheckers { get; } public List<ConsoleKey> MovementOptions { get; set; } public int[] Dice { get; set; } public void Display() { var cursorLeft = Console.CursorLeft; var cursorTop = Console.CursorTop; DisplayMenuHeader(); if (MovementOptions == Movement.RollDice) { DisplayRollDiceMenu(); } else if (MovementOptions == Movement.SelectChecker) { DisplaySelectCheckerMenu(); _arrow.Display(); } else if (MovementOptions == Movement.MoveChecker) { DisplayMoveCheckerMenu(); _arrow.Display(); } else { throw new BackgammonException("BackgammonException: Invalid player movement cannot be displayed."); } DisplayDefaultMenu(); DisplayMenuFooter(); Console.SetCursorPosition(cursorLeft, cursorTop); } public ConsoleKey ReadCommand() { var command = Command.None; while (!MovementOptions.Contains(command)) { command = Console.ReadKey(true).Key; } return command; } public bool ExecuteCommand(ConsoleKey command) { var switchPlayer = false; switch (command) { case Command.UpArrow: if (MovementOptions == Movement.SelectChecker || MovementOptions == Movement.MoveChecker) { _arrow.MoveUp(); } else { throw new BackgammonException("BackgammonException: Invalid player movement. Cannot execute command."); } break; case Command.DownArrow: if (MovementOptions == Movement.SelectChecker || MovementOptions == Movement.MoveChecker) { _arrow.MoveDown(); } else { throw new BackgammonException("BackgammonException: Invalid player movement. Cannot execute command."); } break; case Command.LeftArrow: if (MovementOptions == Movement.SelectChecker || MovementOptions == Movement.MoveChecker) { _arrow.MoveLeft(); } else { throw new BackgammonException("BackgammonException: Invalid player movement. Cannot execute command."); } break; case Command.RightArrow: if (MovementOptions == Movement.SelectChecker || MovementOptions == Movement.MoveChecker) { _arrow.MoveRight(); } else { throw new BackgammonException("BackgammonException: Invalid player movement. Cannot execute command."); } break; case Command.Enter: if (MovementOptions == Movement.RollDice) { RollDice(); } else if (MovementOptions == Movement.SelectChecker) { _arrow.SelectChecker(); } else if (MovementOptions == Movement.MoveChecker) { switchPlayer = _arrow.MoveChecker(); } else { throw new BackgammonException("BackgammonException: Invalid player movement. Cannot execute command."); } break; case Command.Spacebar: if (MovementOptions == Movement.MoveChecker) { _arrow.ReleaseChecker(); } else { throw new BackgammonException("BackgammonException: Invalid player movement. Cannot execute command."); } break; case Command.Tab: if (MovementOptions != Movement.None) { PassTurn(); switchPlayer = true; } else { throw new BackgammonException("BackgammonException: Invalid player movement. Cannot execute command."); } break; default: throw new BackgammonException("BackgammonException: Invalid command cannot be executed."); } return switchPlayer; } private void DisplayMenuHeader() { Console.Write($"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"); Console.ForegroundColor = ColorOfCheckers; Console.WriteLine($" {ColorOfCheckers} Player {Environment.NewLine}"); Console.ForegroundColor = Color.Gray; DisplayDice(); Console.WriteLine(Environment.NewLine); Console.WriteLine("|β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”|"); Console.WriteLine("| |"); } private void DisplayDice() { if (Dice[0] == 0 && Dice[1] == 0) { Console.Write(" "); } else if (Dice[0] != 0 && Dice[1] == 0) { Console.Write(" Left Die: "); Console.ForegroundColor = Color.White; Console.Write(Dice[0]); Console.ForegroundColor = Color.Gray; Console.Write(" "); } else if (Dice[0] == 0 && Dice[1] != 0) { Console.Write(" Right Die: "); Console.ForegroundColor = Color.White; Console.Write(Dice[1]); Console.ForegroundColor = Color.Gray; Console.Write(" "); } else { Console.Write(" Left Die: "); Console.ForegroundColor = Color.White; Console.Write(Dice[0]); Console.ForegroundColor = Color.Gray; Console.Write(" "); Console.Write(" Right Die: "); Console.ForegroundColor = Color.White; Console.Write(Dice[1]); Console.ForegroundColor = Color.Gray; Console.Write(" "); } if (Dice[2] == 0 && Dice[3] == 0) { return; } var cursorLeft = Console.CursorLeft; var cursorTop = Console.CursorTop; if (Dice[2] != 0) { Console.SetCursorPosition(12, cursorTop); Console.Write("x2"); } if (Dice[3] != 0) { Console.SetCursorPosition(41, cursorTop); Console.Write("x2"); } Console.SetCursorPosition(cursorLeft, cursorTop); } private static void DisplayRollDiceMenu() { Console.Write("| Press <"); Console.ForegroundColor = Color.White; Console.Write("Enter"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> to roll the dice. |"); } private static void DisplaySelectCheckerMenu() { Console.Write("| Use the <"); Console.ForegroundColor = Color.White; Console.Write("Arrow"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> keys to navigate. |"); Console.Write("| Press <"); Console.ForegroundColor = Color.White; Console.Write("Enter"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> to select a checker. |"); } private static void DisplayMoveCheckerMenu() { Console.Write("| Use the <"); Console.ForegroundColor = Color.White; Console.Write("Arrow"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> keys to navigate. |"); Console.Write("| Press <"); Console.ForegroundColor = Color.White; Console.Write("Enter"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> to move the checker. |"); Console.Write("| Press <"); Console.ForegroundColor = Color.White; Console.Write("Spacebar"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> to release the checker. |"); } private void DisplayDefaultMenu() { if (MovementOptions != Movement.None) { Console.Write("| Press <"); Console.ForegroundColor = Color.White; Console.Write("Tab"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> to pass your turn. |"); } Console.Write("| Press <"); Console.ForegroundColor = Color.White; Console.Write("Escape"); Console.ForegroundColor = Color.Gray; Console.WriteLine("> to quit the game. |"); } private static void DisplayMenuFooter() { Console.WriteLine("| |"); Console.WriteLine("|β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”|"); for (var i = 0; i < 2; ++i) { Console.WriteLine(" "); } } private void RollDice() { Dice[0] = Random.Next(1, 7); Dice[1] = Random.Next(1, 7); if (Dice[0] == Dice[1]) { Dice[2] = Dice[0]; Dice[3] = Dice[1]; } MovementOptions = Movement.SelectChecker; } private void PassTurn() { if (MovementOptions == Movement.MoveChecker) { _arrow.ReleaseChecker(); } Dice = new[] {0, 0, 0, 0}; MovementOptions = Movement.RollDice; _arrow.Display(); } } }
{ "content_hash": "2855790529b633a33ff7e6d3e3d88721", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 127, "avg_line_length": 38.31089743589744, "alnum_prop": 0.44206475361833847, "repo_name": "Arjestin/code-value-course", "id": "828c8e5e293674fd3da76d83f9ca9c5e1d5c5a72", "size": "12123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Backgammon.Ver1/Backgammon.Framework/Player.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "179102" } ], "symlink_target": "" }
module Main ( main -- main-function ) where -- imports -- import Control.Monad import Control.Exception import Database.HDBC import Database.HDBC.PostgreSQL import Data.List.Split import Data.Char -- functions -- main :: IO () -- http://book.realworldhaskell.org/read/using-databases.html -- could be added -- readCSV :: String -> [[String]] main = handleSqlError $ do conn <- connectPostgreSQL "host=localhost dbname=bundesliga5 user=finn password=root" -- IMPORT LIGA putStrLn "IMPORT LIGA"; contents <- readFile "/home/vagrant/dbs/bundesliga-data/bundesliga_Liga.csv"; let rows = drop 1 $ lines contents; let output = map (splitOn ";") rows forM_ output $ \line -> do -- fields let league_number = read (line!!0) :: Int; run conn "INSERT INTO bundesliga.league (league_number) VALUES (?);" [iToSql league_number] putStrLn $ show $ league_number; return(); -- IMPORT CLUB putStrLn "IMPORT CLUB" contents <- readFile "/home/vagrant/dbs/bundesliga-data/bundesliga_Verein.csv"; let rows = drop 1 $ lines contents; let output = map (splitOn ";") rows forM_ output $ \line -> do -- fields let vID = read (line!!0) :: Int; let name = (line!!1); let liga = read (line!!2) :: Int; run conn "INSERT INTO bundesliga.club (club_id, club_name, league_number) VALUES (?, ?, ?);" [iToSql vID, toSql name, toSql liga] putStrLn $ show $ name; return(); -- IMPORT GAME putStrLn "IMPORT GAME" contents <- readFile "/home/vagrant/dbs/bundesliga-data/bundesliga_Spiel.csv"; let rows = drop 1 $ lines contents; let output = map (splitOn ";") rows forM_ output $ \line -> do -- fields let spielID = read (line!!0) :: Int; let datum = (line!!2); let uhrzeit = (line!!3); let heim = read(line!!4) :: Int; let gast = read(line!!5) :: Int; let toreHeim = read(line!!6) :: Int; let toreGast = read(line!!7) :: Int; run conn "INSERT INTO bundesliga.game (game_id, \"date\", \"begin\", home, guest, home_score, guest_score) VALUES (?, ?, ?, ?, ?, ?, ?);" [iToSql spielID, toSql datum, toSql uhrzeit, iToSql heim, iToSql gast, iToSql toreHeim, iToSql toreGast] putStrLn $ show $ spielID; return(); -- IMPORT PLAYER putStrLn "IMPORT PLAYER" contents <- readFile "/home/vagrant/dbs/bundesliga-data/bundesliga_Spieler.csv"; let rows = drop 1 $ lines contents; let output = map (splitOn ";") rows forM_ output $ \line -> do -- fields let spielerID = read (line!!0) :: Int; let vereinsID = read (line!!1) :: Int; let trikotNr = read (line!!2) :: Int; let spielerName = (line!!3); let land = (line!!4); let spiele = read (line!!5) :: Int; let tore = read (line!!6) :: Int; let vorlagen = read (line!!7) :: Int; run conn "INSERT INTO bundesliga.player(\"id\", \"number\", \"nationality\", \"goals\", \"club_id\") VALUES (?, ?, ?, ?, ?);" [iToSql spielerID, iToSql trikotNr, toSql land, iToSql tore, iToSql vereinsID] putStrLn $ show $ spielerName; return(); rows <- quickQuery' conn "SELECT * FROM bundesliga.player;" [] -- do a query forM_ rows $ \row -> putStrLn $ show row; -- print the query; forM_ :: Monad m => [a] -> (a -> m b) -> m () disconnect conn;
{ "content_hash": "7987407390e35facde276f608f442a94", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 154, "avg_line_length": 42.83157894736842, "alnum_prop": 0.5023347259768985, "repo_name": "finnp/HaskellDatabaseImportExample", "id": "26918140b3dc2caeca36590ae6787fe559579562", "size": "4069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Main.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "4069" } ], "symlink_target": "" }
require 'test_helper' class CaptchaTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end
{ "content_hash": "df86c2e176ade36e78c34c1843a57461", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 43, "avg_line_length": 19.25, "alnum_prop": 0.7272727272727273, "repo_name": "ajahongir/captcha", "id": "6028d9838c387a2ba6a77af571f6b380148338bf", "size": "154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/captcha_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "5856" } ], "symlink_target": "" }
package com.app.aparoksha.apro16; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import DBManager.DBFavs; /** * Created by Satyam Poddar on 16-Feb-16. */ public class Eventlist_SplitSecond extends AppCompatActivity implements View.OnClickListener{ private Toolbar toolbar; private CollapsingToolbarLayout collapsingToolbar; private LinearLayout desc,rules,prize,org; private ImageView bdesc,brules,bprize,borg,bfav; private SharedPreferences sharedpreferences; private String PREF_FILE_NAME = "APRO"; private String FAVSTATUS = "spl"; private String intentNaam; final static private String EVENT_NAME = "Split Second"; private TextView num1; private LinearLayout org1; private TextView num2; private LinearLayout org2; private TextView num3; private LinearLayout org3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.event_splitsecond); toolbar = (Toolbar) findViewById(R.id.anim_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbar.setTitle("Split Second"); desc = (LinearLayout)findViewById(R.id.desc); rules = (LinearLayout)findViewById(R.id.rules); prize = (LinearLayout)findViewById(R.id.prize); org = (LinearLayout)findViewById(R.id.org); desc.setVisibility(View.VISIBLE); bdesc = (ImageView)findViewById(R.id.bdesc); brules = (ImageView)findViewById(R.id.brules); bprize = (ImageView)findViewById(R.id.bprize); borg = (ImageView)findViewById(R.id.borg); bfav = (ImageView)findViewById(R.id.bfav); bdesc.setOnClickListener(this); brules.setOnClickListener(this); bprize.setOnClickListener(this); borg.setOnClickListener(this); bfav.setOnClickListener(this); num1 = (TextView) findViewById(R.id.num1); org1 = (LinearLayout) findViewById(R.id.organiser1); org1.setOnClickListener(this); num2 = (TextView) findViewById(R.id.number2); org2 = (LinearLayout) findViewById(R.id.organiser2); org2.setOnClickListener(this); num3 = (TextView) findViewById(R.id.num3); org3 = (LinearLayout) findViewById(R.id.organiser3); org3.setOnClickListener(this); // Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); // Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); Intent intent = getIntent(); intentNaam = intent.getStringExtra("INTENT"); // String name = intent.getStringExtra("name"); if (getFav().equals("1")) { //fav is set bfav.setImageResource(R.drawable.book2); } else { //fav is not set bfav.setImageResource(R.drawable.book1); } } public void setFav(String fav) { sharedpreferences = getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(FAVSTATUS, fav); editor.commit(); } public String getFav() { sharedpreferences = getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE); if (sharedpreferences.contains(FAVSTATUS)) { return sharedpreferences.getString(FAVSTATUS, ""); } return ""; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.bdesc : desc.setVisibility(View.VISIBLE); rules.setVisibility(View.INVISIBLE); prize.setVisibility(View.INVISIBLE); org.setVisibility(View.INVISIBLE); break; case R.id.brules : desc.setVisibility(View.INVISIBLE); rules.setVisibility(View.VISIBLE); prize.setVisibility(View.INVISIBLE); org.setVisibility(View.INVISIBLE); break; case R.id.bprize : desc.setVisibility(View.INVISIBLE); rules.setVisibility(View.INVISIBLE); prize.setVisibility(View.VISIBLE); org.setVisibility(View.INVISIBLE); break; case R.id.borg : desc.setVisibility(View.INVISIBLE); rules.setVisibility(View.INVISIBLE); prize.setVisibility(View.INVISIBLE); org.setVisibility(View.VISIBLE); break; case R.id.bfav : if(getFav().equals("1")) { //fav is set setFav("0"); DBFavs entryDel = new DBFavs(this); entryDel.openandwrite(); entryDel.deleteTitleGivenName(EVENT_NAME); entryDel.close(); bfav.setImageResource(R.drawable.book1); Toast.makeText(this, "Removed from Favorites", Toast.LENGTH_SHORT).show(); //delete db entry } else { //fav is not set setFav("1"); bfav.setImageResource(R.drawable.book2); DBFavs entry = new DBFavs(this); entry.openandwrite(); entry.createEntry(EVENT_NAME, intentNaam); entry.close(); Toast.makeText(this, "Added to Favorites", Toast.LENGTH_SHORT).show(); //create db entry } break; case R.id.organiser1: String number1 = num1.getText().toString().trim(); Intent callIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:+91"+number1)); //startActivity(callIntent); /* Intent callIntent2 = new Intent(Intent.ACTION_CALL); callIntent2.setData(Uri.parse("tel:+91" + number1));*/ if (!hasPermission("android.permission.CALL_PHONE")) { Toast.makeText(this, "Grant permission for Calling", Toast.LENGTH_SHORT).show(); return; } else { startActivity(callIntent); } /* String to = eid1.getText().toString(); String subject="Regarding " + EVENT_NAME +"!"; Intent email1 = new Intent(Intent.ACTION_SEND); email1.putExtra(Intent.EXTRA_EMAIL, to); email1.putExtra(Intent.EXTRA_SUBJECT, subject); //need this to prompts email client only email1.setType("text/plain"); startActivity(Intent.createChooser(email1, "Choose an Email client :"));*/ break; case R.id.organiser2: String number2 = num2.getText().toString().trim(); Intent callIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:+91"+number2)); /* startActivity(callIntent); Intent callIntent22 = new Intent(Intent.ACTION_CALL); callIntent22.setData(Uri.parse("tel:+91" + number2));*/ if (!hasPermission("android.permission.CALL_PHONE")) { Toast.makeText(this, "Grant permission for Calling", Toast.LENGTH_SHORT).show(); return; } else { startActivity(callIntent2); } break; case R.id.organiser3: String number3 = num3.getText().toString().trim(); Intent callIntent3 = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:+91"+number3)); /* startActivity(callIntent); Intent callIntent22 = new Intent(Intent.ACTION_CALL); callIntent22.setData(Uri.parse("tel:+91" + number2));*/ if (!hasPermission("android.permission.CALL_PHONE")) { Toast.makeText(this, "Grant permission for Calling", Toast.LENGTH_SHORT).show(); return; } else { startActivity(callIntent3); } break; } } public boolean hasPermission(String permission) { try { PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), PackageManager.GET_PERMISSIONS); if (info.requestedPermissions != null) { for (String p : info.requestedPermissions) { if (p.equals(permission)) { return true; } } } } catch (Exception e) { e.printStackTrace(); } return false; } // new addition @Override public boolean dispatchTouchEvent(MotionEvent ev) { try { return super.dispatchTouchEvent(ev); } catch (Exception e) { return false; } } //end @Override protected void onDestroy() { super.onDestroy(); } }
{ "content_hash": "115775a564892aa58ea154c29c09a1e2", "timestamp": "", "source": "github", "line_count": 276, "max_line_length": 121, "avg_line_length": 36.55434782608695, "alnum_prop": 0.5823173753593022, "repo_name": "Aparoksha/App_2016", "id": "59e96d16cfb1173457043fd81988bc845dfe0c59", "size": "10089", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/app/aparoksha/apro16/Eventlist_SplitSecond.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "873642" }, { "name": "Python", "bytes": "444" } ], "symlink_target": "" }
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace AlexaTVInfoSkill.Areas.HelpPage.ModelDescriptions { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
{ "content_hash": "49417483c36b0fba0e62f7b46691a742", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 140, "avg_line_length": 40.138888888888886, "alnum_prop": 0.6373702422145329, "repo_name": "kmcoulson/AlexaTvInfoSkill", "id": "6d22b7969ba3ddc4229e635cf29844aad1211046", "size": "1445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AlexaTVInfoSkill/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "110" }, { "name": "C#", "bytes": "270773" }, { "name": "CSS", "bytes": "3264" }, { "name": "HTML", "bytes": "5069" }, { "name": "JavaScript", "bytes": "10926" } ], "symlink_target": "" }
var config = require("./config/config"); var mongoose = require("./config/mongoose"); var express = require("./config/express"); var passport = require("./config/passport"); process.env.NODE_ENV = process.env.NODE_ENV || "development"; process.env.JWT_SECRET = config.jwtToken; var db = mongoose(); var app = express(); var passport = passport(); app.listen(config.port); module.exports = app; console.log(process.env.NODE_ENV + " server running at http://localhost:" + config.port);
{ "content_hash": "5906474680b6c379f370e3aac1402d59", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 89, "avg_line_length": 28.764705882352942, "alnum_prop": 0.7055214723926381, "repo_name": "sbishop411/PersonalWebsite", "id": "0f9ec9d65e284bccf76e5950cdc70b84ee01bca3", "size": "489", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "37828" }, { "name": "JavaScript", "bytes": "36012" }, { "name": "PostScript", "bytes": "333419" } ], "symlink_target": "" }
<?php /* TwigBundle:Exception:traces_text.html.twig */ class __TwigTemplate_248997e9c28bf086d726379adfab14642a3e1ade750b4d95b05c5eea03b142f7 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<div class=\"block\"> <h2> Stack Trace (Plain Text)&nbsp; "; // line 4 ob_start(); // line 5 echo " <a href=\"#\" onclick=\"toggle('traces-text'); switchIcons('icon-traces-text-open', 'icon-traces-text-close'); return false;\"> <img class=\"toggle\" id=\"icon-traces-text-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: none\" /> <img class=\"toggle\" id=\"icon-traces-text-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: inline\" /> </a> "; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); // line 10 echo " </h2> <div id=\"traces-text\" class=\"trace\" style=\"display: none;\"> <pre>"; // line 13 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "toarray", array())); foreach ($context['_seq'] as $context["i"] => $context["e"]) { // line 14 echo "["; echo twig_escape_filter($this->env, ($context["i"] + 1), "html", null, true); echo "] "; echo twig_escape_filter($this->env, $this->getAttribute($context["e"], "class", array()), "html", null, true); echo ": "; echo twig_escape_filter($this->env, $this->getAttribute($context["e"], "message", array()), "html", null, true); echo " "; // line 15 $this->env->loadTemplate("TwigBundle:Exception:traces.txt.twig")->display(array("exception" => $context["e"])); } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['i'], $context['e'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 16 echo "</pre> </div> </div> "; } public function getTemplateName() { return "TwigBundle:Exception:traces_text.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 57 => 16, 51 => 15, 42 => 14, 38 => 13, 33 => 10, 26 => 5, 24 => 4, 19 => 1,); } }
{ "content_hash": "37448bc88493b3d19b3452872bdd59e1", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 416, "avg_line_length": 43.506493506493506, "alnum_prop": 0.6011940298507462, "repo_name": "Mohamedwertani/projetSymfony2", "id": "a6e31bbedaece5d107810b4634889e49048400c3", "size": "3350", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/cache/dev/twig/24/89/97e9c28bf086d726379adfab14642a3e1ade750b4d95b05c5eea03b142f7.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "109701" }, { "name": "HTML", "bytes": "167464" }, { "name": "JavaScript", "bytes": "8975" }, { "name": "PHP", "bytes": "189746" }, { "name": "Shell", "bytes": "1014" } ], "symlink_target": "" }
package com.linxcool.wechoice.data.entity; import java.io.Serializable; /** * Created by linxcool on 17/4/8. */ public class VideoItem { private String topicSid; private String replyid; private String vid; private String title; private String sectiontitle; private String topicName; private String topicImg; private Topic videoTopic; private String videosource; private String topicDesc; private String cover; private int playCount; private String replyBoard; private String description; private int length; private int playersize; private String ptime; private String mp4_url; private String mp4Hd_url; private String m3u8Hd_url; private String m3u8_url; class Topic implements Serializable { private String alias; private String tname; private String ename; private String tid; private String topic_icons; } public String getTitle() { return title; } public String getDescription() { return description; } public String getMp4_url() { return mp4_url; } public String getCover() { return cover; } public String getTopicImg() { return topicImg; } public String getTopicName() { return topicName; } public String getPtime() { return ptime; } }
{ "content_hash": "2e2a77de8bd5c6e07fbeb80c2f2f1757", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 42, "avg_line_length": 19.013513513513512, "alnum_prop": 0.642501776830135, "repo_name": "linxcool/wechoice", "id": "2d9c9a2321e0a0a09b35d862b7560b0965d25b7c", "size": "1407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/linxcool/wechoice/data/entity/VideoItem.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "425866" } ], "symlink_target": "" }
/******************* * text_ellipsis.h * *******************/ /**************************************************************************** * Written By Marcio Teixeira 2020 - SynDaver Labs, Inc. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 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. * * * * To view a copy of the GNU General Public License, go to the following * * location: <https://www.gnu.org/licenses/>. * ****************************************************************************/ #pragma once /** * This function draws text inside a bounding box, truncating the text and * showing ellipsis if it does not fit. */ namespace FTDI { void draw_text_with_ellipsis(class CommandProcessor& cmd, int x, int y, int w, int h, progmem_str str, uint16_t options = 0, uint8_t font = 31); void draw_text_with_ellipsis(class CommandProcessor& cmd, int x, int y, int w, int h, const char *str, uint16_t options = 0, uint8_t font = 31); }
{ "content_hash": "af0bb8fda13cd2188775cd4412888d53", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 146, "avg_line_length": 56.935483870967744, "alnum_prop": 0.4764872521246459, "repo_name": "limtbk/3dprinting", "id": "a2d8aa94439163c8021597f33d694913dcba5a92", "size": "1765", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Firmware/src/Marlin/src/lcd/extui/ftdi_eve_touch_ui/ftdi_eve_lib/extended/text_ellipsis.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "16427042" }, { "name": "C++", "bytes": "1508812" }, { "name": "Makefile", "bytes": "58317" }, { "name": "Objective-C", "bytes": "195319" }, { "name": "Processing", "bytes": "407203" }, { "name": "Python", "bytes": "11892" }, { "name": "Scilab", "bytes": "10211" } ], "symlink_target": "" }
import os import re import sqlite3 from collections import defaultdict from enum import Enum from flask import abort, Flask, g, redirect, render_template, request, session, url_for from flask.ext.sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash import settings as SETTINGS app = Flask(__name__) app.config.from_object(__name__) app.config.update(dict( SQLALCHEMY_DATABASE_URI='sqlite:///db/sofa.db', DEBUG=True, USERNAME=SETTINGS.DB_USERNAME, PASSWORD=SETTINGS.DB_PASSWORD, SECRET_KEY=SETTINGS.SECRET_KEY )) class Status(Enum): NONE = 0 WAITING = 1 WATCHING = 2 PAUSED = 4 STOPPED = 8 db = SQLAlchemy(app) class Show(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.String(255), unique=True) title = db.Column(db.String(255), unique=True) season_count = db.Column(db.Integer) description = db.Column(db.Text) episodes = db.relationship('Episode', backref='show', cascade='all, delete-orphan', lazy='dynamic') def __init__(self, title, season_count, description): self.public_id = get_public_id(title) self.title = title self.season_count = season_count self.description = description def __repr__(self): return '<Show %r>' % self.title class Episode(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.String(255)) title = db.Column(db.String(255)) season = db.Column(db.Integer) number = db.Column(db.Integer) description = db.Column(db.Text) show_id = db.Column(db.Integer, db.ForeignKey('show.id')) def __init__(self, title, season, number, description, show_id): self.public_id = get_public_id(title) self.title = title self.season = season self.number = number self.description = description self.show_id = show_id def __repr__(self): return '<Episode %r>' % self.title class Progress(db.Model): id = db.Column(db.Integer, primary_key=True) show_id = db.Column(db.Integer, db.ForeignKey('show.id')) episode_id = db.Column(db.Integer, db.ForeignKey('episode.id')) status = db.Column(db.Integer) def __init__(self, show_id, episode_id, status): self.show_id = show_id self.episode_id = episode_id self.status = status @property def show(self): return Show.query.filter_by(id=self.show_id).first() @property def episode(self): return Episode.query.filter_by(id=self.episode_id).first() def __repr__(self): return '<Progress %r>' % self.id class User(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) username = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) first_name = db.Column(db.String(255)) last_name = db.Column(db.String(255)) permissions = db.Column(db.Integer) watching = db.relationship('Progress', backref='progress', secondary='watching', lazy='dynamic') favorites = db.relationship('Show', backref='show', secondary='favorites', lazy='dynamic') def __init__(self, email, username, password, first_name, last_name): self.email = email self.username = username self.password = generate_password_hash(password) self.first_name = first_name self.last_name = last_name self.permissions = 0 def get_watching(self): return [progress for progress in self.watching] def add_watching(self, progress): self.watching.append(progress) def get_favorites(self): return [show for show in self.favorites] def add_favorite(self, show): self.favorites.append(show) def remove_favorite(self, show): self.favorites.remove(show) def __repr__(self): return '<User %r>' % self.username watching = db.Table('watching', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('progress_id', db.Integer, db.ForeignKey('progress.id')) ) favorites = db.Table('favorites', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('show_id', db.Integer, db.ForeignKey('show.id')) ) def get_public_id(title): public_id = re.sub(r'\s', '-', title) public_id = re.sub(r'[^A-Za-z0-9\-]', '', public_id) public_id = re.sub(r'--', '-', public_id) return public_id.lower() @app.route('/') def index(): return render_template('index.html') @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.route('/search', methods=['GET', 'POST']) def search(): if request.method == 'GET': return redirect(url_for('index')) search = request.form['search'] q = '%' + search + '%' results = dict( shows=Show.query.filter(Show.title.like(q)).all(), episodes=Episode.query.filter(Episode.title.like(q)).all(), users=User.query.filter(User.username.like(q)).all() ) print results #dev return render_template('search-results.html', search=search, results=results) @app.route('/shows') def shows(): shows = Show.query.all() return render_template('shows.html', shows=shows) @app.route('/shows/<show_id>') def show_details(show_id): user = User.query.filter_by(username=session.get('username')).first() show = Show.query.filter_by(public_id=show_id).first() episodes = Episode.query.filter_by(show_id=show.id).all() if user: watching = any(show.id == progress.id for progress in user.get_watching()) favorited = any(show_id == show.public_id for show in user.get_favorites()) else: watching = False favorited = False seasons = defaultdict(list) for episode in episodes: seasons[episode.season].append(episode) return render_template('show-details.html', show=show, seasons=seasons, watching=watching, favorited=favorited) @app.route('/shows/<show_id>/start') def show_start(show_id): if session.get('username'): user = User.query.filter_by(username=session.get('username')).first() show = Show.query.filter_by(public_id=show_id).first() episode = Episode.query.filter_by(season=1).filter_by(number=1).first() watching = any(show.id == progress.show_id for progress in user.get_watching()) if not watching: progress = Progress( show.id, episode.id, Status.WATCHING.value ) db.session.add(progress) user.add_watching(progress) db.session.commit() return redirect(url_for('show_details', show_id=show_id)) @app.route('/shows/<show_id>/pause') def show_pause(show_id): if session.get('username'): user = User.query.filter_by(username=session.get('username')).first() show = Show.query.filter_by(public_id=show_id).first() watching = any(show.id == progress.show_id for progress in user.get_watching()) if watching: progress = Progress.query.filter_by(show_id=show.id).first() progress.status = Status.PAUSED.value db.session.commit() return redirect(url_for('show_details', show_id=show_id)) @app.route('/shows/<show_id>/resume') def show_resume(show_id): pass @app.route('/shows/<show_id>/stop') def show_stop(show_id): pass @app.route('/shows/<show_id>/favorite') def show_favorite(show_id): if session.get('username'): user = User.query.filter_by(username=session.get('username')).first() show = Show.query.filter_by(public_id=show_id).first() favorited = any(show_id == show.public_id for show in user.get_favorites()) if not favorited: user.add_favorite(show) db.session.commit() return redirect(url_for('show_details', show_id=show_id)) @app.route('/shows/<show_id>/unfavorite') def show_unfavorite(show_id): if session.get('username'): user = User.query.filter_by(username=session.get('username')).first() show = Show.query.filter_by(public_id=show_id).first() favorited = any(show_id == show.public_id for show in user.get_favorites()) if favorited: user.remove_favorite(show) db.session.commit() return redirect(url_for('show_details', show_id=show_id)) @app.route('/shows/add', methods=['GET', 'POST']) def show_add(): if request.method == 'POST': show = Show( request.form['title'], request.form['seasons'], request.form['description'] ) db.session.add(show) db.session.commit() return redirect(url_for('shows')) return render_template('show-add.html') @app.route('/shows/<show_id>/edit', methods=['GET', 'POST']) def show_edit(show_id): pass @app.route('/shows/<show_id>/delete') def show_delete(show_id): show = Show.query.filter_by(public_id=show_id).first() db.session.delete(show) db.session.commit() return redirect(url_for('shows')) @app.route('/shows/<show_id>/episodes/<episode_id>') def episode_details(show_id, episode_id): pass @app.route('/shows/<show_id>/episodes/add', methods=['GET', 'POST']) def episode_add(show_id): show = Show.query.filter_by(public_id=show_id).first() if request.method == 'POST': episode = Episode( request.form['title'], request.form['season'], request.form['number'], request.form['description'], show.id ) db.session.add(episode) db.session.commit() return redirect(url_for('show_details', show_id=show_id)) return render_template('episode-add.html') @app.route('/shows/<show_id>/episodes/<episode_id>/edit') def episode_edit(show_id, episode_id): pass @app.route('/shows/<show_id>/episodes/<episode_id>/delete') def episode_delete(show_id, episode_id): pass @app.route('/users') def users(): users = User.query.all() return render_template('users.html', users=users) @app.route('/users/<username>') def user_details(username): user = User.query.filter_by(username=username).first() return render_template('user-details.html', user=user) @app.route('/users/<username>/settings') def user_settings(username): if session.get('username') != username: return redirect(url_for('user_details', username=username)) return render_template('user-settings.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': user = User.query.filter_by(username=request.form['username']).first() if check_password_hash(user.password, request.form['password']): session['username'] = user.username return redirect(url_for('index')) else: return redirect(url_for('login')) return render_template('login.html') @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index')) @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': user = User( request.form['email'], request.form['username'], request.form['password'], request.form['first_name'], request.form['last_name'] ) db.session.add(user) db.session.commit() return redirect(url_for('index')) return render_template('register.html') if __name__ == '__main__': app.run()
{ "content_hash": "176263c37a2b518485471ad11f57ef76", "timestamp": "", "source": "github", "line_count": 387, "max_line_length": 115, "avg_line_length": 30.03875968992248, "alnum_prop": 0.6307956989247312, "repo_name": "maxdeviant/sofa", "id": "87a128e3cce7268758299b48dcd904849bec9642", "size": "11625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1173" }, { "name": "Python", "bytes": "11660" } ], "symlink_target": "" }
@CHARSET "UTF-8"; .outBg { background: url(images/outBg.gif) repeat scroll 0 0 transparent; } .inBg { background: url(images/inBg.gif) repeat scroll 0 0 transparent; } .headTopic { background: url(images/banner.jpg) repeat scroll 0 0 transparent; height: 200px; } .topbaner { background: none repeat scroll 0 0 #ccc; } .headerMenuBg { background: url(images/navBg.gif) scroll 0 0 transparent; } .headerMenuBorder { border-style: solid; border-width: 0px 0px 0; height: 34px; } .headerMenuList a { color: #red; } .headerMenuLiCheck { border-color: #5e4e3a; border-style: none; } .headerMenuLiCheckBg{ background: url(images/navBg.gif) scroll 0 0 transparent; } .headerMenuLiCheck a { color: #fff; } .headerMenuBottom { border-bottom-color: #FFFFFF; } .bodyCont { background: url(images/bodyCont.gif) repeat-x scroll 0 0 #d6d6d3; border-color: #d6d6d3; border-style: solid; background-color: #d6d6d3; } .bodyContTitle { background: url(images/titleBg.gif) repeat scroll 0 0; background-color: #51ae00; } .bodyContTitle .titleLinkColor { color: #ffffff; }
{ "content_hash": "566b63a84883176677a8432065795bdc", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 66, "avg_line_length": 16.984375, "alnum_prop": 0.7203311867525299, "repo_name": "baowp/platform", "id": "a863a8401625666c1e4989d2d8d5fee8283abbbc", "size": "1087", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bundle/src/main/webapp/group/dynamic/theme/bridge/theme.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "313319" }, { "name": "CSS", "bytes": "1567456" }, { "name": "Groovy", "bytes": "16703" }, { "name": "Java", "bytes": "2369547" }, { "name": "JavaScript", "bytes": "5755060" }, { "name": "PHP", "bytes": "65173" } ], "symlink_target": "" }
package com.francetelecom.clara.cloud.presentation.utils; import org.apache.wicket.util.tester.FormTester; import org.junit.Assert; /** * Created by IntelliJ IDEA. * User: wwnl9733 * Date: 02/02/12 * Time: 11:24 * To change this template use File | Settings | File Templates. */ public class DeleteEditObjects { public static void deleteAssociationAtCell(PaasWicketTester myTester, int row, int col) { String path = NavigationUtils.getPathForCell(row, col) + ":form"; Assert.assertTrue(isCellAssociated(myTester, row, col)); FormTester cellForm = myTester.newFormTester(path); cellForm.setValue("associated", false); myTester.executeAjaxEvent(path + ":associated", "onclick"); Assert.assertFalse(isCellAssociated(myTester, row, col)); } public static void deleteServiceAtRow(PaasWicketTester myTester, int row) { String path = NavigationUtils.getPathForCell(row, 0) + ":cell-delete"; myTester.executeAjaxEvent(path, "onclick"); } public static void deleteNodeAtCol(PaasWicketTester myTester, int col) { String path = NavigationUtils.getPathForCell(0, col) + ":cell-delete"; myTester.executeAjaxEvent(path, "onclick"); } public static void editServiceAtRow(PaasWicketTester myTester, int row) { String path = NavigationUtils.getPathForCell(row, 0) + ":cell-edit"; myTester.executeAjaxEvent(path, "onclick"); } public static void modifyServiceLabelAtRow(PaasWicketTester myTester, int row) throws NoSuchFieldException { String servicePath = NavigationUtils.designerParamFormPath; FormTester serviceForm = NavigationUtils.getParamsFormTester(myTester); String labelValue = serviceForm.getTextComponentValue("label"); serviceForm.setValue("label", labelValue+row); myTester.executeAjaxEvent(servicePath+":addUpdateButton", "onclick"); } public static void editNodeAtCol(PaasWicketTester myTester, int col) { String path = NavigationUtils.getPathForCell(0, col) + ":cell-edit"; myTester.executeAjaxEvent(path, "onclick"); } public static void viewServiceAtRow(PaasWicketTester myTester, int row) { String path = NavigationUtils.getPathForCell(row, 0) + ":cell-view"; myTester.executeAjaxEvent(path, "onclick"); } public static void viewNodeAtCol(PaasWicketTester myTester, int col) { String path = NavigationUtils.getPathForCell(0, col) + ":cell-view"; myTester.executeAjaxEvent(path, "onclick"); } public static boolean isCellAssociated(PaasWicketTester myTester, int row, int col) { String path = NavigationUtils.getPathForCell(row, col) + ":form"; return (Boolean) myTester.getComponentFromLastRenderedPage(path + ":associated").getDefaultModelObject(); } }
{ "content_hash": "56c0b2e900f603a78e0c9403d75fbdec", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 113, "avg_line_length": 42.47761194029851, "alnum_prop": 0.7122276879831342, "repo_name": "Orange-OpenSource/elpaaso-core", "id": "5046f687dbeebedbdd3df4d1ca1aa430672fadea", "size": "3427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cloud-paas/cloud-paas-webapp/cloud-paas-webapp-war/src/test/java/com/francetelecom/clara/cloud/presentation/utils/DeleteEditObjects.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3983" }, { "name": "CSS", "bytes": "78369" }, { "name": "Cucumber", "bytes": "55546" }, { "name": "HTML", "bytes": "170257" }, { "name": "Java", "bytes": "4183310" }, { "name": "JavaScript", "bytes": "5958" } ], "symlink_target": "" }
namespace mojo { template<> class MOJO_INPUT_EVENTS_EXPORT TypeConverter<EventPtr, ui::Event> { public: static EventPtr ConvertFrom(const ui::Event& input); }; template<> class MOJO_INPUT_EVENTS_EXPORT TypeConverter<EventPtr, ui::KeyEvent> { public: static EventPtr ConvertFrom(const ui::KeyEvent& input); }; template<> class MOJO_INPUT_EVENTS_EXPORT TypeConverter<EventPtr, scoped_ptr<ui::Event> > { public: static scoped_ptr<ui::Event> ConvertTo(const EventPtr& input); }; } // namespace mojo #endif // MOJO_SERVICES_PUBLIC_CPP_INPUT_EVENTS_INPUT_EVENTS_TYPE_CONVERTERS_H_
{ "content_hash": "229d6bfa51552c157d5389534dc07630", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 80, "avg_line_length": 26.5, "alnum_prop": 0.6933962264150944, "repo_name": "chromium2014/src", "id": "00a03ac2e77e0efc77d180b302af8c19d11f0a5e", "size": "1178", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "mojo/services/public/cpp/input_events/input_events_type_converters.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1889381" }, { "name": "Awk", "bytes": "8660" }, { "name": "C", "bytes": "39993418" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "220757674" }, { "name": "CSS", "bytes": "973910" }, { "name": "Java", "bytes": "6583410" }, { "name": "JavaScript", "bytes": "20967999" }, { "name": "Mercury", "bytes": "9480" }, { "name": "Objective-C", "bytes": "943237" }, { "name": "Objective-C++", "bytes": "7190130" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "674461" }, { "name": "Python", "bytes": "10430892" }, { "name": "Rebol", "bytes": "262" }, { "name": "Shell", "bytes": "1337040" }, { "name": "Standard ML", "bytes": "3705" }, { "name": "Tcl", "bytes": "277091" }, { "name": "XSLT", "bytes": "13493" }, { "name": "nesC", "bytes": "15206" } ], "symlink_target": "" }
ο»Ώusing System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AllReady.Configuration; using AllReady.Models; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; namespace AllReady.DataAccess { public class SampleDataGenerator { private readonly AllReadyContext _context; private readonly SampleDataSettings _settings; private readonly GeneralSettings _generalSettings; private readonly UserManager<ApplicationUser> _userManager; private readonly TimeZoneInfo _timeZone = TimeZoneInfo.Local; public SampleDataGenerator(AllReadyContext context, IOptions<SampleDataSettings> options, IOptions<GeneralSettings> generalSettings, UserManager<ApplicationUser> userManager) { _context = context; _settings = options.Value; _generalSettings = generalSettings.Value; _userManager = userManager; } public void InsertTestData() { // Avoid polluting the database if there's already something in there. if (_context.Locations.Any() || _context.Organizations.Any() || _context.VolunteerTasks.Any() || _context.Campaigns.Any() || _context.Events.Any() || _context.EventSkills.Any() || _context.Skills.Any() || _context.Resources.Any()) { return; } #region postalCodes var existingPostalCode = _context.PostalCodes.ToList(); _context.PostalCodes.AddRange(GetPostalCodes(existingPostalCode)); #endregion var organizations = new List<Organization>(); var organizationSkills = new List<Skill>(); var locations = GetLocations(); var users = new List<ApplicationUser>(); var volunteerTaskSignups = new List<VolunteerTaskSignup>(); var events = new List<Event>(); var eventSkills = new List<EventSkill>(); var campaigns = new List<Campaign>(); var volunteerTasks = new List<VolunteerTask>(); var resources = new List<Resource>(); var contacts = GetContacts(); var skills = new List<Skill>(); #region Skills var medical = new Skill { Name = "Medical", Description = "specific enough, right?" }; var cprCertified = new Skill { Name = "CPR Certified", ParentSkill = medical, Description = "ha ha ha ha, stayin alive" }; var md = new Skill { Name = "MD", ParentSkill = medical, Description = "Trust me, I'm a doctor" }; var surgeon = new Skill { Name = "Surgeon", ParentSkill = md, Description = "cut open; sew shut; play 18 holes" }; skills.AddRange(new[] { medical, cprCertified, md, surgeon }); #endregion #region Organization var organization = new Organization { Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Location = locations.FirstOrDefault(), Campaigns = new List<Campaign>(), OrganizationContacts = new List<OrganizationContact>(), }; #endregion #region Organization Skills organizationSkills.Add(new Skill { Name = "Code Ninja", Description = "Ability to commit flawless code without review or testing", OwningOrganization = organization }); #endregion #region Campaign //TODO: Campaign/Event/Task dates need to be set as a DateTimeOffset, offset to the correct timezone instead of UtcNow or DateTime.Today. var firePreventionCampaign = new Campaign { Name = "Neighborhood Fire Prevention Days", ManagingOrganization = organization, TimeZoneId = _timeZone.Id, StartDateTime = AdjustToTimezone(DateTimeOffset.Now.AddMonths(-1), _timeZone), EndDateTime = AdjustToTimezone(DateTimeOffset.Now.AddMonths(3), _timeZone), Location = GetRandom(locations), Published = true }; organization.Campaigns.Add(firePreventionCampaign); var smokeDetectorCampaignGoal = new CampaignGoal { GoalType = GoalType.Numeric, NumericGoal = 10000, CurrentGoalLevel = 6722, Display = true, TextualGoal = "Total number of smoke detectors installed." }; _context.CampaignGoals.Add(smokeDetectorCampaignGoal); var smokeDetectorCampaign = new Campaign { Name = "Working Smoke Detectors Save Lives", ManagingOrganization = organization, StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone), EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone), CampaignGoals = new List<CampaignGoal> { smokeDetectorCampaignGoal }, TimeZoneId = _timeZone.Id, Location = GetRandom(locations), Published = true }; organization.Campaigns.Add(smokeDetectorCampaign); var financialCampaign = new Campaign { Name = "Everyday Financial Safety", ManagingOrganization = organization, TimeZoneId = _timeZone.Id, StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone), EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone), Location = GetRandom(locations), Published = true }; organization.Campaigns.Add(financialCampaign); var safetyKitCampaign = new Campaign { Name = "Simple Safety Kit Building", ManagingOrganization = organization, TimeZoneId = _timeZone.Id, StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone), EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone), Location = GetRandom(locations), Published = true }; organization.Campaigns.Add(safetyKitCampaign); var carSafeCampaign = new Campaign { Name = "Family Safety In the Car", ManagingOrganization = organization, TimeZoneId = _timeZone.Id, StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone), EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone), Location = GetRandom(locations), Published = true }; organization.Campaigns.Add(carSafeCampaign); var escapePlanCampaign = new Campaign { Name = "Be Ready to Get Out: Have a Home Escape Plan", ManagingOrganization = organization, TimeZoneId = _timeZone.Id, StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-6), _timeZone), EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(6), _timeZone), Location = GetRandom(locations), Published = true }; organization.Campaigns.Add(escapePlanCampaign); #endregion #region Event var queenAnne = new Event { Name = "Queen Anne Fire Prevention Day", Campaign = firePreventionCampaign, StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone), TimeZoneId = firePreventionCampaign.TimeZoneId, Location = GetRandom(locations), RequiredSkills = new List<EventSkill>(), EventType = EventType.Itinerary, }; queenAnne.VolunteerTasks = GetSomeVolunteerTasks(queenAnne, organization); var ask = new EventSkill { Skill = surgeon, Event = queenAnne }; queenAnne.RequiredSkills.Add(ask); eventSkills.Add(ask); ask = new EventSkill { Skill = cprCertified, Event = queenAnne }; queenAnne.RequiredSkills.Add(ask); eventSkills.Add(ask); volunteerTasks.AddRange(queenAnne.VolunteerTasks); var ballard = new Event { Name = "Ballard Fire Prevention Day", Campaign = firePreventionCampaign, StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone), TimeZoneId = firePreventionCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; ballard.VolunteerTasks = GetSomeVolunteerTasks(ballard, organization); volunteerTasks.AddRange(ballard.VolunteerTasks); var madrona = new Event { Name = "Madrona Fire Prevention Day", Campaign = firePreventionCampaign, StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone), TimeZoneId = firePreventionCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; madrona.VolunteerTasks = GetSomeVolunteerTasks(madrona, organization); volunteerTasks.AddRange(madrona.VolunteerTasks); var southLoopSmoke = new Event { Name = "Smoke Detector Installation and Testing-South Loop", Campaign = smokeDetectorCampaign, StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone), TimeZoneId = smokeDetectorCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; southLoopSmoke.VolunteerTasks = GetSomeVolunteerTasks(southLoopSmoke, organization); volunteerTasks.AddRange(southLoopSmoke.VolunteerTasks); var northLoopSmoke = new Event { Name = "Smoke Detector Installation and Testing-Near North Side", Campaign = smokeDetectorCampaign, StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone), TimeZoneId = smokeDetectorCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; northLoopSmoke.VolunteerTasks = GetSomeVolunteerTasks(northLoopSmoke, organization); volunteerTasks.AddRange(northLoopSmoke.VolunteerTasks); var dateTimeToday = DateTime.Today; var rentersInsurance = new Event { Name = "Renters Insurance Education Door to Door and a bag of chips", Description = "description for the win", Campaign = financialCampaign, StartDateTime = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 8, 0, 0), _timeZone), EndDateTime = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 16, 0, 0), _timeZone), TimeZoneId = financialCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Rally, }; rentersInsurance.VolunteerTasks = GetSomeVolunteerTasks(rentersInsurance, organization); volunteerTasks.AddRange(rentersInsurance.VolunteerTasks); var rentersInsuranceEd = new Event { Name = "Renters Insurance Education Door to Door (woop woop)", Description = "another great description", Campaign = financialCampaign, StartDateTime = AdjustToTimezone(financialCampaign.StartDateTime.AddMonths(1).AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(financialCampaign.EndDateTime, _timeZone), TimeZoneId = financialCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; rentersInsuranceEd.VolunteerTasks = GetSomeVolunteerTasks(rentersInsuranceEd, organization); volunteerTasks.AddRange(rentersInsuranceEd.VolunteerTasks); var safetyKitBuild = new Event { Name = "Safety Kit Assembly Volunteer Day", Description = "Full day of volunteers building kits", Campaign = safetyKitCampaign, StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone), TimeZoneId = safetyKitCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; safetyKitBuild.VolunteerTasks = GetSomeVolunteerTasks(safetyKitBuild, organization); volunteerTasks.AddRange(safetyKitBuild.VolunteerTasks); var safetyKitHandout = new Event { Name = "Safety Kit Distribution Weekend", Description = "Handing out kits at local fire stations", Campaign = safetyKitCampaign, StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone), TimeZoneId = safetyKitCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; safetyKitHandout.VolunteerTasks = GetSomeVolunteerTasks(safetyKitHandout, organization); volunteerTasks.AddRange(safetyKitHandout.VolunteerTasks); var carSeatTest1 = new Event { Name = "Car Seat Testing-Naperville", Description = "Checking car seats at local fire stations after last day of school year", Campaign = carSafeCampaign, StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone), TimeZoneId = carSafeCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; carSeatTest1.VolunteerTasks = GetSomeVolunteerTasks(carSeatTest1, organization); volunteerTasks.AddRange(carSeatTest1.VolunteerTasks); var carSeatTest2 = new Event { Name = "Car Seat and Tire Pressure Checking Volunteer Day", Description = "Checking those things all day at downtown train station parking", Campaign = carSafeCampaign, StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone), TimeZoneId = carSafeCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; carSeatTest2.VolunteerTasks = GetSomeVolunteerTasks(carSeatTest2, organization); volunteerTasks.AddRange(carSeatTest2.VolunteerTasks); var homeFestival = new Event { Name = "Park District Home Safety Festival", Description = "At downtown park district(adjacent to pool)", Campaign = safetyKitCampaign, StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1), _timeZone), TimeZoneId = safetyKitCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; homeFestival.VolunteerTasks = GetSomeVolunteerTasks(homeFestival, organization); volunteerTasks.AddRange(homeFestival.VolunteerTasks); var homeEscape = new Event { Name = "Home Escape Plan Flyer Distribution", Description = "Handing out flyers door to door in several areas of town after school/ work hours.Streets / blocks will vary but number of volunteers.", Campaign = escapePlanCampaign, StartDateTime = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddDays(1), _timeZone), EndDateTime = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddMonths(7), _timeZone), TimeZoneId = escapePlanCampaign.TimeZoneId, Location = GetRandom(locations), EventType = EventType.Itinerary, }; homeEscape.VolunteerTasks = GetSomeVolunteerTasks(homeEscape, organization); volunteerTasks.AddRange(homeEscape.VolunteerTasks); #endregion #region Link campaign and event firePreventionCampaign.Events = new List<Event> { queenAnne, ballard, madrona }; smokeDetectorCampaign.Events = new List<Event> { southLoopSmoke, northLoopSmoke }; financialCampaign.Events = new List<Event> { rentersInsurance, rentersInsuranceEd }; safetyKitCampaign.Events = new List<Event> { safetyKitBuild, safetyKitHandout }; carSafeCampaign.Events = new List<Event> { carSeatTest1, carSeatTest2 }; escapePlanCampaign.Events = new List<Event> { homeFestival, homeEscape }; #endregion #region Add Campaigns and Events organizations.Add(organization); campaigns.Add(firePreventionCampaign); campaigns.Add(smokeDetectorCampaign); campaigns.Add(financialCampaign); campaigns.Add(escapePlanCampaign); campaigns.Add(safetyKitCampaign); campaigns.Add(carSafeCampaign); events.AddRange(firePreventionCampaign.Events); events.AddRange(smokeDetectorCampaign.Events); events.AddRange(financialCampaign.Events); events.AddRange(escapePlanCampaign.Events); events.AddRange(safetyKitCampaign.Events); events.AddRange(carSafeCampaign.Events); #endregion #region Insert Resource items into Resources resources.Add(new Resource { Name = "allReady Partner Name", Description = "allready Partner Description", PublishDateBegin = DateTime.Today, PublishDateEnd = DateTime.Today.AddDays(14), MediaUrl = "", ResourceUrl = "", CategoryTag = "Partners" }); resources.Add(new Resource { Name = "allReady Partner Name 2", Description = "allready Partner Description 2", PublishDateBegin = DateTime.Today.AddDays(-3), PublishDateEnd = DateTime.Today.AddDays(-1), MediaUrl = "", ResourceUrl = "", CategoryTag = "Partners" }); #endregion #region Insert into DB _context.Skills.AddRange(skills); _context.Contacts.AddRange(contacts); _context.EventSkills.AddRange(eventSkills); _context.Locations.AddRange(locations); _context.Organizations.AddRange(organizations); _context.VolunteerTasks.AddRange(volunteerTasks); _context.Campaigns.AddRange(campaigns); _context.Events.AddRange(events); _context.Resources.AddRange(resources); //_context.SaveChanges(); #endregion #region Users for Events var username1 = $"{_settings.DefaultUsername}1.com"; var username2 = $"{_settings.DefaultUsername}2.com"; var username3 = $"{_settings.DefaultUsername}3.com"; var user1 = new ApplicationUser { FirstName = "FirstName1", LastName = "LastName1", UserName = username1, Email = username1, EmailConfirmed = true, TimeZoneId = _timeZone.Id, PhoneNumber = "111-111-1111" }; _userManager.CreateAsync(user1, _settings.DefaultAdminPassword).GetAwaiter().GetResult(); users.Add(user1); var user2 = new ApplicationUser { FirstName = "FirstName2", LastName = "LastName2", UserName = username2, Email = username2, EmailConfirmed = true, TimeZoneId = _timeZone.Id, PhoneNumber = "222-222-2222" }; _userManager.CreateAsync(user2, _settings.DefaultAdminPassword).GetAwaiter().GetResult(); users.Add(user2); var user3 = new ApplicationUser { FirstName = "FirstName3", LastName = "LastName3", UserName = username3, Email = username3, EmailConfirmed = true, TimeZoneId = _timeZone.Id, PhoneNumber = "333-333-3333" }; _userManager.CreateAsync(user3, _settings.DefaultAdminPassword).GetAwaiter().GetResult(); users.Add(user3); #endregion #region TaskSignups var i = 0; foreach (var volunteerTask in volunteerTasks.Where(t => t.Event == madrona)) { for (var j = 0; j < i; j++) { volunteerTaskSignups.Add(new VolunteerTaskSignup { VolunteerTask = volunteerTask, User = users[j], Status = VolunteerTaskStatus.Assigned }); } i = (i + 1) % users.Count; } _context.VolunteerTaskSignups.AddRange(volunteerTaskSignups); #endregion #region OrganizationContacts organization.OrganizationContacts.Add(new OrganizationContact { Contact = contacts.First(), Organization = organization, ContactType = 1 /*Primary*/ }); #endregion #region Wrap Up DB _context.SaveChanges(); #endregion } private DateTimeOffset AdjustToTimezone(DateTimeOffset dateTimeOffset, TimeZoneInfo timeZone) { return new DateTimeOffset(dateTimeOffset.DateTime, timeZone.GetUtcOffset(dateTimeOffset.DateTime)); } private List<Contact> GetContacts() { var list = new List<Contact>(); list.Add(new Contact { FirstName = "Bob", LastName = "Smith", Email = "BobSmith@mailinator.com", PhoneNumber = "999-888-7777" }); list.Add(new Contact { FirstName = "George", LastName = "Leone", Email = "GeorgeLeone@mailinator.com", PhoneNumber = "999-888-7777" }); return list; } #region Sample Data Helper methods private static T GetRandom<T>(List<T> list) { var rand = new Random(); return list[rand.Next(list.Count)]; } private List<VolunteerTask> GetSomeVolunteerTasks(Event campaignEvent, Organization organization) { var volunteerTasks = new List<VolunteerTask>(); for (var i = 0; i < 5; i++) { volunteerTasks.Add(new VolunteerTask { Event = campaignEvent, Description = "Description of a very important volunteerTask # " + i, Name = "Task # " + i, EndDateTime = AdjustToTimezone(DateTime.Today.AddHours(17).AddDays(i), _timeZone), StartDateTime = AdjustToTimezone(DateTime.Today.AddHours(9).AddDays(i - 1), _timeZone), Organization = organization, NumberOfVolunteersRequired = 5 }); } return volunteerTasks; } private static Location CreateLocation(string address1, string city, string state, string postalCode) { var ret = new Location { Address1 = address1, City = city, State = state, Country = "US", PostalCode = postalCode, Name = "Humanitarian Toolbox location", PhoneNumber = "1-425-555-1212" }; return ret; } private List<PostalCodeGeo> GetPostalCodes(IList<PostalCodeGeo> existingPostalCode) { var postalCodes = new List<PostalCodeGeo>(); if (!existingPostalCode.Any(item => item.PostalCode == "98052")) postalCodes.Add(new PostalCodeGeo { City = "Remond", State = "WA", PostalCode = "98052" }); if (!existingPostalCode.Any(item => item.PostalCode == "98004")) postalCodes.Add(new PostalCodeGeo { City = "Bellevue", State = "WA", PostalCode = "98004" }); if (!existingPostalCode.Any(item => item.PostalCode == "98116")) postalCodes.Add(new PostalCodeGeo { City = "Seattle", State = "WA", PostalCode = "98116" }); if (!existingPostalCode.Any(item => item.PostalCode == "98117")) postalCodes.Add(new PostalCodeGeo { City = "Seattle", State = "WA", PostalCode = "98117" }); if (!existingPostalCode.Any(item => item.PostalCode == "98007")) postalCodes.Add(new PostalCodeGeo { City = "Bellevue", State = "WA", PostalCode = "98007" }); if (!existingPostalCode.Any(item => item.PostalCode == "98027")) postalCodes.Add(new PostalCodeGeo { City = "Issaquah", State = "WA", PostalCode = "98027" }); if (!existingPostalCode.Any(item => item.PostalCode == "98034")) postalCodes.Add(new PostalCodeGeo { City = "Kirkland", State = "WA", PostalCode = "98034" }); if (!existingPostalCode.Any(item => item.PostalCode == "98033")) postalCodes.Add(new PostalCodeGeo { City = "Kirkland", State = "WA", PostalCode = "98033" }); if (!existingPostalCode.Any(item => item.PostalCode == "60505")) postalCodes.Add(new PostalCodeGeo { City = "Aurora", State = "IL", PostalCode = "60505" }); if (!existingPostalCode.Any(item => item.PostalCode == "60506")) postalCodes.Add(new PostalCodeGeo { City = "Aurora", State = "IL", PostalCode = "60506" }); if (!existingPostalCode.Any(item => item.PostalCode == "45231")) postalCodes.Add(new PostalCodeGeo { City = "Cincinnati", State = "OH", PostalCode = "45231" }); if (!existingPostalCode.Any(item => item.PostalCode == "45240")) postalCodes.Add(new PostalCodeGeo { City = "Cincinnati", State = "OH", PostalCode = "45240" }); return postalCodes; } private List<Location> GetLocations() { var ret = new List<Location> { CreateLocation("1 Microsoft Way", "Redmond", "WA", "98052"), CreateLocation("15563 Ne 31st St", "Redmond", "WA", "98052"), CreateLocation("700 Bellevue Way Ne", "Bellevue", "WA", "98004"), CreateLocation("1702 Alki Ave SW", "Seattle", "WA", "98116"), CreateLocation("8498 Seaview Pl NW", "Seattle", "WA", "98117"), CreateLocation("6046 W Lake Sammamish Pkwy Ne", "Redmond", "WA", "98052"), CreateLocation("7031 148th Ave Ne", "Redmond", "WA", "98052"), CreateLocation("2430 148th Ave SE", "Bellevue", "WA", "98007"), CreateLocation("2000 NW Sammamish Rd", "Issaquah", "WA", "98027"), CreateLocation("9703 Ne Juanita Dr", "Kirkland", "WA", "98034"), CreateLocation("25 Lakeshore Plaza Dr", "Kirkland", "Washington", "98033"), CreateLocation("633 Waverly Way", "Kirkland", "WA", "98033") }; return ret; } #endregion /// <summary> /// Creates a administrative user who can manage the inventory. /// </summary> public async Task CreateAdminUser() { var user = await _userManager.FindByNameAsync(_settings.DefaultAdminUsername); if (user == null) { user = new ApplicationUser { FirstName = "FirstName4", LastName = "LastName4", UserName = _settings.DefaultAdminUsername, Email = _settings.DefaultAdminUsername, TimeZoneId = _timeZone.Id, EmailConfirmed = true, PhoneNumber = "444-444-4444" }; _userManager.CreateAsync(user, _settings.DefaultAdminPassword).GetAwaiter().GetResult(); _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.UserType, "SiteAdmin")).GetAwaiter().GetResult(); var user2 = new ApplicationUser { FirstName = "FirstName5", LastName = "LastName5", UserName = _settings.DefaultOrganizationUsername, Email = _settings.DefaultOrganizationUsername, TimeZoneId = _timeZone.Id, EmailConfirmed = true, PhoneNumber = "555-555-5555" }; // For the sake of being able to exercise Organization-specific stuff, we need to associate a organization. await _userManager.CreateAsync(user2, _settings.DefaultAdminPassword); await _userManager.AddClaimAsync(user2, new Claim(Security.ClaimTypes.UserType, "OrgAdmin")); await _userManager.AddClaimAsync(user2, new Claim(Security.ClaimTypes.Organization, _context.Organizations.First().Id.ToString())); var user3 = new ApplicationUser { FirstName = "FirstName5", LastName = "LastName5", UserName = _settings.DefaultUsername, Email = _settings.DefaultUsername, TimeZoneId = _timeZone.Id, EmailConfirmed = true, PhoneNumber = "666-666-6666" }; await _userManager.CreateAsync(user3, _settings.DefaultAdminPassword); } } } }
{ "content_hash": "7d87aab5985dc0ae616e721220547af2", "timestamp": "", "source": "github", "line_count": 611, "max_line_length": 182, "avg_line_length": 52.55155482815057, "alnum_prop": 0.5833878351863964, "repo_name": "arst/allReady", "id": "8a0b5765106dbd53328c563fa739fda13cb52e8f", "size": "32111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AllReadyApp/Web-App/AllReady/DataAccess/SampleDataGenerator.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4478" }, { "name": "C#", "bytes": "2515606" }, { "name": "CSS", "bytes": "271944" }, { "name": "F#", "bytes": "16730" }, { "name": "HTML", "bytes": "8838" }, { "name": "JavaScript", "bytes": "98446" }, { "name": "PowerShell", "bytes": "353" }, { "name": "TypeScript", "bytes": "3840" } ], "symlink_target": "" }
package org.apache.felix.http.base.internal.dispatch; import jakarta.servlet.http.HttpServletMapping; import jakarta.servlet.http.MappingMatch; /** * Information about the request */ public final class RequestInfo implements HttpServletMapping { final String servletPath; final String pathInfo; final String queryString; final String requestURI; private final String matchServletName; private final String matchPattern; private final String matchValue; private final MappingMatch match; final boolean nameMatch; /** * Create a new request info * @param servletPath The servlet path * @param pathInfo The path info * @param queryString The query string * @param requestURI The request uri * @param matchServletName The servlet name * @param matchPattern The servlet pattern * @param matchValue The value matching * @param match The match type * @param nameMatch Is named dispatcher */ public RequestInfo(final String servletPath, final String pathInfo, final String queryString, final String requestURI, final String matchServletName, final String matchPattern, final String matchValue, final MappingMatch match, final boolean nameMatch) { this.servletPath = servletPath; this.pathInfo = pathInfo; this.queryString = queryString; this.requestURI = requestURI; this.matchServletName = matchServletName; this.matchPattern = matchPattern; this.matchValue = matchValue; this.match = match; this.nameMatch = nameMatch; } @Override public String getMatchValue() { return this.matchValue; } @Override public String getPattern() { return this.matchPattern; } @Override public String getServletName() { return this.matchServletName; } @Override public MappingMatch getMappingMatch() { return this.match; } @Override public String toString() { StringBuilder sb = new StringBuilder("RequestInfo[servletPath ="); sb.append(this.servletPath).append(", pathInfo = ").append(this.pathInfo); sb.append(", queryString = ").append(this.queryString).append("]"); return sb.toString(); } }
{ "content_hash": "55f82d312f5ce1a5346c682bbde9367a", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 82, "avg_line_length": 28.710843373493976, "alnum_prop": 0.6588334032731851, "repo_name": "apache/felix-dev", "id": "9a01930b173cce7e34c085b1a0b0f50821538d63", "size": "3185", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "http/base/src/main/java/org/apache/felix/http/base/internal/dispatch/RequestInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53237" }, { "name": "Groovy", "bytes": "9231" }, { "name": "HTML", "bytes": "372812" }, { "name": "Java", "bytes": "28836360" }, { "name": "JavaScript", "bytes": "248796" }, { "name": "Scala", "bytes": "40378" }, { "name": "Shell", "bytes": "12628" }, { "name": "XSLT", "bytes": "151258" } ], "symlink_target": "" }
require 'spec_helper' module RailsBestPractices::Core describe Error do it 'returns error with filename, line number and message' do expect( described_class.new( filename: 'app/models/user.rb', line_number: '100', message: 'not good', type: 'BogusReview' ).to_s ).to eq('app/models/user.rb:100 - not good') end it 'returns short filename' do Runner.base_path = '../rails-bestpractices.com' expect( described_class.new( filename: '../rails-bestpractices.com/app/models/user.rb', line_number: '100', message: 'not good', type: 'BogusReview' ).short_filename ).to eq('app/models/user.rb') end it 'returns first line number' do expect( described_class.new( filename: 'app/models/user.rb', line_number: '50,70,100', message: 'not good', type: 'BogusReview' ).first_line_number ).to eq('50') end end end
{ "content_hash": "18cd1306c5f9d47b4e5369a6018d0365", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 108, "avg_line_length": 29.666666666666668, "alnum_prop": 0.5944841675178754, "repo_name": "flyerhzm/rails_best_practices", "id": "ef36fa65f4098c6f23b49a7915bf84e61d5c1482", "size": "1010", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/rails_best_practices/core/error_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "6586" }, { "name": "Roff", "bytes": "182" }, { "name": "Ruby", "bytes": "460094" } ], "symlink_target": "" }
<?php echo "<?php\n"; echo "/**\n"; echo " * @var " . $this->controllerClass . " \$this\n"; echo " * @var " . $this->modelClass . " \$" . lcfirst($this->modelClass) . "\n"; echo " */\n"; echo "\n"; echo "/** @var ActiveForm \$form */\n"; echo "\$form = \$this->beginWidget('ActiveForm', array(\n"; echo " //'action' => Yii::app()->createUrl(\$this->route),\n"; echo " //'layout' => TbHtml::FORM_LAYOUT_HORIZONTAL,\n"; echo " 'method' => 'get',\n"; echo " 'htmlOptions' => array('class' => 'hide'),\n"; echo "));\n"; echo "\$form->searchToggle('" . lcfirst($this->modelClass) . "-grid-search', '" . lcfirst($this->modelClass) . "-grid');\n"; echo "\n"; echo "echo '<fieldset>';\n"; echo "echo '<legend>' . \$this->getName() . ' ' . Yii::t('app', 'Search') . '</legend>';\n"; foreach ($this->tableSchema->columns as $column) { if ($column->type === 'boolean') $inputField = 'checkBoxControlGroup'; elseif (stripos($column->dbType, 'text') !== false) $inputField = 'textAreaControlGroup'; elseif (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) $inputField = 'passwordFieldControlGroup'; else $inputField = 'textFieldControlGroup'; echo "echo \$form->" . $inputField . "(\$" . lcfirst($this->modelClass) . ", '" . $column->name . "');\n"; } echo "echo '</fieldset>';\n"; echo "\n"; echo "echo \$form->getSubmitButtonRow(Yii::t('app', 'Search'), array('icon' => 'search white'));\n"; echo "\n"; echo "\$this->endWidget();\n";
{ "content_hash": "cfb1bb6ff4355511b894febe08518499", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 124, "avg_line_length": 40.75675675675676, "alnum_prop": 0.5709549071618037, "repo_name": "cornernote/gii-tasty-templates", "id": "f49d179ebaab61fc8dd4b7b6f4bff1016792e2a4", "size": "1870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tasty/crud/templates/tasty/_search.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "40981" } ], "symlink_target": "" }
ο»Ώ// ----------------------------------------------------------------------- // <copyright file="IEasing.cs" company="Steven Kirk"> // Copyright 2014 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Animation { /// <summary> /// Defines the interface for easing functions. /// </summary> public interface IEasing { /// <summary> /// Returns the value of the transition for the specified progress. /// </summary> /// <param name="progress">The progress of the transition, from 0 to 1.</param> /// <param name="start">The start value of the transition.</param> /// <param name="finish">The end value of the transition.</param> /// <returns> /// A value between <paramref name="start"/> and <paramref name="finish"/> as determined /// by <paramref name="progress"/>. /// </returns> object Ease(double progress, object start, object finish); } }
{ "content_hash": "d58cf57c20651e1e3519427780f1d7ba", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 96, "avg_line_length": 40.92307692307692, "alnum_prop": 0.5272556390977443, "repo_name": "sagamors/Perspex", "id": "f9dc0f85d5ea66cd39991c3e0ae6f2ecccb00e4c", "size": "1066", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Perspex.Animation/IEasing.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1918688" } ], "symlink_target": "" }
<?php namespace cascade\components\web\widgets\base; use cascade\components\types\Relationship; use canis\base\exceptions\Exception; use canis\helpers\ArrayHelper; use canis\helpers\Html; use Yii; trait ObjectWidgetTrait { protected $_dataProvider; public $pageSize = 5; protected $_lazyObjectWidget; public function generateStart() { $this->htmlOptions['data-instructions'] = json_encode($this->refreshInstructions); if ($this->lazy) { Html::addCssClass($this->htmlOptions, 'widget-lazy'); } return parent::generateStart(); } public function getLazy() { if (!Yii::$app->collectors['widgets']->lazy) { return false; } if (!isset($this->_lazyObjectWidget)) { return true; } return $this->_lazyObjectWidget; } public function getWidgetClasses() { $classes = parent::getWidgetClasses(); $classes[] = 'refreshable'; $queryModelClass = $this->owner->primaryModel; $classes[] = 'model-' . $queryModelClass::baseClassName(); return $classes; } public function getPriorityAdjust() { if (isset($this->dataProvider->totalCount)) { if (empty($this->dataProvider->totalCount)) { return 1000; } } return 0; } public function getDataProvider() { if (is_null($this->_dataProvider)) { $dataProvider = $this->dataProviderSettings; if (!isset($dataProvider['class'])) { $dataProvider['class'] = 'canis\data\ActiveDataProvider'; } $method = ArrayHelper::getValue($this->settings, 'queryRole', 'all'); if (in_array($method, ['parents', 'children']) && empty(Yii::$app->request->object)) { throw new Exception("Object widget requested when no object has been set!"); } $queryModelClass = $this->owner->primaryModel; switch ($method) { case 'parents': $dataProvider['query'] = Yii::$app->request->object->queryParentObjects($queryModelClass); break; case 'children': $dataProvider['query'] = Yii::$app->request->object->queryChildObjects($queryModelClass); break; default: $dataProvider['query'] = $queryModelClass::find(); break; } $dataProvider['query']->action = 'list'; $dummyModel = new $queryModelClass(); if (in_array($this->currentSortBy, ['familiarity', 'last_accessed'])) { if ($dataProvider['query']->getBehavior('FamiliarityQuery') === null) { $dataProvider['query']->attachBehavior('FamiliarityQuery', ['class' => 'cascade\components\db\behaviors\QueryFamiliarity']); } $dataProvider['query']->withFamiliarity(); } if ($this->getState('showHidden', false)) { $dataProvider['query']->includeArchives(); } else { $dataProvider['query']->excludeArchives(); } $dataProvider['pagination'] = $this->paginationSettings; $dataProvider['sort'] = $this->sortSettings; $this->_dataProvider = Yii::createObject($dataProvider); } return $this->_dataProvider; } public function getSortBy() { $sortBy = []; $dummyModel = $this->owner->dummyModel; $descriptorField = $dummyModel->descriptorField; if (is_array($descriptorField)) { $descriptorLabel = $dummyModel->getAttributeLabel('descriptor'); } else { $descriptorLabel = $dummyModel->getAttributeLabel($descriptorField); } $alias = $dummyModel->tableName(); $defaultOrder = $dummyModel->getDefaultOrder($alias); $sortBy['familiarity'] = [ 'label' => 'Familiarity', 'asc' => array_merge(['ft.[[familiarity]]' => SORT_ASC], $defaultOrder), 'desc' => array_merge(['ft.[[familiarity]]' => SORT_DESC], $defaultOrder), ]; $sortBy['last_accessed'] = [ 'label' => 'Last Accessed', 'asc' => array_merge(['ft.[[last_accessed]]' => SORT_ASC], $defaultOrder), 'desc' => array_merge(['ft.[[last_accessed]]' => SORT_DESC], $defaultOrder), ]; $sortBy['descriptor'] = [ 'label' => $descriptorLabel, 'asc' => $dummyModel->getDescriptorDefaultOrder($alias, SORT_ASC), 'desc' => $dummyModel->getDescriptorDefaultOrder($alias, SORT_DESC), ]; return $sortBy; } public function getCurrentSortBy() { return $this->getState('sortBy', 'familiarity'); } public function getCurrentSortByDirection() { return $this->getState('sortByDirection', ($this->currentSortBy === 'familiarity') ? 'desc' : 'asc'); } public function buildContext($object = null) { if (method_exists($this, 'buildContextBase')) { $context = $this->buildContextBase($object); } else { $context = []; } $method = ArrayHelper::getValue($this->settings, 'queryRole', 'all'); $relationship = ArrayHelper::getValue($this->settings, 'relationship', false); if (isset($object) && isset(Yii::$app->request->object) && Yii::$app->request->object->primaryKey !== $object->primaryKey) { $context['object'] = Yii::$app->request->object; } if ($relationship) { $objectType = $relationship->companionRoleType($method); $objectRole = $relationship->companionRole($method); $relationName = $objectRole . ':' . $objectType->systemId; $context['relation'] = [$relationName]; } return $context; } public function getHeaderMenu() { $menu = []; $baseCreate = []; $typePrefix = null; $method = ArrayHelper::getValue($this->settings, 'queryRole', 'all'); $relationship = ArrayHelper::getValue($this->settings, 'relationship', false); $create = $link = isset(Yii::$app->request->object) && Yii::$app->request->object->can('update'); if (($create || $link) && in_array($method, ['parents', 'children'])) { if (empty(Yii::$app->request->object) || !$relationship) { throw new Exception("Object widget requested when no object has been set!"); } $baseCreate['related_object_id'] = Yii::$app->request->object->primaryKey; $objectRole = $relationship->companionRole($method); $companionRole = $relationship->companionRole($objectRole); $relatedType = $companionRole . ':' . $relationship->roleType($companionRole)->systemId; $baseCreate['object_relation'] = $relatedType; $link = $link && $relationship->canLink($objectRole, Yii::$app->request->object); $create = $create && $relationship->canCreate($objectRole, Yii::$app->request->object); } $baseCreate['type'] = $this->owner->systemId; // $typePrefix . if ($create && Yii::$app->gk->canGeneral('create', $this->owner->primaryModel)) { $createUrl = $baseCreate; array_unshift($createUrl, '/object/create'); $menu[] = [ 'label' => '<i class="fa fa-plus"></i>', 'linkOptions' => ['title' => 'Create'], 'url' => $createUrl, ]; } if ($link) { $createUrl = $baseCreate; array_unshift($createUrl, '/object/link'); $menu[] = [ 'label' => '<i class="fa fa-link"></i>', 'linkOptions' => ['title' => 'Link'], 'url' => $createUrl, ]; } //sorting $sortBy = $this->sortBy; $currentSortBy = $this->currentSortBy; $currentSortByDirection = $this->currentSortByDirection; $oppositeSortByDirection = ($currentSortByDirection === 'asc') ? 'desc' : 'asc'; if (!empty($sortBy)) { $item = [ 'label' => '<i class="fa fa-sort"></i>', 'linkOptions' => ['title' => 'Sort by'], 'url' => '#', 'items' => [], 'options' => ['class' => 'dropleft'], ]; foreach ($sortBy as $sortKey => $sortItem) { $newSortByDirection = 'asc'; $isActive = $sortKey === $currentSortBy; $extra = ''; if ($isActive) { $extra = '<i class="pull-right fa fa-sort-' . $oppositeSortByDirection . '"></i>'; $newSortByDirection = $oppositeSortByDirection; } $stateChange = [ $this->stateKeyName('sortBy') => $sortKey, $this->stateKeyName('sortByDirection') => $newSortByDirection, ]; $item['items'][] = [ 'label' => $extra . $sortItem['label'], 'linkOptions' => [ 'title' => 'Sort by ' . $sortItem['label'], 'data-state-change' => json_encode($stateChange), ], 'options' => [ 'class' => $isActive ? 'active' : '', ], 'url' => '#', 'active' => $isActive, ]; } $menu[] = $item; } return $menu; } public function getListItemOptions($model, $key, $index) { $options = self::getListItemOptionsBase($model, $key, $index); //return $options; $objectType = $model->objectType; $queryRole = ArrayHelper::getValue($this->settings, 'queryRole', false); $relationship = ArrayHelper::getValue($this->settings, 'relationship', false); if (!$relationship) { return $options; } if ($queryRole === 'children') { $baseUrl['object_relation'] = 'child'; $primaryRelation = $relationship->getPrimaryObject(Yii::$app->request->object, $model, 'child'); $key = 'child_object_id'; } else { $baseUrl['object_relation'] = 'parent'; $primaryRelation = $relationship->getPrimaryObject(Yii::$app->request->object, $model, 'parent'); $key = 'parent_object_id'; } if ($primaryRelation && $primaryRelation->{$key} === $model->primaryKey) { Html::addCssClass($options, 'active'); } $options['data-object-id'] = $model->primaryKey; return $options; } public function getMenuItems($model, $key, $index) { $objectType = $model->objectType; $menu = []; $baseUrl = ['id' => $model->primaryKey]; $queryRole = ArrayHelper::getValue($this->settings, 'queryRole', false); $relationship = ArrayHelper::getValue($this->settings, 'relationship', false); // $relationModel = $this->getObjectRelationModel($model); $baseUrl['related_object_id'] = Yii::$app->request->object->primaryKey; // $baseUrl['relationship_id'] = $relationship->systemId; if ($queryRole === 'children') { $primaryRelation = $relationship->getPrimaryObject(Yii::$app->request->object, $model, 'child'); $baseUrl['object_relation'] = 'child:' . $model->objectType->systemId; $checkField = 'child_object_id'; } else { $primaryRelation = $relationship->getPrimaryObject(Yii::$app->request->object, $model, 'parent'); $baseUrl['object_relation'] = 'parent:' . $model->objectType->systemId; $checkField = 'parent_object_id'; } if ($primaryRelation !== false && (empty($primaryRelation) || ($primaryRelation && $primaryRelation->{$checkField} !== $model->primaryKey) )) { $menu['primary'] = [ 'icon' => 'fa fa-star', 'label' => 'Set as primary', 'url' => ['/object/set-primary'] + $baseUrl, 'linkOptions' => ['data-handler' => 'background'], ]; } // update button $updateLabel = false; if (!$objectType->hasDashboard && $model->can('update')) { $updateLabel = 'Update'; $updateUrl = ['/object/update'] + $baseUrl; } elseif ($model->canUpdateAssociation(Yii::$app->request->object) && $relationship->hasFields) { $updateLabel = 'Update Relationship'; $updateUrl = ['/object/link'] + $baseUrl; } if ($updateLabel) { $menu['update'] = [ 'icon' => 'fa fa-wrench', 'label' => $updateLabel, 'url' => $updateUrl, 'linkOptions' => ['data-handler' => 'background'], ]; } if (!$objectType->hasDashboard && $model->can('manageAccess')) { $menu['access'] = [ 'icon' => 'fa fa-key', 'label' => 'Manage Access', 'url' => ['/object/access'] + $baseUrl, 'linkOptions' => ['data-handler' => 'background'], ]; } // delete button if ( $model->can('delete') // they can actually delete it || $model->canDeleteAssociation(Yii::$app->request->object) ) { $menu['delete'] = [ 'icon' => 'fa fa-trash-o', 'label' => 'Delete', 'url' => ['/object/delete'] + $baseUrl, 'linkOptions' => ['data-handler' => 'background'], ]; } return $menu; } protected function getPossibleMenuItems($model) { $possible = []; return $possible; } public function getVariables() { $vars = []; if ( isset($this->settings['relationship']) && isset($this->settings['queryRole']) && $this->settings['relationship']->child === $this->settings['relationship']->parent ) { if ($this->settings['queryRole'] === 'parents') { $vars['relationship'] = 'Parent'; } elseif ($this->settings['queryRole'] === 'children') { $vars['relationship'] = 'Child'; } } return array_merge(parent::getVariables(), $vars); } public function getPaginationSettings() { return [ 'class' => 'canis\data\Pagination', 'pageSize' => $this->pageSize, 'validatePage' => false, 'page' => $this->getState('_page', 0), ]; } public function getSortSettings() { return [ 'class' => 'canis\data\Sort', 'sortOrders' => [ $this->currentSortBy => $this->currentSortByDirection === 'asc' ? SORT_ASC : SORT_DESC, ], 'attributes' => $this->getSortBy(), ]; } public function getPagerSettings() { return [ 'class' => 'canis\widgets\LinkPager', 'pageStateKey' => $this->stateKeyName('_page'), ]; } public function getDataProviderSettings() { return [ 'class' => 'canis\data\ActiveDataProvider', ]; } }
{ "content_hash": "d86a9412aa4c1fb8419ee190e69648ee", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 144, "avg_line_length": 36.52214452214452, "alnum_prop": 0.5104671942813378, "repo_name": "canis-io/cascade-lib", "id": "91b57c2cd8372ccb316982c4fba295677d24fbf3", "size": "15792", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/components/web/widgets/base/ObjectWidgetTrait.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "8360" }, { "name": "JavaScript", "bytes": "56694" }, { "name": "PHP", "bytes": "935908" } ], "symlink_target": "" }
package ottltest // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottltest" func Strp(s string) *string { return &s } func Floatp(f float64) *float64 { return &f } func Intp(i int64) *int64 { return &i } func Boolp(b bool) *bool { return &b }
{ "content_hash": "437b616b1c4d50f9227b5274f724fb54", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 104, "avg_line_length": 16.470588235294116, "alnum_prop": 0.7071428571428572, "repo_name": "open-telemetry/opentelemetry-collector-contrib", "id": "53155eb1e1abbd9e15c77453a0659bba7fae5839", "size": "879", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/ottl/ottltest/ottltest.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2677" }, { "name": "Go", "bytes": "14675167" }, { "name": "Makefile", "bytes": "22547" }, { "name": "PowerShell", "bytes": "2781" }, { "name": "Shell", "bytes": "11998" } ], "symlink_target": "" }
package org.apache.hadoop.mapred; import org.apache.hadoop.io.*; import java.io.*; import java.util.*; /************************************************** * A TaskTrackerStatus is a MapReduce primitive. Keeps * info on a TaskTracker. The JobTracker maintains a set * of the most recent TaskTrackerStatus objects for each * unique TaskTracker it knows about. * **************************************************/ public class TaskTrackerStatus implements Writable { static { // register a ctor WritableFactories.setFactory (TaskTrackerStatus.class, new WritableFactory() { public Writable newInstance() { return new TaskTrackerStatus(); } }); } String trackerName; String host; int httpPort; int failures; List<TaskStatus> taskReports; volatile long lastSeen; private int maxMapTasks; private int maxReduceTasks; /** * Class representing a collection of resources on this tasktracker. */ public static class ResourceStatus implements Writable { private long totalVirtualMemory; private long totalPhysicalMemory; private long mapSlotMemorySizeOnTT; private long reduceSlotMemorySizeOnTT; private long availableSpace; ResourceStatus() { totalVirtualMemory = JobConf.DISABLED_MEMORY_LIMIT; totalPhysicalMemory = JobConf.DISABLED_MEMORY_LIMIT; mapSlotMemorySizeOnTT = JobConf.DISABLED_MEMORY_LIMIT; reduceSlotMemorySizeOnTT = JobConf.DISABLED_MEMORY_LIMIT; availableSpace = Long.MAX_VALUE; } /** * Set the maximum amount of virtual memory on the tasktracker. * * @param vmem maximum amount of virtual memory on the tasktracker in bytes. */ void setTotalVirtualMemory(long totalMem) { totalVirtualMemory = totalMem; } /** * Get the maximum amount of virtual memory on the tasktracker. * * If this is {@link JobConf#DISABLED_MEMORY_LIMIT}, it should be ignored * and not used in any computation. * * @return the maximum amount of virtual memory on the tasktracker in bytes. */ public long getTotalVirtualMemory() { return totalVirtualMemory; } /** * Set the maximum amount of physical memory on the tasktracker. * * @param totalRAM maximum amount of physical memory on the tasktracker in * bytes. */ void setTotalPhysicalMemory(long totalRAM) { totalPhysicalMemory = totalRAM; } /** * Get the maximum amount of physical memory on the tasktracker. * * If this is {@link JobConf#DISABLED_MEMORY_LIMIT}, it should be ignored * and not used in any computation. * * @return maximum amount of physical memory on the tasktracker in bytes. */ public long getTotalPhysicalMemory() { return totalPhysicalMemory; } /** * Set the memory size of each map slot on this TT. This will be used by JT * for accounting more slots for jobs that use more memory. * * @param mem */ void setMapSlotMemorySizeOnTT(long mem) { mapSlotMemorySizeOnTT = mem; } /** * Get the memory size of each map slot on this TT. See * {@link #setMapSlotMemorySizeOnTT(long)} * * @return */ long getMapSlotMemorySizeOnTT() { return mapSlotMemorySizeOnTT; } /** * Set the memory size of each reduce slot on this TT. This will be used by * JT for accounting more slots for jobs that use more memory. * * @param mem */ void setReduceSlotMemorySizeOnTT(long mem) { reduceSlotMemorySizeOnTT = mem; } /** * Get the memory size of each reduce slot on this TT. See * {@link #setReduceSlotMemorySizeOnTT(long)} * * @return */ long getReduceSlotMemorySizeOnTT() { return reduceSlotMemorySizeOnTT; } /** * Set the available disk space on the TT * @param availSpace */ void setAvailableSpace(long availSpace) { availableSpace = availSpace; } /** * Will return LONG_MAX if space hasn't been measured yet. * @return bytes of available local disk space on this tasktracker. */ public long getAvailableSpace() { return availableSpace; } public void write(DataOutput out) throws IOException { WritableUtils.writeVLong(out, totalVirtualMemory); WritableUtils.writeVLong(out, totalPhysicalMemory); WritableUtils.writeVLong(out, mapSlotMemorySizeOnTT); WritableUtils.writeVLong(out, reduceSlotMemorySizeOnTT); WritableUtils.writeVLong(out, availableSpace); } public void readFields(DataInput in) throws IOException { totalVirtualMemory = WritableUtils.readVLong(in); totalPhysicalMemory = WritableUtils.readVLong(in); mapSlotMemorySizeOnTT = WritableUtils.readVLong(in); reduceSlotMemorySizeOnTT = WritableUtils.readVLong(in); availableSpace = WritableUtils.readVLong(in); } } private ResourceStatus resStatus; /** */ public TaskTrackerStatus() { taskReports = new ArrayList<TaskStatus>(); resStatus = new ResourceStatus(); } /** */ public TaskTrackerStatus(String trackerName, String host, int httpPort, List<TaskStatus> taskReports, int failures, int maxMapTasks, int maxReduceTasks) { this.trackerName = trackerName; this.host = host; this.httpPort = httpPort; this.taskReports = new ArrayList<TaskStatus>(taskReports); this.failures = failures; this.maxMapTasks = maxMapTasks; this.maxReduceTasks = maxReduceTasks; this.resStatus = new ResourceStatus(); } /** */ public String getTrackerName() { return trackerName; } /** */ public String getHost() { return host; } /** * Get the port that this task tracker is serving http requests on. * @return the http port */ public int getHttpPort() { return httpPort; } /** * Get the number of tasks that have failed on this tracker. * @return The number of failed tasks */ public int getFailures() { return failures; } /** * Get the current tasks at the TaskTracker. * Tasks are tracked by a {@link TaskStatus} object. * * @return a list of {@link TaskStatus} representing * the current tasks at the TaskTracker. */ public List<TaskStatus> getTaskReports() { return taskReports; } /** * Return the current MapTask count */ public int countMapTasks() { int mapCount = 0; for (Iterator<TaskStatus> it = taskReports.iterator(); it.hasNext();) { TaskStatus ts = it.next(); TaskStatus.State state = ts.getRunState(); if (ts.getIsMap() && ((state == TaskStatus.State.RUNNING) || (state == TaskStatus.State.UNASSIGNED) || ts.inTaskCleanupPhase())) { mapCount++; } } return mapCount; } /** * Return the current ReduceTask count */ public int countReduceTasks() { int reduceCount = 0; for (Iterator<TaskStatus> it = taskReports.iterator(); it.hasNext();) { TaskStatus ts = it.next(); TaskStatus.State state = ts.getRunState(); if ((!ts.getIsMap()) && ((state == TaskStatus.State.RUNNING) || (state == TaskStatus.State.UNASSIGNED) || ts.inTaskCleanupPhase())) { reduceCount++; } } return reduceCount; } /** */ public long getLastSeen() { return lastSeen; } /** */ public void setLastSeen(long lastSeen) { this.lastSeen = lastSeen; } /** * Get the maximum concurrent tasks for this node. (This applies * per type of task - a node with maxTasks==1 will run up to 1 map * and 1 reduce concurrently). * @return maximum tasks this node supports */ public int getMaxMapTasks() { return maxMapTasks; } public int getMaxReduceTasks() { return maxReduceTasks; } /** * Return the {@link ResourceStatus} object configured with this * status. * * @return the resource status */ public ResourceStatus getResourceStatus() { return resStatus; } /////////////////////////////////////////// // Writable /////////////////////////////////////////// public void write(DataOutput out) throws IOException { UTF8.writeString(out, trackerName); UTF8.writeString(out, host); out.writeInt(httpPort); out.writeInt(failures); out.writeInt(maxMapTasks); out.writeInt(maxReduceTasks); resStatus.write(out); out.writeInt(taskReports.size()); for (TaskStatus taskStatus : taskReports) { TaskStatus.writeTaskStatus(out, taskStatus); } } public void readFields(DataInput in) throws IOException { this.trackerName = UTF8.readString(in); this.host = UTF8.readString(in); this.httpPort = in.readInt(); this.failures = in.readInt(); this.maxMapTasks = in.readInt(); this.maxReduceTasks = in.readInt(); resStatus.readFields(in); taskReports.clear(); int numTasks = in.readInt(); for (int i = 0; i < numTasks; i++) { taskReports.add(TaskStatus.readTaskStatus(in)); } } }
{ "content_hash": "54a82970fe9e2379bd337b5debf79a86", "timestamp": "", "source": "github", "line_count": 338, "max_line_length": 80, "avg_line_length": 27.532544378698226, "alnum_prop": 0.6303460133247367, "repo_name": "ryanobjc/hadoop-cloudera", "id": "3b5efdeeee0a1d9f775c8f960b2b8238aebe44f1", "size": "10112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mapred/org/apache/hadoop/mapred/TaskTrackerStatus.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309764" }, { "name": "C++", "bytes": "383846" }, { "name": "Java", "bytes": "12736305" }, { "name": "JavaScript", "bytes": "60544" }, { "name": "Objective-C", "bytes": "112020" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "149888" }, { "name": "Python", "bytes": "1162926" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "1137904" }, { "name": "Smalltalk", "bytes": "56562" } ], "symlink_target": "" }
ο»Ώusing System.Collections; using System.Collections.Generic; using UnityEngine; public class RockBandAudienceMember : MonoBehaviour { #pragma warning disable 0649 //Serialized Fields [SerializeField] private AnimationCurve hopCurve; [SerializeField] private Vector2 hopHeightRandomBounds, hopDurationRandomBounds, hopWaitRandomBounds, flipCooldownBounds; [SerializeField] private SpriteRenderer spriteRenderer; [SerializeField] private Sprite[] sprites; [SerializeField] private Sprite failSprite; #pragma warning restore 0649 private Vector3 startPosition; private float hopStartTime, hopHeight, hopWait, hopDuration, flipCooldown; private int victoryStatus = 0; void Start() { startPosition = transform.position; resetHop(); hopStartTime = Time.time - Random.Range(0f, hopDuration + hopWait); updateHop(); spriteRenderer.sprite = sprites[Random.Range(0, sprites.Length)]; spriteRenderer.sortingOrder += getNumberFromName(); if (MathHelper.randomBool()) flip(); resetFlip(); } void resetHop() { if (victoryStatus == -1) hopHeightRandomBounds = Vector2.zero; hopStartTime = Time.time; hopHeight = MathHelper.randomRangeFromVector(hopHeightRandomBounds); hopWait = MathHelper.randomRangeFromVector(hopWaitRandomBounds); hopDuration = MathHelper.randomRangeFromVector(hopDurationRandomBounds); } void resetFlip() { flip(); flipCooldown = MathHelper.randomRangeFromVector(flipCooldownBounds); } void Update() { updateHop(); updateFlip(); if (victoryStatus == 0) checkVictoryStatus(); } void updateHop() { float timeSinceHopStart = Time.time - hopStartTime, height = timeSinceHopStart <= hopDuration ? (hopCurve.Evaluate(timeSinceHopStart / hopDuration) * hopHeight) : 0f; transform.position = startPosition + (Vector3.up * height); if (timeSinceHopStart > hopDuration + hopWait) resetHop(); } void updateFlip() { flipCooldown -= Time.deltaTime; if (flipCooldown <= 0f) resetFlip(); } void checkVictoryStatus() { if (MicrogameController.instance.getVictoryDetermined()) { if (MicrogameController.instance.getVictory()) { hopWaitRandomBounds = Vector2.zero; hopWait = 0f; hopHeightRandomBounds *= 1.5f; flipCooldownBounds /= 2f; flipCooldown /= 2f; //if (Time.time - hopStartTime >= hopDuration) // resetHop(); victoryStatus = 1; } else { float brightness = .5f; spriteRenderer.color = new Color(brightness, brightness, brightness, 1f); if (Time.time - hopStartTime <= hopDuration) { hopHeight = transform.position.y - startPosition.y; hopStartTime = Time.time - (hopDuration / 2f); } else { enabled = false; } flipCooldown = float.PositiveInfinity; victoryStatus = -1; spriteRenderer.sprite = failSprite; } } } int getNumberFromName() { if (!name.Contains(")")) return 0; return int.Parse(name.Split('(')[1].Split(')')[0]); } void flip() { transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); } }
{ "content_hash": "aed1eaedff87dbab8ef9838ca86d0b38", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 126, "avg_line_length": 29.00769230769231, "alnum_prop": 0.5865818085388491, "repo_name": "plrusek/NitoriWare", "id": "49cc1a1bf9a56978940f667d42f27b5a26790151", "size": "3773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Resources/Microgames/RockBand/Scripts/RockBandAudienceMember.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "462040" }, { "name": "ShaderLab", "bytes": "3449" } ], "symlink_target": "" }
class IntVarSL : public IntVar { vec<int> values; // values that the var can take in ascending order IntVarEL *el; // transform value into index, type determines return value when a hole is encountered // 0: round down, 1: round up, 2: -1 int transform(int v, int type); public: IntVarSL(const IntVar& other, vec<int>& values); void attach(Propagator *p, int pos, int eflags); VarType getType() { return INT_VAR_SL; } // t = 0: [x != v], t = 1: [x = v], t = 2: [x >= v], t = 3: [x <= v] Lit getLit(int64_t v, int t); Lit getMinLit() const { return el->getMinLit(); } Lit getMaxLit() const { return el->getMaxLit(); } Lit getValLit() const { return el->getValLit(); } Lit getFMinLit(int64_t v) { return so.finesse ? ~el->getLit(transform(v, 0), 2) : el->getMinLit(); } Lit getFMaxLit(int64_t v) { return so.finesse ? ~el->getLit(transform(v, 1), 3) : el->getMaxLit(); } bool setMin(int64_t v, Reason r = NULL, bool channel = true); bool setMax(int64_t v, Reason r = NULL, bool channel = true); bool setVal(int64_t v, Reason r = NULL, bool channel = true); bool remVal(int64_t v, Reason r = NULL, bool channel = true); void channel(int val, int val_type, int sign); void debug(); }; #endif
{ "content_hash": "2644339b26c75c2322742159de1b1403", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 101, "avg_line_length": 34.138888888888886, "alnum_prop": 0.6468673718470301, "repo_name": "chuffed/chuffed", "id": "25f41367cc02622efe788e432aeb6680c74f2226", "size": "1349", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chuffed/vars/int-var-sl.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6163" }, { "name": "C++", "bytes": "1291431" }, { "name": "CMake", "bytes": "14462" }, { "name": "Makefile", "bytes": "5979" } ], "symlink_target": "" }
package define import ( "net/http" "github.com/sacloud/libsacloud/v2/internal/define/names" "github.com/sacloud/libsacloud/v2/internal/define/ops" "github.com/sacloud/libsacloud/v2/internal/dsl" "github.com/sacloud/libsacloud/v2/internal/dsl/meta" "github.com/sacloud/libsacloud/v2/sacloud/naked" "github.com/sacloud/libsacloud/v2/sacloud/types" ) const ( diskAPIName = "Disk" diskAPIPathName = "disk" ) var diskAPI = &dsl.Resource{ Name: diskAPIName, PathName: diskAPIPathName, PathSuffix: dsl.CloudAPISuffix, Operations: dsl.Operations{ // find ops.Find(diskAPIName, diskNakedType, findParameter, diskModel), // create { ResourceName: diskAPIName, Name: "Create", PathFormat: dsl.DefaultPathFormat, Method: http.MethodPost, RequestEnvelope: dsl.RequestEnvelope( &dsl.EnvelopePayloadDesc{ Type: diskNakedType, Name: "Disk", }, &dsl.EnvelopePayloadDesc{ Type: diskDistantFromType, Name: "DistantFrom", }, ), Arguments: dsl.Arguments{ { Name: "createParam", MapConvTag: "Disk,recursive", Type: diskCreateParam, }, { Name: "distantFrom", MapConvTag: "DistantFrom", Type: diskDistantFromType, }, }, ResponseEnvelope: dsl.ResponseEnvelope(&dsl.EnvelopePayloadDesc{ Type: diskNakedType, Name: "Disk", }), Results: dsl.Results{ { SourceField: "Disk", DestField: diskModel.Name, IsPlural: false, Model: diskModel, }, }, }, // config(DiskEdit) { ResourceName: diskAPIName, Name: "Config", PathFormat: dsl.IDAndSuffixPathFormat("config"), Method: http.MethodPut, RequestEnvelope: dsl.RequestEnvelopeFromModel(diskEditParam), Arguments: dsl.Arguments{ dsl.ArgumentID, dsl.PassthroughModelArgument("edit", diskEditParam), }, }, // create with config(DiskEdit) { ResourceName: diskAPIName, Name: "CreateWithConfig", PathFormat: dsl.DefaultPathFormat, Method: http.MethodPost, RequestEnvelope: dsl.RequestEnvelope( &dsl.EnvelopePayloadDesc{ Type: diskNakedType, Name: "Disk", }, &dsl.EnvelopePayloadDesc{ Type: diskEditNakedType, Name: "Config", }, &dsl.EnvelopePayloadDesc{ Type: meta.TypeFlag, Name: "BootAtAvailable", }, &dsl.EnvelopePayloadDesc{ Type: diskDistantFromType, Name: "DistantFrom", }, ), ResponseEnvelope: dsl.ResponseEnvelope(&dsl.EnvelopePayloadDesc{ Type: diskNakedType, Name: "Disk", }), Arguments: dsl.Arguments{ { Name: "createParam", MapConvTag: "Disk,recursive", Type: diskCreateParam, }, { Name: "editParam", MapConvTag: "Config,recursive", Type: diskEditParam, }, { Name: "bootAtAvailable", Type: meta.TypeFlag, MapConvTag: "BootAtAvailable", }, { Name: "distantFrom", Type: diskDistantFromType, MapConvTag: "DistantFrom", }, }, Results: dsl.Results{ { SourceField: "Disk", DestField: diskModel.Name, IsPlural: false, Model: diskModel, }, }, }, // resize partition { ResourceName: diskAPIName, Name: "ResizePartition", PathFormat: dsl.IDAndSuffixPathFormat("resize-partition"), Method: http.MethodPut, RequestEnvelope: dsl.RequestEnvelope( &dsl.EnvelopePayloadDesc{ Type: meta.TypeFlag, Name: "Background", }, ), Arguments: dsl.Arguments{ dsl.ArgumentID, dsl.PassthroughModelArgument("param", &dsl.Model{ Name: "DiskResizePartitionRequest", Fields: []*dsl.FieldDesc{ fields.Def("Background", meta.TypeFlag), }, NakedType: meta.Static(naked.ResizePartitionRequest{}), }), }, }, // connect to server ops.WithIDAction(diskAPIName, "ConnectToServer", http.MethodPut, "to/server/{{.serverID}}", &dsl.Argument{ Name: "serverID", Type: meta.TypeID, }, ), // disconnect from server ops.WithIDAction(diskAPIName, "DisconnectFromServer", http.MethodDelete, "to/server"), // read ops.Read(diskAPIName, diskNakedType, diskModel), // update ops.Update(diskAPIName, diskNakedType, diskUpdateParam, diskModel), // delete ops.Delete(diskAPIName), // monitor ops.Monitor(diskAPIName, monitorParameter, monitors.diskModel()), ops.MonitorChild(diskAPIName, "Disk", "", monitorParameter, monitors.diskModel()), }, } var ( diskNakedType = meta.Static(naked.Disk{}) diskEditNakedType = meta.Static(naked.DiskEdit{}) diskDistantFromType = meta.Static([]types.ID{}) diskModel = &dsl.Model{ Name: diskAPIName, NakedType: diskNakedType, Fields: []*dsl.FieldDesc{ fields.ID(), fields.Name(), fields.Description(), fields.Tags(), fields.Availability(), fields.DiskConnection(), fields.DiskConnectionOrder(), fields.DiskReinstallCount(), fields.Def("JobStatus", models.migrationJobStatus()), fields.SizeMB(), fields.MigratedMB(), fields.DiskPlanID(), fields.DiskPlanName(), fields.DiskPlanStorageClass(), fields.SourceDiskID(), fields.SourceDiskAvailability(), fields.SourceArchiveID(), fields.SourceArchiveAvailability(), fields.BundleInfo(), fields.Storage(), fields.ServerID(), fields.ServerName(), fields.IconID(), fields.CreatedAt(), fields.ModifiedAt(), }, } diskCreateParam = &dsl.Model{ Name: names.CreateParameterName(diskAPIName), NakedType: diskNakedType, Fields: []*dsl.FieldDesc{ fields.DiskPlanID(), fields.DiskConnection(), fields.SourceDiskID(), fields.SourceArchiveID(), fields.ServerID(), fields.SizeMB(), fields.Name(), fields.Description(), fields.Tags(), fields.IconID(), }, } diskUpdateParam = &dsl.Model{ Name: names.UpdateParameterName(diskAPIName), NakedType: diskNakedType, Fields: []*dsl.FieldDesc{ fields.Name(), fields.Description(), fields.Tags(), fields.IconID(), fields.DiskConnection(), }, } diskEditParam = models.diskEdit() )
{ "content_hash": "6c91cee90c0a28f425e117075a869a65", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 93, "avg_line_length": 23.961389961389962, "alnum_prop": 0.6458266194005801, "repo_name": "sacloud/libsacloud", "id": "ca8445fbf53d3a964b5fb54040a0eaebd71623b0", "size": "6812", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "v2/internal/define/disk.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "792" }, { "name": "Go", "bytes": "5822818" }, { "name": "Makefile", "bytes": "2248" } ], "symlink_target": "" }
set -o errexit set -o pipefail set -o nounset root_dir="$(git rev-parse --show-toplevel)" cd "${root_dir}" if [ "$#" -ne 1 ] ; then echo "$0 supports exactly 1 argument - <hubble_version>" exit 1 fi hubble_version="${1}" # this is a simple array that assumes the order of the loop; # it's not an associative array because this script needs to # work on any version of bash, and (most notably) macOS ships # an old version that doesn't support associative arrays hubble_sha256=() for arch in amd64 arm64 ; do tmpout="$(mktemp)" curl --fail --show-error --silent --location \ "https://github.com/cilium/hubble/releases/download/${hubble_version}/hubble-linux-${arch}.tar.gz.sha256sum" \ --output "${tmpout}" read -ra sha256 < "${tmpout}" rm -f "${tmpout}" hubble_sha256+=("${sha256[0]}") done cat > "${root_dir}/images/cilium/hubble-version.sh" << EOF # Code generated by images/scripts/update-hubble-version.sh; DO NOT EDIT. hubble_version="${hubble_version}" declare -A hubble_sha256 hubble_sha256[amd64]="${hubble_sha256[0]}" hubble_sha256[arm64]="${hubble_sha256[1]}" EOF
{ "content_hash": "1e657d64da56f1057af1de22b3868818", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 114, "avg_line_length": 29.026315789473685, "alnum_prop": 0.6890299184043518, "repo_name": "tgraf/cilium", "id": "2c58c541cb20eb8c4cfbf704a56669592b932b40", "size": "1195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "images/scripts/update-hubble-version.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1109708" }, { "name": "C++", "bytes": "6557" }, { "name": "Dockerfile", "bytes": "27333" }, { "name": "Go", "bytes": "9930421" }, { "name": "HCL", "bytes": "1127" }, { "name": "Makefile", "bytes": "72210" }, { "name": "Mustache", "bytes": "1457" }, { "name": "Python", "bytes": "11099" }, { "name": "Ruby", "bytes": "392" }, { "name": "Shell", "bytes": "369722" }, { "name": "SmPL", "bytes": "6540" }, { "name": "Smarty", "bytes": "10858" }, { "name": "TeX", "bytes": "416" }, { "name": "sed", "bytes": "1336" } ], "symlink_target": "" }
module Stupidedi module Versions module ThirtyTen module ElementTypes Nn = Common::ElementTypes::Nn FixnumVal = Common::ElementTypes::FixnumVal end end end end
{ "content_hash": "13e88008f6f089d31cc7f2f9834ae74a", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 51, "avg_line_length": 20.7, "alnum_prop": 0.6376811594202898, "repo_name": "kputnam/stupidedi", "id": "6ca14167b1c8bc074e65035dd00648b2694e7f2f", "size": "237", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/stupidedi/versions/003010/element_types/nn.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "1322" }, { "name": "Ruby", "bytes": "5668403" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.wso2.carbon.storagemgt</groupId> <artifactId>carbon-storage-management</artifactId> <version>4.3.5-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <groupId>org.wso2.carbon.storagemgt</groupId> <artifactId>rss-manager</artifactId> <packaging>pom</packaging> <name>WSO2 Carbon - RSS Manager Component</name> <url>http://wso2.org</url> <modules> <module>org.wso2.carbon.rssmanager.common</module> <module>org.wso2.carbon.rssmanager.core</module> <module>org.wso2.carbon.rssmanager.ui</module> <module>org.wso2.carbon.rssmanager.data.mgt</module> </modules> </project>
{ "content_hash": "329aa6edd9169bf08836d215f2d6814b", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 204, "avg_line_length": 39.92, "alnum_prop": 0.6713426853707415, "repo_name": "wso2/carbon-storage-management", "id": "eba61d787257488f411072c10f8c5c1dcd69435f", "size": "998", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/rss-manager/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6360" }, { "name": "Java", "bytes": "1306743" }, { "name": "JavaScript", "bytes": "54851" }, { "name": "PLSQL", "bytes": "8225" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_92) on Wed Jul 27 21:19:24 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class net.sourceforge.pmd.lang.vm.ast.ASTTrue (PMD 5.5.1 API)</title> <meta name="date" content="2016-07-27"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class net.sourceforge.pmd.lang.vm.ast.ASTTrue (PMD 5.5.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/vm/ast/class-use/ASTTrue.html" target="_top">Frames</a></li> <li><a href="ASTTrue.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class net.sourceforge.pmd.lang.vm.ast.ASTTrue" class="title">Uses of Class<br>net.sourceforge.pmd.lang.vm.ast.ASTTrue</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#net.sourceforge.pmd.lang.vm.ast">net.sourceforge.pmd.lang.vm.ast</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#net.sourceforge.pmd.lang.vm.rule">net.sourceforge.pmd.lang.vm.rule</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="net.sourceforge.pmd.lang.vm.ast"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a> in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/package-summary.html">net.sourceforge.pmd.lang.vm.ast</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/package-summary.html">net.sourceforge.pmd.lang.vm.ast</a> with parameters of type <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="typeNameLabel">VmParserVisitor.</span><code><span class="memberNameLink"><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/VmParserVisitor.html#visit-net.sourceforge.pmd.lang.vm.ast.ASTTrue-java.lang.Object-">visit</a></span>(<a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a>&nbsp;node, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;data)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="typeNameLabel">VmParserVisitorAdapter.</span><code><span class="memberNameLink"><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/VmParserVisitorAdapter.html#visit-net.sourceforge.pmd.lang.vm.ast.ASTTrue-java.lang.Object-">visit</a></span>(<a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a>&nbsp;node, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;data)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="net.sourceforge.pmd.lang.vm.rule"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a> in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/rule/package-summary.html">net.sourceforge.pmd.lang.vm.rule</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/rule/package-summary.html">net.sourceforge.pmd.lang.vm.rule</a> with parameters of type <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractVmRule.</span><code><span class="memberNameLink"><a href="../../../../../../../net/sourceforge/pmd/lang/vm/rule/AbstractVmRule.html#visit-net.sourceforge.pmd.lang.vm.ast.ASTTrue-java.lang.Object-">visit</a></span>(<a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTTrue</a>&nbsp;node, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;data)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTTrue.html" title="class in net.sourceforge.pmd.lang.vm.ast">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/vm/ast/class-use/ASTTrue.html" target="_top">Frames</a></li> <li><a href="ASTTrue.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2002&#x2013;2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "1eced6772c55baf9c08edbc3d8b6cf1d", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 432, "avg_line_length": 51.49230769230769, "alnum_prop": 0.6426650731998805, "repo_name": "jasonwee/videoOnCloud", "id": "68754761a996863757635603ddb8f42e3a0d9060", "size": "10041", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pmd/pmd-doc-5.5.1/apidocs/net/sourceforge/pmd/lang/vm/ast/class-use/ASTTrue.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "116270" }, { "name": "C", "bytes": "2209717" }, { "name": "C++", "bytes": "375267" }, { "name": "CSS", "bytes": "1134648" }, { "name": "Dockerfile", "bytes": "1656" }, { "name": "HTML", "bytes": "306558398" }, { "name": "Java", "bytes": "1465506" }, { "name": "JavaScript", "bytes": "9028509" }, { "name": "Jupyter Notebook", "bytes": "30907" }, { "name": "Less", "bytes": "107003" }, { "name": "PHP", "bytes": "856" }, { "name": "PowerShell", "bytes": "77807" }, { "name": "Pug", "bytes": "2968" }, { "name": "Python", "bytes": "1001861" }, { "name": "R", "bytes": "7390" }, { "name": "Roff", "bytes": "3553" }, { "name": "Shell", "bytes": "206191" }, { "name": "Thrift", "bytes": "80564" }, { "name": "XSLT", "bytes": "4740" } ], "symlink_target": "" }
<?php namespace Loct\Pinger\Notifier; /** * NotifierInterface is the interface implemented by all notifier classes. * * @author herloct <herloct@gmail.com> */ interface NotifierInterface { /** * Notify all recipients. * * @param array $pingResults Ping results * @return void */ public function notify(array $pingResults); }
{ "content_hash": "bad73104ccc7d9e2e7f350e6253ab37d", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 74, "avg_line_length": 20.166666666666668, "alnum_prop": 0.6694214876033058, "repo_name": "herloct/pinger", "id": "ccb3dfbfc1d3be9f319c9574032eccc1be6c6a53", "size": "363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Loct/Pinger/Notifier/NotifierInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "16967" } ], "symlink_target": "" }
(function () { 'use strict'; angular.module('core') .directive('getAction', getAction); getAction.$inject = ['$filter']; function getAction($filter) { var directive = { restrict: 'A', replace: true, scope: { getAction: '=getAction' }, link: link }; return directive; function link(scope, element) { scope.$watch(function() { return element.html(); }, function () { console.log(getAction(element.text())); element.html(getAction(element.text())); }); } function getAction(char) { var $translate = $filter('translate'); switch (char) { case 'C': return $translate('Created'); case 'U': return $translate('Updated'); case 'D': return $translate('Deleted'); } } } }());
{ "content_hash": "273c6ae4dba8c096d6de5496d6c914b7", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 48, "avg_line_length": 20.162790697674417, "alnum_prop": 0.5190311418685121, "repo_name": "johnexp/bproject", "id": "772f0642083a218937164b5ea560efb427240123", "size": "867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/core/client/directives/get-action.client.directive.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22043" }, { "name": "HTML", "bytes": "87455" }, { "name": "JavaScript", "bytes": "488324" }, { "name": "Shell", "bytes": "685" } ], "symlink_target": "" }
/*** ESSENTIAL STYLES ***/ .sf-menu, .sf-menu * { margin: 0; padding: 0; list-style: none; } .sf-menu { line-height: 1.0; } .sf-menu ul { position: absolute; top: -999em; width: 10em; /* left offset of submenus need to match (see below) */ } .sf-menu ul li { width: 100%; } .sf-menu li:hover { visibility: inherit; /* fixes IE7 'sticky bug' */ } .sf-menu li { float: left; position: relative; } .sf-menu a { display: block; position: relative; } .sf-menu li:hover ul, .sf-menu li.sfHover ul { left: 0; top: 40px; /* match top ul list item height */ z-index: 99; } ul.sf-menu li:hover li ul, ul.sf-menu li.sfHover li ul { top: -999em; } ul.sf-menu li li:hover ul, ul.sf-menu li li.sfHover ul { left: 10em; /* match ul width */ top: 0; } ul.sf-menu li li:hover li ul, ul.sf-menu li li.sfHover li ul { top: -999em; } ul.sf-menu li li li:hover ul, ul.sf-menu li li li.sfHover ul { left: 10em; /* match ul width */ top: 0; } /*** DEMO SKIN ***/ .sf-menu { float: left; margin-bottom: 1em; } .sf-menu a { padding: .75em 1em; text-decoration:none; } .sf-menu a, .sf-menu a:visited { /* visited pseudo selector so IE6 applies text colour*/ color: #777; } .sf-menu a:hover { color: #222; } .sf-menu li { background: transparent; } .sf-menu li li { background: url('../images/sf-menu-bg.png') no-repeat 0 100%; } .sf-menu li:hover, .sf-menu li.sfHover, .sf-menu a:focus, .sf-menu a:hover, .sf-menu a:active { outline: 0; } /*** arrows **/ .sf-menu a.sf-with-ul { padding-right: 2.25em; min-width: 1px; /* trigger IE7 hasLayout so spans position accurately */ } .sf-sub-indicator, .top_bg_color .sf-sub-indicator { position: absolute !important; display: block !important; right: 10px !important; top: 1.05em !important; /* IE6 only */ width: 10px !important; height: 10px !important; text-indent: -999em !important; overflow: hidden !important; } /* indicator image for light background */ .sf-sub-indicator { background: url('../images/auto-arrows.png') no-repeat -10px -100px !important; /* 8-bit indexed alpha png. IE6 gets solid image only */ } /* indicator image for dark background */ .top-bg-color-dark .sf-sub-indicator { background: url('../images/auto-arrows.png') no-repeat -30px -100px !important; /* 8-bit indexed alpha png. IE6 gets solid image only */ } a > .sf-sub-indicator { /* give all except IE6 the correct values */ top: .8em !important; background-position: 0 -100px !important; /* use translucent arrow for modern browsers*/ } /* hovers for light background */ a:focus > .sf-sub-indicator, a:hover > .sf-sub-indicator, a:active > .sf-sub-indicator, li:hover > a > .sf-sub-indicator, li.sfHover > a > .sf-sub-indicator { background-position: -10px -100px !important; /* arrow hovers for modern browsers*/ } /* hovers for dark background */ .top-bg-color-dark a:focus > .sf-sub-indicator, .top-bg-color-dark a:hover > .sf-sub-indicator, .top-bg-color-dark a:active > .sf-sub-indicator, .top-bg-color-dark li:hover > a > .sf-sub-indicator, .top-bg-color-dark li.sfHover > a > .sf-sub-indicator { background-position: -40px -100px !important; /* arrow hovers for modern browsers*/ } /* point right for anchors in subs */ .sf-menu ul .sf-sub-indicator { background-position: -10px 0 !important; } .sf-menu ul a > .sf-sub-indicator { background-position: 0 0 !important; } /* apply hovers to modern browsers */ .sf-menu ul a:focus > .sf-sub-indicator, .sf-menu ul a:hover > .sf-sub-indicator, .sf-menu ul a:active > .sf-sub-indicator, .sf-menu ul li:hover > a > .sf-sub-indicator, .sf-menu ul li.sfHover > a > .sf-sub-indicator { background-position: -10px 0 !important; /* arrow hovers for modern browsers*/ } /*** shadows for all but IE6 ***/ .sf-shadow ul { -moz-box-shadow: 1px 1px 4px #555; -webkit-box-shadow: 1px 1px 4px #555; box-shadow: 1px 1px 4px #555; } .sf-shadow ul.sf-shadow-off { background: transparent; }
{ "content_hash": "ab923c4ccecf7f6d0149c25fb5ce2ee5", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 138, "avg_line_length": 27.15753424657534, "alnum_prop": 0.6607818411097099, "repo_name": "oceanmatters/static-site", "id": "4438a4ee926f65be9d16e84140864c168bf93a67", "size": "3965", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "wp-content/themes/u-design/scripts/superfish-1.4.8/css/superfish-ver=1.0.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "94633" }, { "name": "HTML", "bytes": "5289143" }, { "name": "JavaScript", "bytes": "16228" }, { "name": "PHP", "bytes": "5926" } ], "symlink_target": "" }
public class Foo extends Bar { public Foo() {} public int foo() { return field; } }
{ "content_hash": "faddcc72fb7f63f844bf48b2385a16f8", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 30, "avg_line_length": 14.833333333333334, "alnum_prop": 0.6292134831460674, "repo_name": "gregwym/joos-compiler-java", "id": "3add76ab999833e3638211c78542a52914fdce17", "size": "89", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "testcases/a2/J1_implicitsuper/Foo.java", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "6846" }, { "name": "Java", "bytes": "802860" }, { "name": "Shell", "bytes": "141" } ], "symlink_target": "" }
<?php namespace Eightfold\Html\Elements\Embedded; use Eightfold\Html\Elements\HtmlElement; use Eightfold\Html\Elements\HtmlElementInterface; use Eightfold\Html\Data\Elements; use Eightfold\Html\Data\AriaRoles; use Eightfold\Html\Data\Attributes\Content; /** * @version 1.0.0 * * Area * * @todo There are a lot of conditions related to areas. * */ class Area extends HtmlElement implements HtmlElementInterface { static public function elementName(): string { return Elements::area()[0]; } static public function categories(): array { return array_merge( Elements::flow(), Elements::phrasing() ); } static public function contexts(): array { // TODO: Where phrasing content is expected, but only if there is a map // element ancestor or a template element ancestor. return Elements::phrasing(); } static public function optionalAttributes(): array { return array_merge( parent::optionalAriaAttributes(), Content::alt(), Content::coords(), Content::download(), Content::href(), Content::hreflang(), Content::rel(), Content::shape(), Content::target(), Content::type() ); } static public function defaultAriaRole(): string { return 'link'; } }
{ "content_hash": "3ed486587004340a5cd3f9331e9c3dab", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 80, "avg_line_length": 23.063492063492063, "alnum_prop": 0.591878871300757, "repo_name": "8fold/html5-generator-php", "id": "dfab958bcb677789824c1abfe9be86fb7f12163a", "size": "1453", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Elements/Embedded/Area.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "337474" } ], "symlink_target": "" }
package org.eigenbase.rex; /** * A <code>RexPattern</code> represents an expression with holes in it. The * {@link #match} method tests whether a given expression matches the pattern. * * @author jhyde * @version $Id$ * @since May 3, 2002 */ public interface RexPattern { //~ Methods ---------------------------------------------------------------- /** * Calls <code>action</code> for every combination of tokens for which this * pattern matches. */ void match( RexNode ptree, RexAction action); } // End RexPattern.java
{ "content_hash": "113e00414c7fa01a7a12bc1cdf5c72d4", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 80, "avg_line_length": 23, "alnum_prop": 0.5721739130434783, "repo_name": "julianhyde/luciddb", "id": "233444df69eb4a3322f652f6788c3941dc64a6b4", "size": "1373", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "farrago/src/org/eigenbase/rex/RexPattern.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
""" Utilities for providing backwards compatibility for the maxlength argument, which has been replaced by max_length. See ticket #2101. """ from warnings import warn def get_maxlength(self): return self.max_length def set_maxlength(self, value): self.max_length = value def legacy_maxlength(max_length, maxlength): """ Consolidates max_length and maxlength, providing backwards compatibilty for the legacy "maxlength" argument. If one of max_length or maxlength is given, then that value is returned. If both are given, a TypeError is raised. If maxlength is used at all, a deprecation warning is issued. """ if maxlength is not None: warn("maxlength is deprecated. Use max_length instead.", DeprecationWarning, stacklevel=3) if max_length is not None: raise TypeError("Field cannot take both the max_length argument and the legacy maxlength argument.") max_length = maxlength return max_length def remove_maxlength(func): """ A decorator to be used on a class's __init__ that provides backwards compatibilty for the legacy "maxlength" keyword argument, i.e. name = models.CharField(maxlength=20) It does this by changing the passed "maxlength" keyword argument (if it exists) into a "max_length" keyword argument. """ def inner(self, *args, **kwargs): max_length = kwargs.get('max_length', None) # pop maxlength because we don't want this going to __init__. maxlength = kwargs.pop('maxlength', None) max_length = legacy_maxlength(max_length, maxlength) # Only set the max_length keyword argument if we got a value back. if max_length is not None: kwargs['max_length'] = max_length func(self, *args, **kwargs) return inner # This metaclass is used in two places, and should be removed when legacy # support for maxlength is dropped. # * oldforms.FormField # * db.models.fields.Field class LegacyMaxlength(type): """ Metaclass for providing backwards compatibility support for the "maxlength" keyword argument. """ def __init__(cls, name, bases, attrs): super(LegacyMaxlength, cls).__init__(name, bases, attrs) # Decorate the class's __init__ to remove any maxlength keyword. cls.__init__ = remove_maxlength(cls.__init__) # Support accessing and setting to the legacy maxlength attribute. cls.maxlength = property(get_maxlength, set_maxlength)
{ "content_hash": "580ab3cea26eae8ec2a9267e2c262e75", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 112, "avg_line_length": 38.53846153846154, "alnum_prop": 0.6838323353293413, "repo_name": "diofeher/django-nfa", "id": "a616541f854c66a7a8d531f523b7f8a5a034becb", "size": "2505", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "build/lib/django/utils/maxlength.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "66105" }, { "name": "Python", "bytes": "5174003" }, { "name": "Shell", "bytes": "804" } ], "symlink_target": "" }
(function() { module.exports = { k: "__iced_k", k_noop: "__iced_k_noop", param: "__iced_p_", ns: "iced", runtime: "runtime", Deferrals: "Deferrals", deferrals: "__iced_deferrals", fulfill: "_fulfill", b_while: "_break", t_while: "_while", c_while: "_continue", n_while: "_next", n_arg: "__iced_next_arg", defer_method: "defer", slot: "__slot", assign_fn: "assign_fn", autocb: "autocb", retslot: "ret", trace: "__iced_trace", passed_deferral: "__iced_passed_deferral", findDeferral: "findDeferral", lineno: "lineno", parent: "parent", filename: "filename", funcname: "funcname", catchExceptions: 'catchExceptions', runtime_modes: ["node", "inline", "window", "none", "browserify", "interp"], trampoline: "trampoline", context: "context", defer_arg: "__iced_defer_", iterator: "__iced_it", await_exit: "await_exit" }; }).call(this);
{ "content_hash": "7d282e8ec4af0a5f25dd276dfa61a3ce", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 80, "avg_line_length": 26.054054054054053, "alnum_prop": 0.5632780082987552, "repo_name": "maxtaco/iced-runtime-3", "id": "8d83e51d7ee0728a87af730475dbb383ea4c73cf", "size": "1005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/const.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CoffeeScript", "bytes": "10311" }, { "name": "Makefile", "bytes": "408" } ], "symlink_target": "" }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".Activities.FullScreenImageActivity$PlaceholderFragment"> <TextView android:id="@+id/section_label" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
{ "content_hash": "10b26f5e3acdca18b588e6d748286b39", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 76, "avg_line_length": 43, "alnum_prop": 0.7398255813953488, "repo_name": "regini/inSquare", "id": "674040a19e82e06ef1f86014b6a32c08ed4cb541", "size": "688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inSquareAndroid/app/src/main/res/layout/fragment_full_screen_image.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "14876" }, { "name": "Java", "bytes": "527086" }, { "name": "JavaScript", "bytes": "99697" }, { "name": "Objective-C", "bytes": "256886" }, { "name": "Ruby", "bytes": "423" }, { "name": "Swift", "bytes": "614561" } ], "symlink_target": "" }
function Memory() { if (!(this instanceof Memory)) return new Memory(); // Map from collection name -> doc name -> snapshot ({v:, type:, data:}) this.collections = {}; // Map from collection name -> doc name -> list of operations. Operations // don't store their version - instead their version is simply the index in // the list. this.ops = {}; this.closed = false; }; module.exports = Memory; Memory.prototype.close = function() {}; // Snapshot database API var clone = function(obj) { return obj === undefined ? undefined : JSON.parse(JSON.stringify(obj)); }; // Get the named document from the database. The callback is called with (err, // data). data may be null if the docuemnt has never been created in the // database. Memory.prototype.getSnapshot = function(cName, docName, callback) { var c = this.collections[cName]; // We need to clone the snapshot because at the moment LiveDB's validation // code assumes each call to getSnapshot returns a new object. callback(null, c ? clone(c[docName]) : null); }; Memory.prototype.writeSnapshot = function(cName, docName, snapshot, callback) { var c = this.collections[cName] = this.collections[cName] || {}; c[docName] = clone(snapshot); callback(); }; // This function is optional. // // - It makes it faster for dedicated indexes (like SOLR) to get a whole bunch // of complete documents to service queries. // - It can also improve reconnection time // // Its included here for demonstration purposes and so we can test our tests. // // requests is an object mapping collection name -> list of doc names for // documents that need to be fetched. // // The callback is called with (err, results) where results is a map from // collection name -> {docName:data for data that exists in the collection} // // Documents that have never been touched can be ommitted from the results. // Documents that have been created then later deleted must exist in the result // set, though only the version field needs to be returned. // // bulkFetch replaces getBulkSnapshots in livedb 0.2. Memory.prototype.bulkGetSnapshot = function(requests, callback) { var results = {}; for (var cName in requests) { var cResult = results[cName] = {}; var c = this.collections[cName]; if (!c) continue; var docNames = requests[cName]; for (var i = 0; i < docNames.length; i++) { var snapshot = c[docNames[i]]; if (snapshot) cResult[docNames[i]] = { type: snapshot.type, v: snapshot.v, m: clone(snapshot.m), data: clone(snapshot.data) }; } } callback(null, results); }; // Thats it; thats the whole snapshot database API. // Query support API. This is optional. It allows you to run queries against the data. // The memory database has a really simple (probably too simple) query // mechanism to get all documents in the collection. The query is just the // collection name. // Run the query itself. The query is ignored - we just return all documents in // the specified index (=collection). Memory.prototype.query = function(liveDb, index, query, options, callback) { //if(typeof index !== 'string') return callback('Invalid query'); var c = this.collections[index]; if (!c) return callback(null, []); var results = []; for (var docName in c) { var snapshot = c[docName]; if (snapshot.data !== undefined) results.push({v:snapshot.v, type:snapshot.type, docName:docName, data:snapshot.data}); } callback(null, results); }; // Queries can avoid a lot of CPU load by querying individual documents instead // of the whole collection. Memory.prototype.queryNeedsPollMode = function(index, query) { return false; }; Memory.prototype.queryDoc = function(liveDb, index, cName, docName, query, callback) { // console.log('queryDoc', cName, index); // We simply return whether or not the document is inside the specified index. if (index !== cName) return callback(); var c = this.collections[cName]; c[docName].docName = docName; // console.log(c && c[docName]); if (c && c[docName] && c[docName].data) callback(null, c && c[docName]); else callback(); }; // Operation log // Internal function. Memory.prototype._getOpLog = function(cName, docName) { var c = this.ops[cName]; if (!c) c = this.ops[cName] = {}; var ops = c[docName] if (!ops) ops = c[docName] = []; return ops; }; // This is used to store an operation. // // Its possible writeOp will be called multiple times with the same operation // (at the same version). In this case, the function can safely do nothing (or // overwrite the existing identical data). It MUST NOT change the version number. // // Its guaranteed that writeOp calls will be in order - that is, the database // will never be asked to store operation 10 before it has received operation // 9. It may receive operation 9 on a different server. // // opData looks like: // {v:version, op:... OR create:{optional data:..., type:...} OR del:true, [src:string], [seq:number], [meta:{...}]} // // callback should be called as callback(error) Memory.prototype.writeOp = function(cName, docName, opData, callback) { var opLog = this._getOpLog(cName, docName); // This should never actually happen unless there's bugs in livedb. (Or you // try to use this memory implementation with multiple frontend servers) if (opLog.length < opData.v - 1) return callback('Internal consistancy error - database missing parent version'); opLog[opData.v] = opData; callback(); }; // Get the current version of the document, which is one more than the version // number of the last operation the database stores. // // callback should be called as callback(error, version) Memory.prototype.getVersion = function(cName, docName, callback) { var opLog = this._getOpLog(cName, docName); callback(null, opLog.length); }; // Get operations between [start, end) noninclusively. (Ie, the range should // contain start but not end). // // If end is null, this function should return all operations from start onwards. // // The operations that getOps returns don't need to have a version: field. // The version will be inferred from the parameters if it is missing. // // Callback should be called as callback(error, [list of ops]); Memory.prototype.getOps = function(cName, docName, start, end, callback) { var opLog = this._getOpLog(cName, docName); if (end == null) end = opLog.length; callback(null, opLog.slice(start, end)); };
{ "content_hash": "1323bf993a412a86b4209ce18d495228", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 116, "avg_line_length": 32.05911330049261, "alnum_prop": 0.6940688383527965, "repo_name": "jclem/livedb", "id": "aeb96b1de808b5e4a9e4c66da3adf9de2a6d0e63", "size": "7528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/memory.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "94429" }, { "name": "JavaScript", "bytes": "111242" }, { "name": "Lua", "bytes": "4786" } ], "symlink_target": "" }
<div class="commune_descr limited"> <p> Marchastel est un village situé dans le département de Lozère en Languedoc-Roussillon. Elle totalisait 87 habitants en 2008.</p> <p>Si vous envisagez de demenager à Marchastel, vous pourrez facilement trouver une maison à vendre. </p> <p>À proximité de Marchastel sont positionnées géographiquement les communes de <a href="{{VLROOT}}/immobilier/recoules-daubrac_48123/">Recoules-d'Aubrac</a> localisée à 7&nbsp;km, 255 habitants, <a href="{{VLROOT}}/immobilier/buisson_48032/">Le&nbsp;Buisson</a> située à 10&nbsp;km, 207 habitants, <a href="{{VLROOT}}/immobilier/prinsuejols_48120/">Prinsuéjols</a> à 5&nbsp;km, 161 habitants, <a href="{{VLROOT}}/immobilier/sainte-colombe-de-peyre_48142/">Sainte-Colombe-de-Peyre</a> localisée à 11&nbsp;km, 235 habitants, <a href="{{VLROOT}}/immobilier/saint-laurent-de-muret_48165/">Saint-Laurent-de-Muret</a> à 9&nbsp;km, 169 habitants, <a href="{{VLROOT}}/immobilier/grandvals_48071/">Grandvals</a> à 11&nbsp;km, 84 habitants, entre autres. De plus, Marchastel est située à seulement 18&nbsp;km de <a href="{{VLROOT}}/immobilier/marvejols_48092/">Marvejols</a>.</p> <p>Le parc de logements, à Marchastel, était réparti en 2011 en deux appartements et 53 maisons soit un marché relativement équilibré.</p> </div>
{ "content_hash": "3cf2c63387f845b15dec8053d335741e", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 139, "avg_line_length": 77.05882352941177, "alnum_prop": 0.7442748091603053, "repo_name": "donaldinou/frontend", "id": "c1a1c6f65a8450b1078a64a413a180ade359f9e8", "size": "1337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Viteloge/CoreBundle/Resources/descriptions/48091.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "111338" }, { "name": "HTML", "bytes": "58634405" }, { "name": "JavaScript", "bytes": "88564" }, { "name": "PHP", "bytes": "841919" } ], "symlink_target": "" }
@implementation NSString (SZUrlEncode) - (NSString *)sz_urlEncode { return [self sz_urlEncodeUsingEncoding:NSUTF8StringEncoding]; } - (NSString *)sz_urlEncodeUsingEncoding:(NSStringEncoding)encoding { return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)self,NULL,(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)); } - (NSString *)sz_urlDecode { return [self sz_urlDecodeUsingEncoding:NSUTF8StringEncoding]; } - (NSString *)sz_urlDecodeUsingEncoding:(NSStringEncoding)encoding { return (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)self,CFSTR(""),CFStringConvertNSStringEncodingToEncoding(encoding)); } - (NSDictionary *)sz_dictionaryFromURLParameters { NSArray *pairs = [self componentsSeparatedByString:@"&"]; NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; for (NSString *pair in pairs) { NSArray *kv = [pair componentsSeparatedByString:@"="]; NSString *val = [[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [params setObject:val forKey:[kv objectAtIndex:0]]; } return params; } @end
{ "content_hash": "a2b2ff52999852461f87db7b2cc67c5a", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 113, "avg_line_length": 40, "alnum_prop": 0.7227272727272728, "repo_name": "chenshengzhi/SZCategories", "id": "b63dd22fa631d3c27e6cc5739ee2b22e1a81e6ca", "size": "1502", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SZCategories/Foundation/NSString/NSString+SZUrlEncode.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "160070" }, { "name": "Ruby", "bytes": "5196" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Collections.ObjectModel; namespace RCSIssues.ApiData.Areas.HelpPage.ModelDescriptions { public class EnumTypeModelDescription : ModelDescription { public EnumTypeModelDescription() { Values = new Collection<EnumValueDescription>(); } public Collection<EnumValueDescription> Values { get; private set; } } }
{ "content_hash": "3febe603c0ba5bdfe810024011ff4995", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 76, "avg_line_length": 27.4, "alnum_prop": 0.7104622871046229, "repo_name": "tazmanrising/RCSIssues.ApiData", "id": "1bde338e2e7e50300a7b0ac15228da086a22d6c0", "size": "411", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "RCSIssuescode.ApiData/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "222" }, { "name": "C#", "bytes": "232202" }, { "name": "CSS", "bytes": "163322" }, { "name": "HTML", "bytes": "6621" }, { "name": "JavaScript", "bytes": "1743093" }, { "name": "Pascal", "bytes": "130881" }, { "name": "PowerShell", "bytes": "105012" }, { "name": "Puppet", "bytes": "3202" } ], "symlink_target": "" }
package com.jasonette.seed.Helper; import android.content.Context; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Color; import android.graphics.Typeface; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.WindowManager; import android.widget.TextView; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.jasonette.seed.Core.JasonViewActivity; import com.jasonette.seed.Launcher.Launcher; import org.hjson.JsonValue; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import timber.log.Timber; public class JasonHelper { public static JSONObject style(JSONObject component, Context root_context) { JSONObject style = new JSONObject(); try { if (component.has("class")) { String style_class_string = component.getString("class"); String[] style_classes = style_class_string.split("\\s+"); for(int i = 0 ; i < style_classes.length ; i++){ JSONObject astyle = ((JasonViewActivity) root_context).model.jason.getJSONObject("$jason").getJSONObject("head").getJSONObject("styles").getJSONObject(style_classes[i]); Iterator iterator = astyle.keys(); String style_key; while (iterator.hasNext()) { style_key = (String) iterator.next(); style.put(style_key, astyle.get(style_key)); } } } } catch (Exception e){ Timber.w(e); } try { // iterate through inline style and overwrite if (component.has("style")) { JSONObject inline_style = component.getJSONObject("style"); Iterator iterator = inline_style.keys(); String style_key; while (iterator.hasNext()) { style_key = (String) iterator.next(); style.put(style_key, inline_style.get(style_key)); } } } catch (Exception e) { Timber.w(e); } return style; } public static JSONObject merge(JSONObject old, JSONObject add) { try { JSONObject stub = new JSONObject(old.toString()); Iterator<String> keysIterator = add.keys(); while (keysIterator.hasNext()) { String key = (String) keysIterator.next(); Object val = add.get(key); stub.put(key, val); } return stub; } catch (Exception e) { Timber.w(e); return new JSONObject(); } } public static void next(String type, JSONObject action, Object data, final JSONObject event, Context context) { try { if (action.has(type)) { Intent intent = new Intent(type); intent.putExtra("action", action.get(type).toString()); intent.putExtra("data", data.toString()); intent.putExtra("event", event.toString()); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } else { // Release everything and finish Intent intent = new Intent("call"); JSONObject unlock_action = new JSONObject(); unlock_action.put("type", "$unlock"); intent.putExtra("action", unlock_action.toString()); intent.putExtra("event", event.toString()); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } } catch (Exception e) { Timber.e(e); } } /** * Parse a string as either a JSON Object or Array. * * @param json * @return a JSONObject or JSONArray based on the Json string, * return an emptry JSONObject if json param is null or on parsing supplied json string. */ public static Object objectify(String json) { try { if (json == null) { return new JSONObject(); } if (json.trim().startsWith("[")) { // JSONArray return new JSONArray(json); } else if (json.trim().startsWith("{")) { return new JSONObject(json); } else { return new JSONObject(); } } catch (Exception e) { Timber.w(e, "error objectifying: %s", json); return new JSONObject(); } } public static ArrayList<JSONObject> toArrayList(JSONArray jsonArray) { ArrayList<JSONObject> list = new ArrayList<JSONObject>(); try { for (int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getJSONObject(i)); } } catch (Exception e) { Timber.w(e); } return list; } public static float ratio(String ratio) { String regex = "^[ ]*([0-9]+)[ ]*[:/][ ]*([0-9]+)[ ]*$"; Pattern pat = Pattern.compile(regex); Matcher m = pat.matcher(ratio); if (m.matches()) { Float w = Float.parseFloat(m.group(1)); Float h = Float.parseFloat(m.group(2)); return w/h; } else { return Float.parseFloat(ratio); } } public static float pixels(Context context, String size, String direction) { String regex_percent_and_pixels = "^([0-9.]+)%[ ]*([+-]?)[ ]*([0-9]+)$"; Pattern percent_pixels = Pattern.compile(regex_percent_and_pixels); Matcher m = percent_pixels.matcher(size); if (m.matches()) { Float percentage = Float.parseFloat(m.group(1)); String sign = m.group(2); Float pixels = Float.parseFloat(m.group(3)); pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pixels, context.getResources().getDisplayMetrics()); DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); windowmanager.getDefaultDisplay().getMetrics(displayMetrics); float percent_height; float percent_width; float s; if (direction.equalsIgnoreCase("vertical")) { int full = displayMetrics.heightPixels; percent_height = full * percentage / 100; s = percent_height; } else { int full = displayMetrics.widthPixels; percent_width = full * percentage / 100; s = percent_width; } if (sign.equalsIgnoreCase("+")) { s = s + pixels; } else { s = s - pixels; } return s; } else { String regex = "(\\d+)%"; Pattern percent = Pattern.compile(regex); m = percent.matcher(size); float s; if (m.matches()) { Float percentage = Float.parseFloat(m.group(1)); DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); windowmanager.getDefaultDisplay().getMetrics(displayMetrics); if (direction.equalsIgnoreCase("vertical")) { int full = displayMetrics.heightPixels; s = full * percentage / 100; } else { int full = displayMetrics.widthPixels; s = full * percentage / 100; } return s; } else { s = Float.parseFloat(size); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, s, context.getResources().getDisplayMetrics()); } } } public static int parse_color(String color_string) { Pattern rgb = Pattern.compile("rgb *\\( *([0-9]+), *([0-9]+), *([0-9]+) *\\)"); Pattern rgba = Pattern.compile("rgba *\\( *([0-9]+), *([0-9]+), *([0-9]+), *([0-9.]+) *\\)"); Matcher rgba_m = rgba.matcher(color_string); Matcher rgb_m = rgb.matcher(color_string); if (rgba_m.matches()) { float a = Float.valueOf(rgba_m.group(4)); int alpha = (int) Math.round(a * 255); String hex = Integer.toHexString(alpha).toUpperCase(); if (hex.length() == 1) hex = "0" + hex; hex = "0000" + hex; return Color.argb(Integer.parseInt(hex, 16), Integer.valueOf(rgba_m.group(1)), Integer.valueOf(rgba_m.group(2)), Integer.valueOf(rgba_m.group(3))); } else if (rgb_m.matches()) { return Color.rgb(Integer.valueOf(rgb_m.group(1)), Integer.valueOf(rgb_m.group(2)), Integer.valueOf(rgb_m.group(3))); } else { // Otherwise assume hex code return Color.parseColor(color_string); } } public static Typeface get_font(String font, Context context) { Typeface font_type = Typeface.createFromAsset(context.getAssets(), "fonts/" + font + ".ttf"); return font_type; } public static String read_file_scheme(String filename, Context context) throws IOException { filename = filename.replace("file://", "file/"); return read_file(filename, context); } public static String read_file(String filename, Context context) throws IOException { AssetManager assets = context.getAssets(); final InputStream inputStream = assets.open(filename); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); final StringBuilder stringBuilder = new StringBuilder(); boolean done = false; while (!done) { final String line = reader.readLine(); done = (line == null); if (line != null) { stringBuilder.append("\n"); stringBuilder.append(line); } } reader.close(); inputStream.close(); return stringBuilder.toString(); } public static Object read_json(String fn, Context context) {// throws IOException { // we're expecting a filename that looks like "file://..." String filename = fn.replace("file://", "file/"); String jr = null; Object ret; try { InputStream is = context.getAssets().open(filename); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String jsonString = JsonValue.readHjson(new String(buffer)).toString(); jr = new String(jsonString.getBytes(), "UTF-8"); if(jr.trim().startsWith("[")) { // array ret = new JSONArray(jr); } else if(jr.trim().startsWith("{")){ // object ret = new JSONObject(jr); } else { // string ret = jr; } } catch (Exception e) { Timber.w(e); return new JSONObject(); } return ret; } public static void permission_exception(String actionName, Context context) { try { Intent intent = new Intent("call"); JSONObject alert_action = new JSONObject(); alert_action.put("type", "$util.alert"); JSONObject options = new JSONObject(); options.put("title", "Turn on Permissions"); options.put("description", actionName + " requires additional permissions. Go to AndroidManifest.xml file and turn on the permission"); alert_action.put("options", options); intent.putExtra("action", alert_action.toString()); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } catch (Exception e) { Timber.w(e); } } public static byte[] readBytes(InputStream inputStream) throws IOException { // this dynamically extends to take the bytes you read ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); // this is storage overwritten on each iteration with bytes int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; // we need to know how may bytes were read to write them to the byteBuffer int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } // and then we can return your byte array. return byteBuffer.toByteArray(); } // dispatchIntent method // 1. triggers an external Intent // 2. attaches a callback with all the payload so that we can pick it up where we left off when the intent returns // the callback needs to specify the class name and the method name we wish to trigger after the intent returns public static void dispatchIntent(String name, JSONObject action, JSONObject data, JSONObject event, Context context, Intent intent, JSONObject handler) { // Generate unique identifier for return value // This will be used to name the handlers int requestCode; try { requestCode = Integer.parseInt(name); } catch (NumberFormatException e) { requestCode = -1; } try { // handler looks like this: /* { "class": [class name], "method": [method name], "options": { [options to preserve] } } */ JSONObject options = new JSONObject(); options.put("action", action); options.put("data", data); options.put("event", event); options.put("context", context); handler.put("options", options); ((Launcher) ((JasonViewActivity) context).getApplicationContext()).once(name, handler); } catch (Exception e) { Timber.w(e); } if (intent != null) { // Start the activity ((JasonViewActivity) context).startActivityForResult(intent, requestCode); } else { // if intent is null, // it means we are manually going to deal with opening a new Intent } } public static void dispatchIntent(JSONObject action, JSONObject data, JSONObject event, Context context, Intent intent, JSONObject handler) { dispatchIntent(String.valueOf((int) (System.currentTimeMillis() % 10000)), action, data, event, context, intent, handler); } public static void callback(JSONObject callback, String result, Context context) { ((Launcher) context.getApplicationContext()).callback(callback, result, (JasonViewActivity) context); } public static JSONObject preserve(JSONObject callback, JSONObject action, JSONObject data, JSONObject event, Context context) { try { JSONObject callback_options = new JSONObject(); callback_options.put("action", action); callback_options.put("data", data); callback_options.put("event", event); callback_options.put("context", context); callback.put("options", callback_options); return callback; } catch (Exception e) { Timber.e(e, "wasn't able to preserve stack for action: %s", action); return callback; } } public static void setTextViewFont(TextView view, JSONObject style, Context context) { try { if (style.has("font:android")) { String f = style.getString("font:android"); if (f.equalsIgnoreCase("bold")) { view.setTypeface(Typeface.DEFAULT_BOLD); } else if (f.equalsIgnoreCase("sans")) { view.setTypeface(Typeface.SANS_SERIF); } else if (f.equalsIgnoreCase("serif")) { view.setTypeface(Typeface.SERIF); } else if (f.equalsIgnoreCase("monospace")) { view.setTypeface(Typeface.MONOSPACE); } else if (f.equalsIgnoreCase("default")) { view.setTypeface(Typeface.DEFAULT); } else { try { Typeface font_type = Typeface.createFromAsset(context.getAssets(), "fonts/" + style.getString("font:android") + ".ttf"); view.setTypeface(font_type); } catch (Exception e) { } } } else if (style.has("font")) { if (style.getString("font").toLowerCase().contains("bold")) { if (style.getString("font").toLowerCase().contains("italic")) { view.setTypeface(Typeface.DEFAULT_BOLD, Typeface.ITALIC); } else { view.setTypeface(Typeface.DEFAULT_BOLD); } } else { if (style.getString("font").toLowerCase().contains("italic")) { view.setTypeface(Typeface.DEFAULT, Typeface.ITALIC); } else { view.setTypeface(Typeface.DEFAULT); } } } } catch (JSONException e) {} } }
{ "content_hash": "6256aaab6408b58a1970be3ad08575bd", "timestamp": "", "source": "github", "line_count": 452, "max_line_length": 189, "avg_line_length": 39.676991150442475, "alnum_prop": 0.5541987286717965, "repo_name": "Jasonette/JASONETTE-Android", "id": "96c83f427e9efec64fd6d7a079b16e92dd0225ce", "size": "17934", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "app/src/main/java/com/jasonette/seed/Helper/JasonHelper.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "529418" } ], "symlink_target": "" }
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("d3-axis"), require("d3-brush"), require("d3-color"), require("d3-drag"), require("d3-dsv"), require("d3-ease"), require("d3-interpolate"), require("d3-scale"), require("d3-selection"), require("d3-shape"), require("d3-time-format"), require("d3-transition"), require("d3-zoom")); else if(typeof define === 'function' && define.amd) define(["d3-axis", "d3-brush", "d3-color", "d3-drag", "d3-dsv", "d3-ease", "d3-interpolate", "d3-scale", "d3-selection", "d3-shape", "d3-time-format", "d3-transition", "d3-zoom"], factory); else { var a = typeof exports === 'object' ? factory(require("d3-axis"), require("d3-brush"), require("d3-color"), require("d3-drag"), require("d3-dsv"), require("d3-ease"), require("d3-interpolate"), require("d3-scale"), require("d3-selection"), require("d3-shape"), require("d3-time-format"), require("d3-transition"), require("d3-zoom")) : factory(root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"], root["d3"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, function(__WEBPACK_EXTERNAL_MODULE__10__, __WEBPACK_EXTERNAL_MODULE__3__, __WEBPACK_EXTERNAL_MODULE__13__, __WEBPACK_EXTERNAL_MODULE__7__, __WEBPACK_EXTERNAL_MODULE__5__, __WEBPACK_EXTERNAL_MODULE__11__, __WEBPACK_EXTERNAL_MODULE__12__, __WEBPACK_EXTERNAL_MODULE__6__, __WEBPACK_EXTERNAL_MODULE__2__, __WEBPACK_EXTERNAL_MODULE__9__, __WEBPACK_EXTERNAL_MODULE__4__, __WEBPACK_EXTERNAL_MODULE__8__, __WEBPACK_EXTERNAL_MODULE__14__) { return /******/ (function() { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ /* 0 */, /* 1 */, /* 2 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__2__; /***/ }), /* 3 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__3__; /***/ }), /* 4 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__4__; /***/ }), /* 5 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__5__; /***/ }), /* 6 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__6__; /***/ }), /* 7 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__7__; /***/ }), /* 8 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__8__; /***/ }), /* 9 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__9__; /***/ }), /* 10 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__10__; /***/ }), /* 11 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__11__; /***/ }), /* 12 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__12__; /***/ }), /* 13 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__13__; /***/ }), /* 14 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__14__; /***/ }) /******/ ]); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ !function() { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = function(exports, definition) { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ !function() { /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /******/ }(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ !function() { /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ }(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other entry modules. !function() { // extracted by mini-css-extract-plugin }(); // This entry need to be wrapped in an IIFE because it need to be isolated against other entry modules. !function() { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "bb": function() { return /* reexport */ bb; }, "default": function() { return /* reexport */ bb; } }); // NAMESPACE OBJECT: ./src/config/resolver/shape.ts var resolver_shape_namespaceObject = {}; __webpack_require__.r(resolver_shape_namespaceObject); __webpack_require__.d(resolver_shape_namespaceObject, { "area": function() { return _area; }, "areaLineRange": function() { return areaLineRange; }, "areaSpline": function() { return areaSpline; }, "areaSplineRange": function() { return areaSplineRange; }, "areaStep": function() { return areaStep; }, "bar": function() { return resolver_shape_bar; }, "bubble": function() { return resolver_shape_bubble; }, "candlestick": function() { return resolver_shape_candlestick; }, "donut": function() { return shape_donut; }, "gauge": function() { return resolver_shape_gauge; }, "line": function() { return resolver_shape_line; }, "pie": function() { return shape_pie; }, "radar": function() { return resolver_shape_radar; }, "scatter": function() { return shape_scatter; }, "spline": function() { return shape_spline; }, "step": function() { return step; } }); // NAMESPACE OBJECT: ./src/config/resolver/interaction.ts var resolver_interaction_namespaceObject = {}; __webpack_require__.r(resolver_interaction_namespaceObject); __webpack_require__.d(resolver_interaction_namespaceObject, { "selection": function() { return _selectionModule; }, "subchart": function() { return subchartModule; }, "zoom": function() { return zoomModule; } }); // EXTERNAL MODULE: external {"commonjs":"d3-time-format","commonjs2":"d3-time-format","amd":"d3-time-format","root":"d3"} var external_commonjs_d3_time_format_commonjs2_d3_time_format_amd_d3_time_format_root_d3_ = __webpack_require__(4); // EXTERNAL MODULE: external {"commonjs":"d3-selection","commonjs2":"d3-selection","amd":"d3-selection","root":"d3"} var external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_ = __webpack_require__(2); ;// CONCATENATED MODULE: ./src/config/classes.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * CSS class names definition * @private */ /* harmony default export */ var config_classes = ({ arc: "bb-arc", arcLabelLine: "bb-arc-label-line", arcs: "bb-arcs", area: "bb-area", areas: "bb-areas", axis: "bb-axis", axisX: "bb-axis-x", axisXLabel: "bb-axis-x-label", axisY: "bb-axis-y", axisY2: "bb-axis-y2", axisY2Label: "bb-axis-y2-label", axisYLabel: "bb-axis-y-label", bar: "bb-bar", bars: "bb-bars", brush: "bb-brush", button: "bb-button", buttonZoomReset: "bb-zoom-reset", candlestick: "bb-candlestick", candlesticks: "bb-candlesticks", chart: "bb-chart", chartArc: "bb-chart-arc", chartArcs: "bb-chart-arcs", chartArcsBackground: "bb-chart-arcs-background", chartArcsGaugeMax: "bb-chart-arcs-gauge-max", chartArcsGaugeMin: "bb-chart-arcs-gauge-min", chartArcsGaugeUnit: "bb-chart-arcs-gauge-unit", chartArcsTitle: "bb-chart-arcs-title", chartArcsGaugeTitle: "bb-chart-arcs-gauge-title", chartBar: "bb-chart-bar", chartBars: "bb-chart-bars", chartCandlestick: "bb-chart-candlestick", chartCandlesticks: "bb-chart-candlesticks", chartCircles: "bb-chart-circles", chartLine: "bb-chart-line", chartLines: "bb-chart-lines", chartRadar: "bb-chart-radar", chartRadars: "bb-chart-radars", chartText: "bb-chart-text", chartTexts: "bb-chart-texts", circle: "bb-circle", circles: "bb-circles", colorPattern: "bb-color-pattern", colorScale: "bb-colorscale", defocused: "bb-defocused", dragarea: "bb-dragarea", empty: "bb-empty", eventRect: "bb-event-rect", eventRects: "bb-event-rects", eventRectsMultiple: "bb-event-rects-multiple", eventRectsSingle: "bb-event-rects-single", focused: "bb-focused", gaugeValue: "bb-gauge-value", grid: "bb-grid", gridLines: "bb-grid-lines", legend: "bb-legend", legendBackground: "bb-legend-background", legendItem: "bb-legend-item", legendItemEvent: "bb-legend-item-event", legendItemFocused: "bb-legend-item-focused", legendItemHidden: "bb-legend-item-hidden", legendItemPoint: "bb-legend-item-point", legendItemTile: "bb-legend-item-tile", level: "bb-level", levels: "bb-levels", line: "bb-line", lines: "bb-lines", main: "bb-main", region: "bb-region", regions: "bb-regions", selectedCircle: "bb-selected-circle", selectedCircles: "bb-selected-circles", shape: "bb-shape", shapes: "bb-shapes", stanfordElements: "bb-stanford-elements", stanfordLine: "bb-stanford-line", stanfordLines: "bb-stanford-lines", stanfordRegion: "bb-stanford-region", stanfordRegions: "bb-stanford-regions", subchart: "bb-subchart", target: "bb-target", text: "bb-text", texts: "bb-texts", title: "bb-title", tooltip: "bb-tooltip", tooltipContainer: "bb-tooltip-container", tooltipName: "bb-tooltip-name", valueDown: "bb-value-down", valueUp: "bb-value-up", xgrid: "bb-xgrid", xgridFocus: "bb-xgrid-focus", xgridLine: "bb-xgrid-line", xgridLines: "bb-xgrid-lines", xgrids: "bb-xgrids", ygrid: "bb-ygrid", ygridFocus: "bb-ygrid-focus", ygridLine: "bb-ygrid-line", ygridLines: "bb-ygrid-lines", ygrids: "bb-ygrids", zoomBrush: "bb-zoom-brush", EXPANDED: "_expanded_", SELECTED: "_selected_", INCLUDED: "_included_", TextOverlapping: "text-overlapping" }); ;// CONCATENATED MODULE: ./src/config/Store/Element.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Elements class. * @class Elements * @ignore * @private */ var Element = function () { return { chart: null, main: null, svg: null, axis: { // axes x: null, y: null, y2: null, subX: null }, defs: null, tooltip: null, legend: null, title: null, subchart: { main: null, // $$.context bar: null, // $$.contextBar line: null, // $$.contextLine area: null // $$.contextArea }, arcs: null, bar: null, // mainBar, candlestick: null, line: null, // mainLine, area: null, // mainArea, circle: null, // mainCircle, radar: null, text: null, // mainText, grid: { main: null, // grid (also focus) x: null, // xgrid, y: null // ygrid, }, gridLines: { main: null, // gridLines x: null, // xgridLines, y: null // ygridLines }, region: { main: null, // region list: null // mainRegion }, eventRect: null }; }; ;// CONCATENATED MODULE: ./src/config/Store/State.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * State class. * @class State * @ignore * @private */ var State = function () { return { width: 0, width2: 0, height: 0, height2: 0, margin: { top: 0, bottom: 0, left: 0, right: 0 }, margin2: { top: 0, bottom: 0, left: 0, right: 0 }, margin3: { top: 0, bottom: 0, left: 0, right: 0 }, arcWidth: 0, arcHeight: 0, xAxisHeight: 0, hasAxis: !1, hasRadar: !1, current: { width: 0, height: 0, dataMax: 0, maxTickWidths: { x: { size: 0, ticks: [], clipPath: 0, domain: "" }, y: { size: 0, domain: "" }, y2: { size: 0, domain: "" } }, // current used chart type list types: [] }, // legend isLegendRight: !1, isLegendInset: !1, isLegendTop: !1, isLegendLeft: !1, legendStep: 0, legendItemWidth: 0, legendItemHeight: 0, legendHasRendered: !1, eventReceiver: { currentIdx: -1, // current event interaction index rect: {}, // event rect's clientBoundingRect data: [], // event data bound of previoous eventRect coords: [] // coordination value of previous eventRect }, axis: { x: { padding: { left: 0, right: 0 }, tickCount: 0 } }, rotatedPadding: { left: 30, right: 0, top: 5 }, withoutFadeIn: {}, inputType: "", datetimeId: "", // clip id string clip: { id: "", idXAxis: "", idYAxis: "", idXAxisTickTexts: "", idGrid: "", idSubchart: "", // clipIdForSubchart path: "", pathXAxis: "", pathYAxis: "", pathXAxisTickTexts: "", pathGrid: "" }, // status event: null, // event object dragStart: null, dragging: !1, flowing: !1, cancelClick: !1, mouseover: !1, rendered: !1, transiting: !1, redrawing: !1, // if redraw() is on process resizing: !1, // resize event called toggling: !1, // legend toggle zooming: !1, hasNegativeValue: !1, hasPositiveValue: !0, orgAreaOpacity: "0.2", // ID strings hiddenTargetIds: [], hiddenLegendIds: [], focusedTargetIds: [], defocusedTargetIds: [], // value for Arc radius: 0, innerRadius: 0, outerRadius: undefined, innerRadiusRatio: 0, gaugeArcWidth: 0, radiusExpanded: 0, // xgrid attribute xgridAttr: { x1: null, x2: null, y1: null, y2: null } }; }; ;// CONCATENATED MODULE: ./src/config/Store/Store.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // mapping var classes = { element: Element, state: State }; /** * Internal store class. * @class Store * @ignore * @private */ var Store = /*#__PURE__*/function () { function Store() { var _this = this; Object.keys(classes).forEach(function (v) { _this[v] = new classes[v](); }); } var _proto = Store.prototype; return _proto.getStore = function getStore(name) { return this[name]; }, Store; }(); ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } ;// CONCATENATED MODULE: ./src/config/Options/common/main.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * main config options */ /* harmony default export */ var main = ({ /** * Specify the CSS selector or the element which the chart will be set to. D3 selection object can be specified also.<br> * If other chart is set already, it will be replaced with the new one (only one chart can be set in one element). * - **NOTE:** In case of element doesn't exist or not specified, will add a `<div>` element to the body. * @name bindto * @memberof Options * @property {string|HTMLElement|d3.selection|object} [bindto="#chart"] Specify the element where chart will be drawn. * @property {string|HTMLElement|d3.selection} bindto.element="#chart" Specify the element where chart will be drawn. * @property {string} [bindto.classname=bb] Specify the class name of bind element.<br> * **NOTE:** When class name isn't `bb`, then you also need to update the default CSS to be rendered correctly. * @default #chart * @example * bindto: "#myContainer" * * // or HTMLElement * bindto: document.getElementById("myContainer") * * // or D3 selection object * bindto: d3.select("#myContainer") * * // or to change default classname * bindto: { * element: "#chart", * classname: "bill-board" // ex) <div id='chart' class='bill-board'> * } */ bindto: "#chart", /** * Set chart background. * @name background * @memberof Options * @property {object} background background object * @property {string} background.class Specify the class name for background element. * @property {string} background.color Specify the fill color for background element.<br>**NOTE:** Will be ignored if `imgUrl` option is set. * @property {string} background.imgUrl Specify the image url string for background. * @see [Demo](https://naver.github.io/billboard.js/demo/#ChartOptions.Background) * @example * background: { * class: "myClass", * color: "red", * * // Set image url for background. * // If specified, 'color' option will be ignored. * imgUrl: "https://naver.github.io/billboard.js/img/logo/billboard.js.svg", * } */ background: {}, /** * Set 'clip-path' attribute for chart element * - **NOTE:** * > When is false, chart node element is positioned after the axis node in DOM tree hierarchy. * > Is to make chart element positioned over axis element. * @name clipPath * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#ChartOptions.clipPath) * @example * // don't set 'clip-path' attribute * clipPath: false */ clipPath: !0, /** * Set svg element's class name * @name svg * @memberof Options * @type {object} * @property {object} [svg] svg object * @property {string} [svg.classname] class name for svg element * @example * svg: { * classname: "test_class" * } */ svg_classname: undefined, /** * The desired size of the chart element. * If value is not specified, the width of the chart will be calculated by the size of the parent element it's appended to. * @name size * @memberof Options * @type {object} * @property {object} [size] size object * @property {number} [size.width] width of the chart element * @property {number} [size.height] height of the chart element * @see [Demo](https://naver.github.io/billboard.js/demo/#ChartOptions.ChartSize) * @example * size: { * width: 640, * height: 480 * } */ size_width: undefined, size_height: undefined, /** * The padding of the chart element. * @name padding * @memberof Options * @type {object} * @property {object} [padding] padding object * @property {number} [padding.top] padding on the top of chart * @property {number} [padding.right] padding on the right of chart * @property {number} [padding.bottom] padding on the bottom of chart * @property {number} [padding.left] padding on the left of chart * @example * padding: { * top: 20, * right: 20, * bottom: 20, * left: 20 * } */ padding_left: undefined, padding_right: undefined, padding_top: undefined, padding_bottom: undefined, /** * Set chart resize options * @name resize * @memberof Options * @type {object} * @property {object} [resize] resize object * @property {boolean} [resize.auto=true] Set chart resize automatically on viewport changes. * @example * resize: { * auto: false * } */ resize_auto: !0, /** * Set a callback to execute when mouse/touch enters the chart. * @name onover * @memberof Options * @type {Function} * @default undefined * @example * onover: function() { * this; // chart instance itself * ... * } */ onover: undefined, /** * Set a callback to execute when mouse/touch leaves the chart. * @name onout * @memberof Options * @type {Function} * @default undefined * @example * onout: function() { * this; // chart instance itself * ... * } */ onout: undefined, /** * Set a callback to execute when user resizes the screen. * @name onresize * @memberof Options * @type {Function} * @default undefined * @example * onresize: function() { * this; // chart instance itself * ... * } */ onresize: undefined, /** * Set a callback to execute when screen resize finished. * @name onresized * @memberof Options * @type {Function} * @default undefined * @example * onresized: function() { * this; // chart instance itself * ... * } */ onresized: undefined, /** * Set a callback to execute before the chart is initialized * @name onbeforeinit * @memberof Options * @type {Function} * @default undefined * @example * onbeforeinit: function() { * this; // chart instance itself * ... * } */ onbeforeinit: undefined, /** * Set a callback to execute when the chart is initialized. * @name oninit * @memberof Options * @type {Function} * @default undefined * @example * oninit: function() { * this; // chart instance itself * ... * } */ oninit: undefined, /** * Set a callback to execute after the chart is initialized * @name onafterinit * @memberof Options * @type {Function} * @default undefined * @example * onafterinit: function() { * this; // chart instance itself * ... * } */ onafterinit: undefined, /** * Set a callback which is executed when the chart is rendered. Basically, this callback will be called in each time when the chart is redrawed. * @name onrendered * @memberof Options * @type {Function} * @default undefined * @example * onrendered: function() { * this; // chart instance itself * ... * } */ onrendered: undefined, /** * Set duration of transition (in milliseconds) for chart animation.<br><br> * - **NOTE:** If `0 `or `null` set, transition will be skipped. So, this makes initial rendering faster especially in case you have a lot of data. * @name transition * @memberof Options * @type {object} * @property {object} [transition] transition object * @property {number} [transition.duration=350] duration in milliseconds * @example * transition: { * duration: 500 * } */ transition_duration: 350, /** * Set plugins * @name plugins * @memberof Options * @type {Array} * @example * plugins: [ * new bb.plugin.stanford({ ... }), * new PluginA(), * ... * ] */ plugins: [], /** * Control the render timing * @name render * @memberof Options * @type {object} * @property {object} [render] render object * @property {boolean} [render.lazy=true] Make to not render at initialization (enabled by default when bind element's visibility is hidden). * @property {boolean} [render.observe=true] Observe bind element's visibility(`display` or `visiblity` inline css property or class value) & render when is visible automatically (for IEs, only works IE11+). When set to **false**, call [`.flush()`](./Chart.html#flush) to render. * @see [Demo](https://naver.github.io/billboard.js/demo/#ChartOptions.LazyRender) * @example * render: { * lazy: true, * observe: true * } * * @example * // <!-- render.lazy will detect visibility defined --> * // (a) <div id='chart' class='hide'></div> * // (b) <div id='chart' style='display:none'></div> * * // render.lazy enabled by default when element is hidden * var chart = bb.generate({ ... }); * * // chart will be rendered automatically when element's visibility changes * // Note: works only for inlined css property or class attribute changes * document.getElementById('chart').classList.remove('hide') // (a) * document.getElementById('chart').style.display = 'block'; // (b) * * @example * // chart won't be rendered and not observing bind element's visiblity changes * var chart = bb.generate({ * render: { * lazy: true, * observe: false * } * }); * * // call at any point when you want to render * chart.flush(); */ render: {}, /** * Show rectangles inside the chart.<br><br> * This option accepts array including object that has axis, start, end and class. * The keys start, end and class are optional. * axis must be x, y or y2. start and end should be the value where regions start and end. * If not specified, the edge values will be used. * If timeseries x axis, date string, Date object and unixtime integer can be used. * If class is set, the region element will have it as class. * @name regions * @memberof Options * @type {Array} * @default [] * @example * regions: [ * { * axis: "x", * start: 1, * end: 4, * class: "region-1-4" * } * ] */ regions: [] }); ;// CONCATENATED MODULE: ./src/config/Options/data/data.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * data config options */ /* harmony default export */ var data = ({ /** * Specify the key of x values in the data.<br><br> * We can show the data with non-index x values by this option. This option is required when the type of x axis is timeseries. If this option is set on category axis, the values of the data on the key will be used for category names. * @name dataβ€€x * @memberof Options * @type {string} * @default undefined * @example * data: { * x: "date" * } */ data_x: undefined, /** * Converts data id value * @name dataβ€€idConverter * @memberof Options * @type {Function} * @default function(id) { return id; } * @example * data: { * idConverter: function(id) { * // when id is 'data1', converts to be 'data2' * // 'data2' should be given as the initial data value * if (id === "data1") { * return "data2"; * } else { * return id; * } * } * } */ data_idConverter: function data_idConverter(id) { return id; }, /** * Set custom data name. * @name dataβ€€names * @memberof Options * @type {object} * @default {} * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.DataName) * @example * data: { * names: { * data1: "Data Name 1", * data2: "Data Name 2" * } * } */ data_names: {}, /** * Set custom data class.<br><br> * If this option is specified, the element g for the data has an additional class that has the prefix 'bb-target-' (eg. bb-target-additional-data1-class). * @name dataβ€€classes * @memberof Options * @type {object} * @default {} * @example * data: { * classes: { * data1: "additional-data1-class", * data2: "additional-data2-class" * } * } */ data_classes: {}, /** * Set chart type at once.<br><br> * If this option is specified, the type will be applied to every data. This setting can be overwritten by data.types.<br><br> * **Available Values:** * - area * - area-line-range * - area-spline * - area-spline-range * - area-step * - bar * - bubble * - candlestick * - donut * - gauge * - line * - pie * - radar * - scatter * - spline * - step * @name dataβ€€type * @memberof Options * @type {string} * @default "line"<br>NOTE: When importing shapes by ESM, `line()` should be specified for type. * @example * data: { * type: "bar" * } * @example * // Generate chart by importing ESM * // Import types to be used only, where this will make smaller bundle size. * import bb, { * area, * areaLineRange, * areaSpline, * areaSplineRange, * areaStep, * bar, * bubble, * candlestick, * donut, * gauge, * line, * pie, * radar, * scatter, * spline, * step * } * * bb.generate({ * ..., * data: { * type: bar() * } * }); */ data_type: undefined, /** * Set chart type for each data.<br> * This setting overwrites data.type setting. * - **NOTE:** `radar` type can't be combined with other types. * @name dataβ€€types * @memberof Options * @type {object} * @default {} * @example * data: { * types: { * data1: "bar", * data2: "spline" * } * } * @example * // Generate chart by importing ESM * // Import types to be used only, where this will make smaller bundle size. * import bb, { * area, * areaLineRange, * areaSpline, * areaSplineRange, * areaStep, * bar, * bubble, * candlestick, * donut, * gauge, * line, * pie, * radar, * scatter, * spline, * step * } * * bb.generate({ * ..., * data: { * types: { * data1: bar(), * data1: spline() * } * } * }); */ data_types: {}, /** * This option changes the order of stacking data and pieces of pie/donut. * - If `null` specified, it will be the order the data loaded. * - If function specified, it will be used as [Array.sort compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters)<br><br> * * **Available Values:** * - `desc`: In descending order * - `asc`: In ascending order * - `null`: It keeps the data load order * - `function(data1, data2) { ... }`: Array.sort compareFunction * * **NOTE**: order function, only works for Axis based types & Arc types, except `Radar` type. * @name dataβ€€order * @memberof Options * @type {string|Function|null} * @default desc * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.DataOrder) * @example * data: { * // in descending order (default) * order: "desc" * * // in ascending order * order: "asc" * * // keeps data input order * order: null * * // specifying sort function * order: function(a, b) { * // param data passed format * // { * // id: "data1", id_org: "data1", values: [ * // {x: 5, value: 250, id: "data1", index: 5, name: "data1"}, * // ... * // ] * // } * * const reducer = (p, c) => p + Math.abs(c.value); * const aSum = a.values.reduce(reducer, 0); * const bSum = b.values.reduce(reducer, 0); * * // ascending order * return aSum - bSum; * * // descending order * // return bSum - aSum; * } * } */ data_order: "desc", /** * Set groups for the data for stacking. * @name dataβ€€groups * @memberof Options * @type {Array} * @default [] * @example * data: { * groups: [ * ["data1", "data2"], * ["data3"] * ] * } */ data_groups: [], /** * Set color converter function.<br><br> * This option should a function and the specified function receives color (e.g. '#ff0000') and d that has data parameters like id, value, index, etc. And it must return a string that represents color (e.g. '#00ff00'). * @name dataβ€€color * @memberof Options * @type {Function} * @default undefined * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.DataColor) * @example * data: { * color: function(color, d) { ... } * } */ data_color: undefined, /** * Set color for each data. * @name dataβ€€colors * @memberof Options * @type {object} * @default {} * @example * data: { * colors: { * data1: "#ff0000", * data2: function(d) { * return "#000"; * } * ... * } * } */ data_colors: {}, /** * Set labels options * @name dataβ€€labels * @memberof Options * @type {object} * @property {object} data Data object * @property {boolean} [data.labels=false] Show or hide labels on each data points * @property {boolean} [data.labels.centered=false] Centerize labels on `bar` shape. (**NOTE:** works only for 'bar' type) * @property {Function} [data.labels.format] Set formatter function for data labels.<br> * The formatter function receives 4 arguments such as v, id, i, j and it **must return a string**(`\n` character will be used as line break) that will be shown as the label.<br><br> * The arguments are:<br> * - `v` is the value of the data point where the label is shown. * - `id` is the id of the data where the label is shown. * - `i` is the index of the data point where the label is shown. * - `j` is the sub index of the data point where the label is shown.<br><br> * Formatter function can be defined for each data by specifying as an object and D3 formatter function can be set (ex. d3.format('$')) * @property {string|object|Function} [data.labels.colors] Set label text colors. * @property {object} [data.labels.position] Set each dataset position, relative the original. * @property {number} [data.labels.position.x=0] x coordinate position, relative the original. * @property {number} [data.labels.position.y=0] y coordinate position, relative the original. * @memberof Options * @type {object} * @default {} * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.DataLabel) * @see [Demo: label colors](https://naver.github.io/billboard.js/demo/#Data.DataLabelColors) * @see [Demo: label format](https://naver.github.io/billboard.js/demo/#Data.DataLabelFormat) * @see [Demo: label multiline](https://naver.github.io/billboard.js/demo/#Data.DataLabelMultiline) * @see [Demo: label overlap](https://naver.github.io/billboard.js/demo/#Data.DataLabelOverlap) * @see [Demo: label position](https://naver.github.io/billboard.js/demo/#Data.DataLabelPosition) * @example * data: { * labels: true, * * // or set specific options * labels: { * format: function(v, id, i, j) { * ... * // to multiline, return with '\n' character * return "Line1\nLine2"; * }, * * // it's possible to set for each data * format: { * data1: function(v, id, i, j) { ... }, * ... * }, * * // align text to center of the 'bar' shape (works only for 'bar' type) * centered: true, * * // apply for all label texts * colors: "red", * * // set different colors per dataset * // for not specified dataset, will have the default color value * colors: { * data1: "yellow", * data3: "green" * }, * * // call back for label text color * colors: function(color, d) { * // color: the default data label color string * // data: ex) {x: 0, value: 200, id: "data3", index: 0} * .... * return d.value > 200 ? "cyan" : color; * }, * * // set x, y coordinate position * position: { * x: -10, * y: 10 * }, * * // or set x, y coordinate position by each dataset * position: { * data1: {x: 5, y: 5}, * data2: {x: 10, y: -20} * } * } * } */ data_labels: {}, data_labels_colors: undefined, data_labels_position: {}, /** * Hide each data when the chart appears.<br><br> * If true specified, all of data will be hidden. If multiple ids specified as an array, those will be hidden. * @name dataβ€€hide * @memberof Options * @type {boolean|Array} * @default false * @example * data: { * // all of data will be hidden * hide: true * * // specified data will be hidden * hide: ["data1", ...] * } */ data_hide: !1, /** * Filter values to be shown * The data value is the same as the returned by `.data()`. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter * @name dataβ€€filter * @memberof Options * @type {Function} * @default undefined * @example * data: { * // filter for id value * filter: function(v) { * // v: [{id: "data1", id_org: "data1", values: [ * // {x: 0, value: 130, id: "data2", index: 0}, ...] * // }, ...] * return v.id !== "data1"; * } */ data_filter: undefined, /** * Set a callback for click event on each data point.<br><br> * This callback will be called when each data point clicked and will receive `d` and element as the arguments. * - `d` is the data clicked and element is the element clicked. * - `element` is the current interacting svg element. * - In this callback, `this` will be the Chart object. * @name dataβ€€onclick * @memberof Options * @type {Function} * @default function() {} * @example * data: { * onclick: function(d, element) { * // d - ex) {x: 4, value: 150, id: "data1", index: 4, name: "data1"} * // element - <circle> * ... * } * } */ data_onclick: function data_onclick() {}, /** * Set a callback for mouse/touch over event on each data point.<br><br> * This callback will be called when mouse cursor or via touch moves onto each data point and will receive `d` and `element` as the argument. * - `d` is the data where mouse cursor moves onto. * - `element` is the current interacting svg element. * - In this callback, `this` will be the Chart object. * @name dataβ€€onover * @memberof Options * @type {Function} * @default function() {} * @example * data: { * onover: function(d, element) { * // d - ex) {x: 4, value: 150, id: "data1", index: 4} * // element - <circle> * ... * } * } */ data_onover: function data_onover() {}, /** * Set a callback for mouse/touch out event on each data point.<br><br> * This callback will be called when mouse cursor or via touch moves out each data point and will receive `d` as the argument. * - `d` is the data where mouse cursor moves out. * - `element` is the current interacting svg element. * - In this callback, `this` will be the Chart object. * @name dataβ€€onout * @memberof Options * @type {Function} * @default function() {} * @example * data: { * onout: function(d, element) { * // d - ex) {x: 4, value: 150, id: "data1", index: 4} * // element - <circle> * ... * } * } */ data_onout: function data_onout() {}, /** * Set a callback for minimum data * - **NOTE:** For 'area-line-range' and 'area-spline-range', `mid` data will be taken for the comparison * @name dataβ€€onmin * @memberof Options * @type {Function} * @default undefined * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.OnMinMaxCallback) * @example * onmin: function(data) { * // data - ex) [{x: 3, value: 400, id: "data1", index: 3}, ... ] * ... * } */ data_onmin: undefined, /** * Set a callback for maximum data * - **NOTE:** For 'area-line-range' and 'area-spline-range', `mid` data will be taken for the comparison * @name dataβ€€onmax * @memberof Options * @type {Function} * @default undefined * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.OnMinMaxCallback) * @example * onmax: function(data) { * // data - ex) [{x: 3, value: 400, id: "data1", index: 3}, ... ] * ... * } */ data_onmax: undefined, /** * Load a CSV or JSON file from a URL. NOTE that this will not work if loading via the "file://" protocol as the most browsers will block XMLHTTPRequests. * @name dataβ€€url * @memberof Options * @type {string} * @default undefined * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.LoadData) * @example * data: { * url: "/data/test.csv" * } */ data_url: undefined, /** * XHR header value * - **NOTE:** Should be used with `data.url` option * @name dataβ€€headers * @memberof Options * @type {string} * @default undefined * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader * @example * data: { * url: "/data/test.csv", * headers: { * "Content-Type": "text/xml", * ... * } * } */ data_headers: undefined, /** * Parse a JSON object for data. See also data.keys. * @name dataβ€€json * @memberof Options * @type {Array} * @default undefined * @see [dataβ€€keys](#.data%25E2%2580%25A4keys) * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.JSONData) * @example * data: { * json: [ * {name: "www.site1.com", upload: 200, download: 200, total: 400}, * {name: "www.site2.com", upload: 100, download: 300, total: 400}, * {name: "www.site3.com", upload: 300, download: 200, total: 500}, * {name: "www.site4.com", upload: 400, download: 100, total: 500} * ], * keys: { * // x: "name", // it's possible to specify 'x' when category axis * value: ["upload", "download"] * } * } */ data_json: undefined, /** * Load data from a multidimensional array, with the first element containing the data names, the following containing related data in that order. * @name dataβ€€rows * @memberof Options * @type {Array} * @default undefined * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.RowOrientedData) * @example * data: { * rows: [ * ["A", "B", "C"], * [90, 120, 300], * [40, 160, 240], * [50, 200, 290], * [120, 160, 230], * [80, 130, 300], * [90, 220, 320] * ] * } * * // for 'range' types('area-line-range' or 'area-spline-range'), data should contain: * // - an array of [high, mid, low] data following the order * // - or an object with 'high', 'mid' and 'low' key value * data: { * rows: [ * ["data1", "data2"], * [ * // or {high:150, mid: 140, low: 110}, 120 * [150, 140, 110], 120 * ], * [[155, 130, 115], 55], * [[160, 135, 120], 60] * ], * types: { * data1: "area-line-range", * data2: "line" * } * } * * // for 'bubble' type, data can contain dimension value: * // - an array of [y, z] data following the order * // - or an object with 'y' and 'z' key value * // 'y' is for y axis coordination and 'z' is the bubble radius value * data: { * rows: [ * ["data1", "data2"], * [ * // or {y:10, z: 140}, 120 * [10, 140], 120 * ], * [[100, 30], 55], * [[50, 100], 60] * ], * types: { * data1: "bubble", * data2: "line" * } * } * * // for 'canlestick' type, data should contain: * // - an array of [open, high, low, close, volume(optional)] data following the order * // - or an object with 'open', 'high', 'low', 'close' and 'value'(optional) key value * data: { * rows: [ * ["data1", "data2"], * [ * // open, high, low, close, volume (optional) * {open: 1300, high: 1369, low: 1200, close: 1339, volume: 100}, * [1000, 1100, 850, 870] * ], * [ * {open: 1348, high: 1371, low: 1271, close: 1320}, * [870, 1250, 830, 1200, 50] * ] * ], * type: "candlestick" * } */ data_rows: undefined, /** * Load data from a multidimensional array, with each element containing an array consisting of a datum name and associated data values. * @name dataβ€€columns * @memberof Options * @type {Array} * @default undefined * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.ColumnOrientedData) * @example * data: { * columns: [ * ["data1", 30, 20, 50, 40, 60, 50], * ["data2", 200, 130, 90, 240, 130, 220], * ["data3", 300, 200, 160, 400, 250, 250] * ] * } * * // for 'range' types('area-line-range' or 'area-spline-range'), data should contain: * // - an array of [high, mid, low] data following the order * // - or an object with 'high', 'mid' and 'low' key value * data: { * columns: [ * ["data1", * [150, 140, 110], // or {high:150, mid: 140, low: 110} * [150, 140, 110], * [150, 140, 110] * ] * ], * type: "area-line-range" * } * * // for 'bubble' type, data can contain dimension value: * // - an array of [y, z] data following the order * // - or an object with 'y' and 'z' key value * // 'y' is for y axis coordination and 'z' is the bubble radius value * data: { * columns: [ * ["data1", * [10, 140], // or {y:10, z: 140} * [100, 30], * [50, 100] * ] * ], * type: "bubble" * } * * // for 'canlestick' type, data should contain: * // - an array of [open, high, low, close, volume(optional)] data following the order * // - or an object with 'open', 'high', 'low', 'close' and 'value'(optional) key value * data: { * columns: [ * ["data1", * [1000, 1100, 850, 870, 100], // or {open:1000, high: 1100, low: 870, volume: 100} * [870, 1250, 830, 1200] // 'volume' can be omitted * ] * ], * type: "candlestick" * } */ data_columns: undefined, /** * Used if loading JSON via data.url. * - **Available Values:** * - json * - csv * - tsv * @name dataβ€€mimeType * @memberof Options * @type {string} * @default csv * @example * data: { * mimeType: "json" * } */ data_mimeType: "csv", /** * Choose which JSON object keys correspond to desired data. * - **NOTE:** Only for JSON object given as array. * @name dataβ€€keys * @memberof Options * @type {string} * @default undefined * @example * data: { * json: [ * {name: "www.site1.com", upload: 200, download: 200, total: 400}, * {name: "www.site2.com", upload: 100, download: 300, total: 400}, * {name: "www.site3.com", upload: 300, download: 200, total: 500}, * {name: "www.site4.com", upload: 400, download: 100, total: 500} * ], * keys: { * // x: "name", // it's possible to specify 'x' when category axis * value: ["upload", "download"] * } * } */ data_keys: undefined, /** * Set text label to be displayed when there's no data to show. * - ex. Toggling all visible data to not be shown, unloading all current data, etc. * @name dataβ€€emptyβ€€labelβ€€text * @memberof Options * @type {string} * @default "" * @example * data: { * empty: { * label: { * text: "No Data" * } * } * } */ data_empty_label_text: "" }); ;// CONCATENATED MODULE: ./src/config/Options/common/color.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * color config options */ /* harmony default export */ var color = ({ /** * Set color of the data values * @name color * @memberof Options * @type {object} * @property {object} color color object * @property {string|object|Function} [color.onover] Set the color value for each data point when mouse/touch onover event occurs. * @property {Array|null} [color.pattern=[]] Set custom color pattern. Passing `null` will not set a color for these elements, which requires the usage of custom CSS-based theming to work. * @property {Function} [color.tiles] if defined, allows use svg's patterns to fill data area. It should return an array of [SVGPatternElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGPatternElement). * - **NOTE:** The pattern element's id will be defined as `bb-colorize-pattern-$COLOR-VALUE`.<br> * ex. When color pattern value is `['red', '#fff']` and defined 2 patterns,then ids for pattern elements are:<br> * - `bb-colorize-pattern-red` * - `bb-colorize-pattern-fff` * @property {object} [color.threshold] color threshold for gauge and tooltip color * @property {string} [color.threshold.unit] If set to `value`, the threshold will be based on the data value. Otherwise it'll be based on equation of the `threshold.max` option value. * @property {Array} [color.threshold.values] Threshold values for each steps * @property {number} [color.threshold.max=100] The base value to determine threshold step value condition. When the given value is 15 and max 10, then the value for threshold is `15*100/10`. * @example * color: { * pattern: ["#1f77b4", "#aec7e8", ...], * * // Set colors' patterns * // it should return an array of SVGPatternElement * tiles: function() { * var pattern = document.createElementNS("http://www.w3.org/2000/svg", "pattern"); * var g = document.createElementNS("http://www.w3.org/2000/svg", "g"); * var circle1 = document.createElementNS("http://www.w3.org/2000/svg", "circle"); * * pattern.setAttribute("patternUnits", "userSpaceOnUse"); * pattern.setAttribute("width", "32"); * pattern.setAttribute("height", "32"); * * g.style.fill = "#000"; * g.style.opacity = "0.2"; * * circle1.setAttribute("cx", "3"); * circle1.setAttribute("cy", "3"); * circle1.setAttribute("r", "3"); * * g.appendChild(circle1); * pattern.appendChild(g); * * return [pattern]; * }, * * // for threshold usage, pattern values should be set for each steps * pattern: ["grey", "green", "yellow", "orange", "red"], * threshold: { * unit: "value", * * // when value is 20 => 'green', value is 40 => 'orange' will be set. * values: [10, 20, 30, 40, 50], * * // the equation for max: * // - unit == 'value': max => 30 * // - unit != 'value': max => value*100/30 * max: 30 * }, * * // set all data to 'red' * onover: "red", * * // set different color for data * onover: { * data1: "red", * data2: "yellow" * }, * * // will pass data object to the callback * onover: function(d) { * return d.id === "data1" ? "red" : "green"; * } * } */ color_pattern: [], color_tiles: undefined, color_threshold: {}, color_onover: undefined }); ;// CONCATENATED MODULE: ./src/config/Options/interaction/interaction.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * interaction config options */ /* harmony default export */ var interaction = ({ /** * Interaction options * @name interaction * @memberof Options * @type {object} * @property {object} interaction Intersection object * @property {boolean} [interaction.enabled=true] Indicate if the chart should have interactions.<br> * If `false` is set, all of interactions (showing/hiding tooltip, selection, mouse events, etc) will be disabled. * @property {boolean} [interaction.brighten=true] Make brighter for the selected area (ex. 'pie' type data selected area) * @property {boolean} [interaction.inputType.mouse=true] enable or disable mouse interaction * @property {boolean} [interaction.inputType.touch=true] enable or disable touch interaction * @property {boolean|number} [interaction.inputType.touch.preventDefault=false] enable or disable to call event.preventDefault on touchstart & touchmove event. It's usually used to prevent document scrolling. * @see [Demo: touch.preventDefault](https://naver.github.io/billboard.js/demo/#Interaction.PreventScrollOnTouch) * @example * interaction: { * enabled: false, * brighten: false, * inputType: { * mouse: true, * touch: false * * // or declare preventDefault explicitly. * // In this case touch inputType is enabled by default * touch: { * preventDefault: true * * // or threshold pixel value (pixel moved from touchstart to touchmove) * preventDefault: 5 * } * } * } */ interaction_enabled: !0, interaction_brighten: !0, interaction_inputType_mouse: !0, interaction_inputType_touch: {} }); ;// CONCATENATED MODULE: ./src/config/Options/common/legend.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * legend config options */ /* harmony default export */ var legend = ({ /** * Legend options * @name legend * @memberof Options * @type {object} * @property {object} legend Legend object * @property {boolean} [legend.show=true] Show or hide legend. * @property {boolean} [legend.hide=false] Hide legend * If true given, all legend will be hidden. If string or array given, only the legend that has the id will be hidden. * @property {string|HTMLElement} [legend.contents.bindto=undefined] Set CSS selector or element reference to bind legend items. * @property {string|Function} [legend.contents.template=undefined] Set item's template.<br> * - If set `string` value, within template the 'color' and 'title' can be replaced using template-like syntax string: * - {=COLOR}: data color value * - {=TITLE}: data title value * - If set `function` value, will pass following arguments to the given function: * - title {string}: data's id value * - color {string}: color string * - data {Array}: data array * @property {string} [legend.position=bottom] Change the position of legend.<br> * Available values are: `bottom`, `right` and `inset` are supported. * @property {object} [legend.inset={anchor: 'top-left',x: 10,y: 0,step: undefined}] Change inset legend attributes.<br> * This option accepts object that has the keys `anchor`, `x`, `y` and `step`. * - **anchor** decides the position of the legend: * - top-left * - top-right * - bottom-left * - bottom-right * - **x** and **y**: * - set the position of the legend based on the anchor. * - **step**: * - defines the max step the legend has (e.g. If 2 set and legend has 3 legend item, the legend 2 columns). * @property {boolean} [legend.equally=false] Set to all items have same width size. * @property {boolean} [legend.padding=0] Set padding value * @property {Function} [legend.item.onclick=undefined] Set click event handler to the legend item. * @property {Function} [legend.item.onover=undefined] Set mouse/touch over event handler to the legend item. * @property {Function} [legend.item.onout=undefined] Set mouse/touch out event handler to the legend item. * @property {number} [legend.item.tile.width=10] Set width of item tile element * @property {number} [legend.item.tile.height=10] Set height of item tile element * @property {boolean} [legend.usePoint=false] Whether to use custom points in legend. * @see [Demo: position](https://naver.github.io/billboard.js/demo/#Legend.LegendPosition) * @see [Demo: contents.template](https://naver.github.io/billboard.js/demo/#Legend.LegendTemplate1) * @see [Demo: usePoint](https://naver.github.io/billboard.js/demo/#Legend.usePoint) * @example * legend: { * show: true, * hide: true, * //or hide: "data1" * //or hide: ["data1", "data2"] * contents: { * bindto: "#legend", // <ul id='legend'></ul> * * // will be as: <li style='background-color:#1f77b4'>data1</li> * template: "<li style='background-color:{=COLOR}'>{=TITLE}</li>" * * // or using function * template: function(id, color, data) { * // if you want omit some legend, return falsy value * if (id !== "data1") { * return "<li style='background-color:"+ color +">"+ id +"</li>"; * } * } * }, * position: "bottom", // bottom, right, inset * inset: { * anchor: "top-right" // top-left, top-right, bottom-left, bottom-right * x: 20, * y: 10, * step: 2 * }, * equally: false, * padding: 10, * item: { * onclick: function(id) { ... }, * onover: function(id) { ... }, * onout: function(id) { ... }, * * // set tile's size * tile: { * width: 20, * height: 15 * } * }, * usePoint: true * } */ legend_show: !0, legend_hide: !1, legend_contents_bindto: undefined, legend_contents_template: undefined, legend_position: "bottom", legend_inset_anchor: "top-left", legend_inset_x: 10, legend_inset_y: 0, legend_inset_step: undefined, legend_item_onclick: undefined, legend_item_onover: undefined, legend_item_onout: undefined, legend_equally: !1, legend_padding: 0, legend_item_tile_width: 10, legend_item_tile_height: 10, legend_usePoint: !1 }); ;// CONCATENATED MODULE: ./src/config/Options/common/title.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * title config options */ /* harmony default export */ var title = ({ /** * Set title options * @name title * @memberof Options * @type {object} * @property {object} title Title object * @property {string} [title.text] Title text. If contains `\n`, it's used as line break allowing multiline title. * @property {number} [title.padding.top=0] Top padding value. * @property {number} [title.padding.right=0] Right padding value. * @property {number} [title.padding.bottom=0] Bottom padding value. * @property {number} [title.padding.left=0] Left padding value. * @property {string} [title.position=center] Available values are: 'center', 'right' and 'left'. * @see [Demo](https://naver.github.io/billboard.js/demo/#Title.MultilinedTitle) * @example * title: { * text: "Title Text", * * // or Multiline title text * text: "Main title text\nSub title text", * * padding: { * top: 10, * right: 10, * bottom: 10, * left: 10 * }, * position: "center" * } */ title_text: undefined, title_padding: { top: 0, right: 0, bottom: 0, left: 0 }, title_position: "center" }); ;// CONCATENATED MODULE: ./src/config/Options/common/tooltip.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * tooltip config options */ /* harmony default export */ var tooltip = ({ /** * Tooltip options * @name tooltip * @memberof Options * @type {object} * @property {object} tooltip Tooltip object * @property {boolean} [tooltip.show=true] Show or hide tooltip. * @property {boolean} [tooltip.doNotHide=false] Make tooltip keep showing not hiding on interaction. * @property {boolean} [tooltip.grouped=true] Set if tooltip is grouped or not for the data points. * - **NOTE:** The overlapped data points will be displayed as grouped even if set false. * @property {boolean} [tooltip.linked=false] Set if tooltips on all visible charts with like x points are shown together when one is shown. * @property {string} [tooltip.linked.name=""] Groping name for linked tooltip.<br>If specified, linked tooltip will be groped interacting to be worked only with the same name. * @property {Function} [tooltip.format.title] Set format for the title of tooltip.<br> * Specified function receives x of the data point to show. * @property {Function} [tooltip.format.name] Set format for the name of each data in tooltip.<br> * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. * @property {Function} [tooltip.format.value] Set format for the value of each data in tooltip.<br> * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. * If undefined returned, the row of that value will be skipped. * @property {Function} [tooltip.position] Set custom position function for the tooltip.<br> * This option can be used to modify the tooltip position by returning object that has top and left. * @property {Function|object} [tooltip.contents] Set custom HTML for the tooltip.<br> * Specified function receives data, defaultTitleFormat, defaultValueFormat and color of the data point to show. If tooltip.grouped is true, data includes multiple data points. * @property {string|HTMLElement} [tooltip.contents.bindto=undefined] Set CSS selector or element reference to bind tooltip. * - **NOTE:** When is specified, will not be updating tooltip's position. * @property {string} [tooltip.contents.template=undefined] Set tooltip's template.<br><br> * Within template, below syntax will be replaced using template-like syntax string: * - **{{ ... }}**: the doubly curly brackets indicate loop block for data rows. * - **{=CLASS_TOOLTIP}**: default tooltip class name `bb-tooltip`. * - **{=CLASS_TOOLTIP_NAME}**: default tooltip data class name (ex. `bb-tooltip-name-data1`) * - **{=TITLE}**: title value. * - **{=COLOR}**: data color. * - **{=VALUE}**: data value. * @property {object} [tooltip.contents.text=undefined] Set additional text content within data loop, using template syntax. * - **NOTE:** It should contain `{ key: Array, ... }` value * - 'key' name is used as substitution within template as '{=KEY}' * - The value array length should match with the data length * @property {boolean} [tooltip.init.show=false] Show tooltip at the initialization. * @property {number} [tooltip.init.x=0] Set x Axis index(or index for Arc(donut, gauge, pie) types) to be shown at the initialization. * @property {object} [tooltip.init.position={top: "0px",left: "50px"}] Set the position of tooltip at the initialization. * @property {Function} [tooltip.onshow] Set a callback that will be invoked before the tooltip is shown. * @property {Function} [tooltip.onhide] Set a callback that will be invoked before the tooltip is hidden. * @property {Function} [tooltip.onshown] Set a callback that will be invoked after the tooltip is shown * @property {Function} [tooltip.onhidden] Set a callback that will be invoked after the tooltip is hidden. * @property {string|Function|null} [tooltip.order=null] Set tooltip data display order.<br><br> * **Available Values:** * - `desc`: In descending data value order * - `asc`: In ascending data value order * - `null`: It keeps the data display order<br> * **NOTE:** When `data.groups` is set, the order will follow as the stacked graph order.<br> * If want to order as data bound, set any value rather than asc, desc or null. (ex. empty string "") * - `function(data1, data2) { ... }`: [Array.sort compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters) * @see [Demo: Hide Tooltip](https://naver.github.io/billboard.js/demo/#Tooltip.HideTooltip) * @see [Demo: Tooltip Grouping](https://naver.github.io/billboard.js/demo/#Tooltip.TooltipGrouping) * @see [Demo: Tooltip Format](https://naver.github.io/billboard.js/demo/#Tooltip.TooltipFormat) * @see [Demo: Linked Tooltip](https://naver.github.io/billboard.js/demo/#Tooltip.LinkedTooltips) * @see [Demo: Tooltip Template](https://naver.github.io/billboard.js/demo/#Tooltip.TooltipTemplate) * @example * tooltip: { * show: true, * doNotHide: true, * grouped: false, * format: { * title: function(x) { return "Data " + x; }, * name: function(name, ratio, id, index) { return name; }, * value: function(value, ratio, id, index) { return ratio; } * }, * position: function(data, width, height, element) { * return {top: 0, left: 0} * }, * * contents: function(d, defaultTitleFormat, defaultValueFormat, color) { * return ... // formatted html as you want * }, * * // specify tooltip contents using template * // - example of HTML returned: * // <ul class="bb-tooltip"> * // <li class="bb-tooltip-name-data1"><span>250</span><br><span style="color:#00c73c">data1</span></li> * // <li class="bb-tooltip-name-data2"><span>50</span><br><span style="color:#fa7171">data2</span></li> * // </ul> * contents: { * bindto: "#tooltip", * template: '<ul class={=CLASS_TOOLTIP}>{{' + * '<li class="{=CLASS_TOOLTIP_NAME}"><span>{=VALUE}</span><br>' + * '<span style=color:{=COLOR}>{=NAME}</span></li>' + * '}}</ul>' * } * * // with additional text value * // - example of HTML returned: * // <ul class="bb-tooltip"> * // <li class="bb-tooltip-name-data1"><span>250</span><br>comment1<span style="color:#00c73c">data1</span>text1</li> * // <li class="bb-tooltip-name-data2"><span>50</span><br>comment2<span style="color:#fa7171">data2</span>text2</li> * // </ul> * contents: { * bindto: "#tooltip", * text: { * // a) 'key' name is used as substitution within template as '{=KEY}' * // b) the length should match with the data length * VAR1: ["text1", "text2"], * VAR2: ["comment1", "comment2"], * }, * template: '<ul class={=CLASS_TOOLTIP}>{{' + * '<li class="{=CLASS_TOOLTIP_NAME}"><span>{=VALUE}</span>{=VAR2}<br>' + * '<span style=color:{=COLOR}>{=NAME}</span>{=VAR1}</li>' + * '}}</ul>' * } * * // sort tooltip data value display in ascending order * order: "asc", * * // specifying sort function * order: function(a, b) { * // param data passed format * {x: 5, value: 250, id: "data1", index: 5, name: "data1"} * ... * }, * * // show at the initialization * init: { * show: true, * x: 2, // x Axis index(or index for Arc(donut, gauge, pie) types) * position: { * top: "150px", * left: "250px" * } * }, * * // fires prior tooltip is shown * onshow: function(selectedData) { * // current dataset selected * // ==> [{x: 4, value: 150, id: "data2", index: 4, name: "data2"}, ...] * selectedData; * }, * * // fires prior tooltip is hidden * onhide: function(selectedData) { * // current dataset selected * // ==> [{x: 4, value: 150, id: "data2", index: 4, name: "data2"}, ...] * selectedData; * }, * * // fires after tooltip is shown * onshown: function(selectedData) { * // current dataset selected * // ==> [{x: 4, value: 150, id: "data2", index: 4, name: "data2"}, ...] * selectedData; * }, * * // fires after tooltip is hidden * onhidden: function(selectedData) { * // current dataset selected * // ==> [{x: 4, value: 150, id: "data2", index: 4, name: "data2"}, ...] * selectedData; * }, * * // Link any tooltips when multiple charts are on the screen where same x coordinates are available * // Useful for timeseries correlation * linked: true, * * // Specify name to interact those with the same name only. * linked: { * name: "some-group" * } * } */ tooltip_show: !0, tooltip_doNotHide: !1, tooltip_grouped: !0, tooltip_format_title: undefined, tooltip_format_name: undefined, tooltip_format_value: undefined, tooltip_position: undefined, tooltip_contents: {}, tooltip_init_show: !1, tooltip_init_x: 0, tooltip_init_position: { top: "0px", left: "50px" }, tooltip_linked: !1, tooltip_linked_name: "", tooltip_onshow: function tooltip_onshow() {}, tooltip_onhide: function tooltip_onhide() {}, tooltip_onshown: function tooltip_onshown() {}, tooltip_onhidden: function tooltip_onhidden() {}, tooltip_order: null }); // EXTERNAL MODULE: external {"commonjs":"d3-brush","commonjs2":"d3-brush","amd":"d3-brush","root":"d3"} var external_commonjs_d3_brush_commonjs2_d3_brush_amd_d3_brush_root_d3_ = __webpack_require__(3); ;// CONCATENATED MODULE: ./src/module/browser.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Window object * @private */ /* eslint-disable no-new-func, no-undef */ var win = function () { var root = typeof globalThis === "object" && globalThis !== null && globalThis.Object === Object && globalThis || typeof global === "object" && global !== null && global.Object === Object && global || typeof self === "object" && self !== null && self.Object === Object && self; return root || Function("return this")(); }(), browser_doc = win && win.document; /* eslint-enable no-new-func, no-undef */ ;// CONCATENATED MODULE: ./src/module/util.ts function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var source, i = 1; i < arguments.length; i++) source = arguments[i] == null ? {} : arguments[i], i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); return target; } /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license * @ignore */ var isValue = function (v) { return v || v === 0; }, isFunction = function (v) { return typeof v === "function"; }, isString = function (v) { return typeof v === "string"; }, isNumber = function (v) { return typeof v === "number"; }, isUndefined = function (v) { return typeof v === "undefined"; }, isDefined = function (v) { return typeof v !== "undefined"; }, isboolean = function (v) { return typeof v === "boolean"; }, ceil10 = function (v) { return Math.ceil(v / 10) * 10; }, asHalfPixel = function (n) { return Math.ceil(n) + .5; }, diffDomain = function (d) { return d[1] - d[0]; }, isObjectType = function (v) { return typeof v === "object"; }, isEmpty = function (o) { return isUndefined(o) || o === null || isString(o) && o.length === 0 || isObjectType(o) && !(o instanceof Date) && Object.keys(o).length === 0 || isNumber(o) && isNaN(o); }, notEmpty = function (o) { return !isEmpty(o); }, isArray = function (arr) { return Array.isArray(arr); }, isObject = function (obj) { return obj && !obj.nodeType && isObjectType(obj) && !isArray(obj); }; /** * Get specified key value from object * If default value is given, will return if given key value not found * @param {object} options Source object * @param {string} key Key value * @param {*} defaultValue Default value * @returns {*} * @private */ function getOption(options, key, defaultValue) { return isDefined(options[key]) ? options[key] : defaultValue; } /** * Check if value exist in the given object * @param {object} dict Target object to be checked * @param {*} value Value to be checked * @returns {boolean} * @private */ function hasValue(dict, value) { var found = !1; return Object.keys(dict).forEach(function (key) { return dict[key] === value && (found = !0); }), found; } /** * Call function with arguments * @param {Function} fn Function to be called * @param {*} args Arguments * @returns {boolean} true: fn is function, false: fn is not function * @private */ function callFn(fn) { for (var isFn = isFunction(fn), _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key]; return isFn && fn.call.apply(fn, args), isFn; } /** * Call function after all transitions ends * @param {d3.transition} transition Transition * @param {Fucntion} cb Callback function * @private */ function endall(transition, cb) { var n = 0; transition.each(function () { return ++n; }).on("end", function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; --n || cb.apply.apply(cb, [this].concat(args)); }); } /** * Replace tag sign to html entity * @param {string} str Target string value * @returns {string} * @private */ function sanitise(str) { return isString(str) ? str.replace(/</g, "&lt;").replace(/>/g, "&gt;") : str; } /** * Set text value. If there's multiline add nodes. * @param {d3Selection} node Text node * @param {string} text Text value string * @param {Array} dy dy value for multilined text * @param {boolean} toMiddle To be alingned vertically middle * @private */ function setTextValue(node, text, dy, toMiddle) { if (dy === void 0 && (dy = [-1, 1]), toMiddle === void 0 && (toMiddle = !1), node && isString(text)) if (text.indexOf("\n") === -1) node.text(text);else { var diff = [node.text(), text].map(function (v) { return v.replace(/[\s\n]/g, ""); }); if (diff[0] !== diff[1]) { var multiline = text.split("\n"), len = toMiddle ? multiline.length - 1 : 1; node.html(""), multiline.forEach(function (v, i) { node.append("tspan").attr("x", 0).attr("dy", (i === 0 ? dy[0] * len : dy[1]) + "em").text(v); }); } } } /** * Substitution of SVGPathSeg API polyfill * @param {SVGGraphicsElement} path Target svg element * @returns {Array} * @private */ function getRectSegList(path) { /* * seg1 ---------- seg2 * | | * | | * | | * seg0 ---------- seg3 * */ var _path$getBBox = path.getBBox(), x = _path$getBBox.x, y = _path$getBBox.y, width = _path$getBBox.width, height = _path$getBBox.height; return [{ x: x, y: y + height }, // seg0 { x: x, y: y }, // seg1 { x: x + width, y: y }, // seg2 { x: x + width, y: y + height } // seg3 ]; } /** * Get svg bounding path box dimension * @param {SVGGraphicsElement} path Target svg element * @returns {object} * @private */ function getPathBox(path) { var _path$getBoundingClie = path.getBoundingClientRect(), width = _path$getBoundingClie.width, height = _path$getBoundingClie.height, items = getRectSegList(path), x = items[0].x, y = Math.min(items[0].y, items[1].y); return { x: x, y: y, width: width, height: height }; } /** * Get event's current position coordinates * @param {object} event Event object * @param {SVGElement|HTMLElement} element Target element * @returns {Array} [x, y] Coordinates x, y array * @private */ function getPointer(event, element) { var touches = event && (event.touches || event.sourceEvent && event.sourceEvent.touches), pointer = event ? (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.pointer)(touches ? touches[0] : event, element) : [0, 0]; return pointer; } /** * Return brush selection array * @param {object} ctx Current instance * @returns {d3.brushSelection} * @private */ function getBrushSelection(ctx) { var selection, event = ctx.event, $el = ctx.$el, main = $el.subchart.main || $el.main; return event && event.type === "brush" ? selection = event.selection : main && (selection = main.select("." + config_classes.brush).node()) && (selection = (0,external_commonjs_d3_brush_commonjs2_d3_brush_amd_d3_brush_root_d3_.brushSelection)(selection)), selection; } /** * Get boundingClientRect. * Cache the evaluated value once it was called. * @param {HTMLElement} node Target element * @returns {object} * @private */ function getBoundingRect(node) { var needEvaluate = !("rect" in node) || "rect" in node && node.hasAttribute("width") && node.rect.width !== +node.getAttribute("width"); return needEvaluate ? node.rect = node.getBoundingClientRect() : node.rect; } /** * Retrun random number * @param {boolean} asStr Convert returned value as string * @returns {number|string} * @private */ function getRandom(asStr) { asStr === void 0 && (asStr = !0); var rand = Math.random(); return asStr ? rand + "" : rand; } /** * Find index based on binary search * @param {Array} arr Data array * @param {number} v Target number to find * @param {number} start Start index of data array * @param {number} end End index of data arr * @param {boolean} isRotated Weather is roted axis * @returns {number} Index number * @private */ function findIndex(arr, v, start, end, isRotated) { if (start > end) return -1; var mid = Math.floor((start + end) / 2), _arr$mid = arr[mid], x = _arr$mid.x, _arr$mid$w = _arr$mid.w, w = _arr$mid$w === void 0 ? 0 : _arr$mid$w; return isRotated && (x = arr[mid].y, w = arr[mid].h), v >= x && v <= x + w ? mid : v < x ? findIndex(arr, v, start, mid - 1, isRotated) : findIndex(arr, v, mid + 1, end, isRotated); } /** * Check if brush is empty * @param {object} ctx Bursh context * @returns {boolean} * @private */ function brushEmpty(ctx) { var selection = getBrushSelection(ctx); return !selection || selection[0] === selection[1]; } /** * Deep copy object * @param {object} objectN Source object * @returns {object} Cloned object * @private */ function deepClone() { for (var clone = function (_clone) { function clone() { return _clone.apply(this, arguments); } return clone.toString = function () { return _clone.toString(); }, clone; }(function (v) { if (isObject(v) && v.constructor) { var r = new v.constructor(); for (var k in v) r[k] = clone(v[k]); return r; } return v; }), _len3 = arguments.length, objectN = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) objectN[_key3] = arguments[_key3]; return objectN.map(function (v) { return clone(v); }).reduce(function (a, c) { return _objectSpread(_objectSpread({}, a), c); }); } /** * Extend target from source object * @param {object} target Target object * @param {object|Array} source Source object * @returns {object} * @private */ function extend(target, source) { // exclude name with only numbers for (var p in target === void 0 && (target = {}), isArray(source) && source.forEach(function (v) { return extend(target, v); }), source) /^\d+$/.test(p) || p in target || (target[p] = source[p]); return target; } /** * Return first letter capitalized * @param {string} str Target string * @returns {string} capitalized string * @private */ var capitalize = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); }, toArray = function (v) { return [].slice.call(v); }; /** * Convert to array * @param {object} v Target to be converted * @returns {Array} * @private */ /** * Get css rules for specified stylesheets * @param {Array} styleSheets The stylesheets to get the rules from * @returns {Array} * @private */ function getCssRules(styleSheets) { var rules = []; return styleSheets.forEach(function (sheet) { try { sheet.cssRules && sheet.cssRules.length && (rules = rules.concat(toArray(sheet.cssRules))); } catch (e) { console.error("Error while reading rules from " + sheet.href + ": " + e.toString()); } }), rules; } /** * Gets the SVGMatrix of an SVGGElement * @param {SVGElement} node Node element * @returns {SVGMatrix} matrix * @private */ var getTranslation = function (node) { var transform = node ? node.transform : null, baseVal = transform && transform.baseVal; return baseVal && baseVal.numberOfItems ? baseVal.getItem(0).matrix : { a: 0, b: 0, c: 0, d: 0, e: 0, f: 0 }; }; /** * Get unique value from array * @param {Array} data Source data * @returns {Array} Unique array value * @private */ function getUnique(data) { var isDate = data[0] instanceof Date, d = (isDate ? data.map(Number) : data).filter(function (v, i, self) { return self.indexOf(v) === i; }); return isDate ? d.map(function (v) { return new Date(v); }) : d; } /** * Merge array * @param {Array} arr Source array * @returns {Array} * @private */ function mergeArray(arr) { return arr && arr.length ? arr.reduce(function (p, c) { return p.concat(c); }) : []; } /** * Merge object returning new object * @param {object} target Target object * @param {object} objectN Source object * @returns {object} merged target object * @private */ function mergeObj(target) { for (var _len4 = arguments.length, objectN = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) objectN[_key4 - 1] = arguments[_key4]; if (!objectN.length || objectN.length === 1 && !objectN[0]) return target; var source = objectN.shift(); return isObject(target) && isObject(source) && Object.keys(source).forEach(function (key) { var value = source[key]; isObject(value) ? (!target[key] && (target[key] = {}), target[key] = mergeObj(target[key], value)) : target[key] = isArray(value) ? value.concat() : value; }), mergeObj.apply(void 0, [target].concat(objectN)); } /** * Sort value * @param {Array} data value to be sorted * @param {boolean} isAsc true: asc, false: desc * @returns {number|string|Date} sorted date * @private */ function sortValue(data, isAsc) { isAsc === void 0 && (isAsc = !0); var fn; return data[0] instanceof Date ? fn = isAsc ? function (a, b) { return a - b; } : function (a, b) { return b - a; } : isAsc && !data.every(isNaN) ? fn = function (a, b) { return a - b; } : !isAsc && (fn = function (a, b) { return a > b && -1 || a < b && 1 || a === b && 0; }), data.concat().sort(fn); } /** * Get min/max value * @param {string} type 'min' or 'max' * @param {Array} data Array data value * @returns {number|Date|undefined} * @private */ function getMinMax(type, data) { var res = data.filter(function (v) { return notEmpty(v); }); return res.length ? isNumber(res[0]) ? res = Math[type].apply(Math, res) : res[0] instanceof Date && (res = sortValue(res, type === "min")[0]) : res = undefined, res; } /** * Get range * @param {number} start Start number * @param {number} end End number * @param {number} step Step number * @returns {Array} * @private */ var getRange = function (start, end, step) { step === void 0 && (step = 1); var res = [], n = Math.max(0, Math.ceil((end - start) / step)) | 0; for (var i = start; i < n; i++) res.push(start + i * step); return res; }, emulateEvent = { mouse: function () { var getParams = function () { return { bubbles: !1, cancelable: !1, screenX: 0, screenY: 0, clientX: 0, clientY: 0 }; }; try { return new MouseEvent("t"), function (el, eventType, params) { params === void 0 && (params = getParams()), el.dispatchEvent(new MouseEvent(eventType, params)); }; } catch (e) { // Polyfills DOM4 MouseEvent return function (el, eventType, params) { params === void 0 && (params = getParams()); var mouseEvent = browser_doc.createEvent("MouseEvent"); // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, win, 0, // the event's mouse click count params.screenX, params.screenY, params.clientX, params.clientY, !1, !1, !1, !1, 0, null), el.dispatchEvent(mouseEvent); }; } }(), touch: function touch(el, eventType, params) { var touchObj = new Touch(mergeObj({ identifier: Date.now(), target: el, radiusX: 2.5, radiusY: 2.5, rotationAngle: 10, force: .5 }, params)); el.dispatchEvent(new TouchEvent(eventType, { cancelable: !0, bubbles: !0, shiftKey: !0, touches: [touchObj], targetTouches: [], changedTouches: [touchObj] })); } }; // emulate event /** * Process the template & return bound string * @param {string} tpl Template string * @param {object} data Data value to be replaced * @returns {string} * @private */ function tplProcess(tpl, data) { var res = tpl; for (var x in data) res = res.replace(new RegExp("{=" + x + "}", "g"), data[x]); return res; } /** * Get parsed date value * (It must be called in 'ChartInternal' context) * @param {Date|string|number} date Value of date to be parsed * @returns {Date} * @private */ function parseDate(date) { var parsedDate; if (date instanceof Date) parsedDate = date;else if (isString(date)) { var config = this.config, format = this.format; parsedDate = format.dataTime(config.data_xFormat)(date); } else isNumber(date) && !isNaN(date) && (parsedDate = new Date(+date)); return (!parsedDate || isNaN(+parsedDate)) && console && console.error && console.error("Failed to parse x '" + date + "' to Date object"), parsedDate; } /** * Return if the current doc is visible or not * @returns {boolean} * @private */ function isTabVisible() { return !browser_doc.hidden; } /** * Get the current input type * @param {boolean} mouse Config value: interaction.inputType.mouse * @param {boolean} touch Config value: interaction.inputType.touch * @returns {string} "mouse" | "touch" | null * @private */ function convertInputType(mouse, touch) { var isMobile = !1; // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent#Mobile_Tablet_or_Desktop if (/Mobi/.test(win.navigator.userAgent) && touch) { // Some Edge desktop return true: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/20417074/ var hasTouchPoints = win.navigator && "maxTouchPoints" in win.navigator && win.navigator.maxTouchPoints > 0, hasTouch = "ontouchmove" in win || win.DocumentTouch && browser_doc instanceof win.DocumentTouch; // Ref: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js // On IE11 with IE9 emulation mode, ('ontouchstart' in window) is returning true isMobile = hasTouchPoints || hasTouch; } var hasMouse = !(!mouse || isMobile) && "onmouseover" in win; return hasMouse && "mouse" || isMobile && "touch" || null; } ;// CONCATENATED MODULE: ./src/config/Options/Options.ts function Options_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function Options_objectSpread(target) { for (var source, i = 1; i < arguments.length; i++) source = arguments[i] == null ? {} : arguments[i], i % 2 ? Options_ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : Options_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); return target; } /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // common /** * Class to set options on generating chart. * - It's instantiated internally, not exposed for public. * @class Options * @see {@link bb.generate} to use these options on generating the chart */ var Options = /*#__PURE__*/function () { function Options() { return deepClone(main, data, color, interaction, legend, title, tooltip, Options.data); } return Options.setOptions = function setOptions(options) { this.data = options.reduce(function (a, c) { return Options_objectSpread(Options_objectSpread({}, a), c); }, this.data); }, Options; }(); Options.data = {}; ;// CONCATENATED MODULE: ./src/module/Cache.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Constant for cache key * - NOTE: Prefixed with '$', will be resetted when .load() is called * @private */ var KEY = { bubbleBaseLength: "$baseLength", colorPattern: "__colorPattern__", dataMinMax: "$dataMinMax", dataTotalSum: "$dataTotalSum", dataTotalPerIndex: "$totalPerIndex", legendItemTextBox: "legendItemTextBox", radarPoints: "$radarPoints", setOverOut: "setOverOut", callOverOutForTouch: "callOverOutForTouch", textRect: "textRect" }; var Cache = /*#__PURE__*/function () { function Cache() { this.cache = {}; } var _proto = Cache.prototype; return _proto.add = /** * Add cache * @param {string} key Cache key * @param {*} value Value to be stored * @param {boolean} isDataType Weather the cache is data typed '{id:'data', id_org: 'data', values: [{x:0, index:0,...}, ...]}' * @returns {*} Added data value * @private */ function add(key, value, isDataType) { return isDataType === void 0 && (isDataType = !1), this.cache[key] = isDataType ? this.cloneTarget(value) : value, this.cache[key]; } /** * Remove cache * @param {string|Array} key Cache key * @private */ , _proto.remove = function remove(key) { var _this = this; toArray(key).forEach(function (v) { return delete _this.cache[v]; }); } /** * Get cahce * @param {string|Array} key Cache key * @param {boolean} isDataType Weather the cache is data typed '{id:'data', id_org: 'data', values: [{x:0, index:0,...}, ...]}' * @returns {*} * @private */ , _proto.get = function get(key, isDataType) { if (isDataType === void 0 && (isDataType = !1), isDataType) { for (var id, targets = [], i = 0; id = key[i]; i++) id in this.cache && targets.push(this.cloneTarget(this.cache[id])); return targets; } var value = this.cache[key]; return isValue(value) ? value : null; } /** * Reset cached data * @param {boolean} all true: reset all data, false: reset only '$' prefixed key data * @private */ , _proto.reset = function reset(all) { var $$ = this; for (var x in $$.cache) (all || /^\$/.test(x)) && ($$.cache[x] = null); } /** * Clone data target object * @param {object} target Data object * @returns {object} * @private */ // eslint-disable-next-line camelcase , _proto.cloneTarget = function cloneTarget(target) { return { id: target.id, id_org: target.id_org, values: target.values.map(function (d) { return { x: d.x, value: d.value, id: d.id }; }) }; }, Cache; }(); ;// CONCATENATED MODULE: ./src/module/generator.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ var generator_setTimeout = win.setTimeout, generator_clearTimeout = win.clearTimeout; /** * Generate resize queue function * @returns {Fucntion} * @private */ function generateResize() { var timeout, fn = [], callResizeFn = function () { callResizeFn.clear(), timeout = generator_setTimeout(function () { fn.forEach(function (f) { return f(); }); }, 200); }; return callResizeFn.clear = function () { timeout && (generator_clearTimeout(timeout), timeout = null); }, callResizeFn.add = function (f) { return fn.push(f); }, callResizeFn.remove = function (f) { return fn.splice(fn.indexOf(f), 1); }, callResizeFn; } /** * Generate transition queue function * @returns {Function} * @private */ function generateWait() { var transitionsToWait = [], f = function (t, callback) { // eslint-disable-next-line function loop() { for (var _t, done = 0, i = 0; _t = transitionsToWait[i]; i++) { if (_t === !0 || _t.empty && _t.empty()) { done++; continue; } try { _t.transition(); } catch (e) { done++; } } timer && generator_clearTimeout(timer), done === transitionsToWait.length ? callback && callback() : timer = generator_setTimeout(loop, 50); } var timer; loop(); }; return f.add = function (t) { isArray(t) ? transitionsToWait = transitionsToWait.concat(t) : transitionsToWait.push(t); }, f; } // EXTERNAL MODULE: external {"commonjs":"d3-dsv","commonjs2":"d3-dsv","amd":"d3-dsv","root":"d3"} var external_commonjs_d3_dsv_commonjs2_d3_dsv_amd_d3_dsv_root_d3_ = __webpack_require__(5); ;// CONCATENATED MODULE: ./src/ChartInternal/data/convert.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Data convert * @memberof ChartInternal * @private */ /* harmony default export */ var convert = ({ /** * Convert data according its type * @param {object} args data object * @param {Function} [callback] callback for url(XHR) type loading * @returns {object} * @private */ convertData: function convertData(args, callback) { var data; if (args.bindto ? (data = {}, ["url", "mimeType", "headers", "keys", "json", "keys", "rows", "columns"].forEach(function (v) { var key = "data_" + v; key in args && (data[v] = args[key]); })) : data = args, data.url && callback) this.convertUrlToData(data.url, data.mimeType, data.headers, data.keys, callback);else if (data.json) data = this.convertJsonToData(data.json, data.keys);else if (data.rows) data = this.convertRowsToData(data.rows);else if (data.columns) data = this.convertColumnsToData(data.columns);else if (args.bindto) throw Error("url or json or rows or columns is required."); return isArray(data) && data; }, /** * Convert URL data * @param {string} url Remote URL * @param {string} mimeType MIME type string: json | csv | tsv * @param {object} headers Header object * @param {object} keys Key object * @param {Function} done Callback function * @private */ convertUrlToData: function convertUrlToData(url, mimeType, headers, keys, done) { var _this = this; mimeType === void 0 && (mimeType = "csv"); var req = new XMLHttpRequest(); req.open("GET", url), headers && Object.keys(headers).forEach(function (key) { req.setRequestHeader(key, headers[key]); }), req.onreadystatechange = function () { if (req.readyState === 4) if (req.status === 200) { var response = req.responseText; response && done.call(_this, _this["convert" + capitalize(mimeType) + "ToData"](mimeType === "json" ? JSON.parse(response) : response, keys)); } else throw new Error(url + ": Something went wrong loading!"); }, req.send(); }, /** * Convert CSV/TSV data * @param {object} parser Parser object * @param {object} xsv Data * @private * @returns {object} */ convertCsvTsvToData: function convertCsvTsvToData(parser, xsv) { var d, rows = parser.rows(xsv); return rows.length === 1 ? (d = [{}], rows[0].forEach(function (id) { d[0][id] = null; })) : d = parser.parse(xsv), d; }, convertCsvToData: function convertCsvToData(xsv) { return this.convertCsvTsvToData({ rows: external_commonjs_d3_dsv_commonjs2_d3_dsv_amd_d3_dsv_root_d3_.csvParseRows, parse: external_commonjs_d3_dsv_commonjs2_d3_dsv_amd_d3_dsv_root_d3_.csvParse }, xsv); }, convertTsvToData: function convertTsvToData(tsv) { return this.convertCsvTsvToData({ rows: external_commonjs_d3_dsv_commonjs2_d3_dsv_amd_d3_dsv_root_d3_.tsvParseRows, parse: external_commonjs_d3_dsv_commonjs2_d3_dsv_amd_d3_dsv_root_d3_.tsvParse }, tsv); }, convertJsonToData: function convertJsonToData(json, keysParam) { var targetKeys, data, _this2 = this, config = this.config, newRows = []; if (isArray(json)) { var keys = keysParam || config.data_keys; keys.x ? (targetKeys = keys.value.concat(keys.x), config.data_x = keys.x) : targetKeys = keys.value, newRows.push(targetKeys), json.forEach(function (o) { var newRow = targetKeys.map(function (key) { // convert undefined to null because undefined data will be removed in convertDataToTargets() var v = _this2.findValueInJson(o, key); return isUndefined(v) && (v = null), v; }); newRows.push(newRow); }), data = this.convertRowsToData(newRows); } else Object.keys(json).forEach(function (key) { var tmp = json[key].concat(); tmp.unshift(key), newRows.push(tmp); }), data = this.convertColumnsToData(newRows); return data; }, findValueInJson: function findValueInJson(object, path) { if (object[path] !== undefined) return object[path]; var convertedPath = path.replace(/\[(\w+)\]/g, ".$1"), pathArray = convertedPath.replace(/^\./, "").split("."), target = object; // convert indexes to properties (replace [] with .) return pathArray.some(function (k) { return !(target = target && k in target ? target[k] : undefined); }), target; }, convertRowsToData: function convertRowsToData(rows) { var keys = rows[0], newRows = []; return rows.forEach(function (row, i) { if (i > 0) { var newRow = {}; row.forEach(function (v, j) { if (isUndefined(v)) throw new Error("Source data is missing a component at (" + i + ", " + j + ")!"); newRow[keys[j]] = v; }), newRows.push(newRow); } }), newRows; }, convertColumnsToData: function convertColumnsToData(columns) { var newRows = []; return columns.forEach(function (col, i) { var key = col[0]; col.forEach(function (v, j) { if (j > 0) { if (isUndefined(newRows[j - 1]) && (newRows[j - 1] = {}), isUndefined(v)) throw new Error("Source data is missing a component at (" + i + ", " + j + ")!"); newRows[j - 1][key] = v; } }); }), newRows; }, convertDataToTargets: function convertDataToTargets(data, appendXs) { var _this3 = this, $$ = this, axis = $$.axis, config = $$.config, state = $$.state, isCategorized = !1, isTimeSeries = !1, isCustomX = !1; axis && (isCategorized = axis.isCategorized(), isTimeSeries = axis.isTimeSeries(), isCustomX = axis.isCustomX()); var xsData, dataKeys = Object.keys(data[0] || {}), ids = dataKeys.length ? dataKeys.filter($$.isNotX, $$) : [], xs = dataKeys.length ? dataKeys.filter($$.isX, $$) : []; ids.forEach(function (id) { var xKey = _this3.getXKey(id); isCustomX || isTimeSeries ? xs.indexOf(xKey) >= 0 ? xsData = (appendXs && $$.data.xs[id] || []).concat(data.map(function (d) { return d[xKey]; }).filter(isValue).map(function (rawX, i) { return $$.generateTargetX(rawX, id, i); })) : config.data_x ? xsData = _this3.getOtherTargetXs() : notEmpty(config.data_xs) && (xsData = $$.getXValuesOfXKey(xKey, $$.data.targets)) : xsData = data.map(function (d, i) { return i; }), xsData && (_this3.data.xs[id] = xsData); }), ids.forEach(function (id) { if (!_this3.data.xs[id]) throw new Error("x is not defined for id = \"" + id + "\"."); }); // convert to target var targets = ids.map(function (id, index) { var convertedId = config.data_idConverter.bind($$.api)(id), xKey = $$.getXKey(id), isCategory = isCustomX && isCategorized, hasCategory = isCategory && data.map(function (v) { return v.x; }).every(function (v) { return config.axis_x_categories.indexOf(v) > -1; }); return { id: convertedId, id_org: id, values: data.map(function (d, i) { var x, rawX = d[xKey], value = d[id]; return value = value === null || isNaN(value) || isObject(value) ? isArray(value) || isObject(value) ? value : null : +value, (isCategory || state.hasRadar) && index === 0 && !isUndefined(rawX) ? (!hasCategory && index === 0 && i === 0 && (config.axis_x_categories = []), x = config.axis_x_categories.indexOf(rawX), x === -1 && (x = config.axis_x_categories.length, config.axis_x_categories.push(rawX))) : x = $$.generateTargetX(rawX, id, i), (isUndefined(value) || $$.data.xs[id].length <= i) && (x = undefined), { x: x, value: value, id: convertedId }; }).filter(function (v) { return isDefined(v.x); }) }; }); // finish targets return targets.forEach(function (t) { config.data_xSort && (t.values = t.values.sort(function (v1, v2) { var x1 = v1.x || v1.x === 0 ? v1.x : Infinity, x2 = v2.x || v2.x === 0 ? v2.x : Infinity; return x1 - x2; })), t.values.forEach(function (v, i) { return v.index = i; }), $$.data.xs[t.id].sort(function (v1, v2) { return v1 - v2; }); }), state.hasNegativeValue = $$.hasNegativeValueInTargets(targets), state.hasPositiveValue = $$.hasPositiveValueInTargets(targets), config.data_type && $$.setTargetType($$.mapToIds(targets).filter(function (id) { return !(id in config.data_types); }), config.data_type), targets.forEach(function (d) { return $$.cache.add(d.id_org, d, !0); }), targets; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/data/data.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var data_data = ({ isX: function isX(key) { var $$ = this, config = $$.config, dataKey = config.data_x && key === config.data_x, existValue = notEmpty(config.data_xs) && hasValue(config.data_xs, key); return dataKey || existValue; }, isNotX: function isNotX(key) { return !this.isX(key); }, isStackNormalized: function isStackNormalized() { var config = this.config; return !!(config.data_stack_normalize && config.data_groups.length); }, isGrouped: function isGrouped(id) { var groups = this.config.data_groups; return id ? groups.some(function (v) { return v.indexOf(id) >= 0 && v.length > 1; }) : groups.length > 0; }, getXKey: function getXKey(id) { var $$ = this, config = $$.config; return config.data_x ? config.data_x : notEmpty(config.data_xs) ? config.data_xs[id] : null; }, getXValuesOfXKey: function getXValuesOfXKey(key, targets) { var xValues, $$ = this, ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : []; return ids.forEach(function (id) { $$.getXKey(id) === key && (xValues = $$.data.xs[id]); }), xValues; }, /** * Get index number based on given x Axis value * @param {Date|number|string} x x Axis to be compared * @param {Array} basedX x Axis list to be based on * @returns {number} index number * @private */ getIndexByX: function getIndexByX(x, basedX) { var $$ = this; return basedX ? basedX.indexOf(isString(x) ? x : +x) : ($$.filterByX($$.data.targets, x)[0] || { index: null }).index; }, getXValue: function getXValue(id, i) { var $$ = this; return id in $$.data.xs && $$.data.xs[id] && isValue($$.data.xs[id][i]) ? $$.data.xs[id][i] : i; }, getOtherTargetXs: function getOtherTargetXs() { var $$ = this, idsForX = Object.keys($$.data.xs); return idsForX.length ? $$.data.xs[idsForX[0]] : null; }, getOtherTargetX: function getOtherTargetX(index) { var xs = this.getOtherTargetXs(); return xs && index < xs.length ? xs[index] : null; }, addXs: function addXs(xs) { var $$ = this, config = $$.config; Object.keys(xs).forEach(function (id) { config.data_xs[id] = xs[id]; }); }, isMultipleX: function isMultipleX() { return notEmpty(this.config.data_xs) || !this.config.data_xSort || this.hasType("bubble") || this.hasType("scatter"); }, addName: function addName(data) { var name, $$ = this, config = $$.config; return data && (name = config.data_names[data.id], data.name = name === undefined ? data.id : name), data; }, /** * Get all values on given index * @param {number} index Index * @param {boolean} filterNull Filter nullish value * @returns {Array} * @private */ getAllValuesOnIndex: function getAllValuesOnIndex(index, filterNull) { filterNull === void 0 && (filterNull = !1); var $$ = this, value = $$.filterTargetsToShow($$.data.targets).map(function (t) { return $$.addName($$.getValueOnIndex(t.values, index)); }); return filterNull && (value = value.filter(function (v) { return isValue(v.value); })), value; }, getValueOnIndex: function getValueOnIndex(values, index) { var valueOnIndex = values.filter(function (v) { return v.index === index; }); return valueOnIndex.length ? valueOnIndex[0] : null; }, updateTargetX: function updateTargetX(targets, x) { var $$ = this; targets.forEach(function (t) { t.values.forEach(function (v, i) { v.x = $$.generateTargetX(x[i], t.id, i); }), $$.data.xs[t.id] = x; }); }, updateTargetXs: function updateTargetXs(targets, xs) { var $$ = this; targets.forEach(function (t) { xs[t.id] && $$.updateTargetX([t], xs[t.id]); }); }, generateTargetX: function generateTargetX(rawX, id, index) { var $$ = this, axis = $$.axis, x = axis && axis.isCategorized() ? index : rawX || index; if (axis && axis.isTimeSeries()) { var fn = parseDate.bind($$); x = rawX ? fn(rawX) : fn($$.getXValue(id, index)); } else axis && axis.isCustomX() && !axis.isCategorized() && (x = isValue(rawX) ? +rawX : $$.getXValue(id, index)); return x; }, updateXs: function updateXs(values) { values.length && (this.axis.xs = values.map(function (v) { return v.x; })); }, getPrevX: function getPrevX(i) { var x = this.axis.xs[i - 1]; return isDefined(x) ? x : null; }, getNextX: function getNextX(i) { var x = this.axis.xs[i + 1]; return isDefined(x) ? x : null; }, /** * Get base value isAreaRangeType * @param {object} data Data object * @returns {number} * @private */ getBaseValue: function getBaseValue(data) { var $$ = this, hasAxis = $$.state.hasAxis, value = data.value; return value && hasAxis && ($$.isAreaRangeType(data) ? value = $$.getRangedData(data, "mid") : $$.isBubbleZType(data) && (value = $$.getBubbleZData(value, "y"))), value; }, /** * Get min/max value from the data * @private * @param {Array} data array data to be evaluated * @returns {{min: {number}, max: {number}}} */ getMinMaxValue: function getMinMaxValue(data) { var min, max, getBaseValue = this.getBaseValue.bind(this); return (data || this.data.targets.map(function (t) { return t.values; })).forEach(function (v, i) { var value = v.map(getBaseValue).filter(isNumber); min = Math.min.apply(Math, [i ? min : Infinity].concat(value)), max = Math.max.apply(Math, [i ? max : -Infinity].concat(value)); }), { min: min, max: max }; }, /** * Get the min/max data * @private * @returns {{min: Array, max: Array}} */ getMinMaxData: function getMinMaxData() { var $$ = this, cacheKey = KEY.dataMinMax, minMaxData = $$.cache.get(cacheKey); if (!minMaxData) { var data = $$.data.targets.map(function (t) { return t.values; }), minMax = $$.getMinMaxValue(data), min = [], max = []; // update the cached data data.forEach(function (v) { var minData = $$.getFilteredDataByValue(v, minMax.min), maxData = $$.getFilteredDataByValue(v, minMax.max); minData.length && (min = min.concat(minData)), maxData.length && (max = max.concat(maxData)); }), $$.cache.add(cacheKey, minMaxData = { min: min, max: max }); } return minMaxData; }, /** * Get sum of data per index * @private * @returns {Array} */ getTotalPerIndex: function getTotalPerIndex() { var $$ = this, cacheKey = KEY.dataTotalPerIndex, sum = $$.cache.get(cacheKey); return $$.isStackNormalized() && !sum && (sum = [], $$.data.targets.forEach(function (row) { row.values.forEach(function (v, i) { sum[i] || (sum[i] = 0), sum[i] += isNumber(v.value) ? v.value : 0; }); })), sum; }, /** * Get total data sum * @param {boolean} subtractHidden Subtract hidden data from total * @returns {number} * @private */ getTotalDataSum: function getTotalDataSum(subtractHidden) { var $$ = this, cacheKey = KEY.dataTotalSum, total = $$.cache.get(cacheKey); if (!isNumber(total)) { var sum = mergeArray($$.data.targets.map(function (t) { return t.values; })).map(function (v) { return v.value; }).reduce(function (p, c) { return p + c; }); $$.cache.add(cacheKey, total = sum); } return subtractHidden && (total -= $$.getHiddenTotalDataSum()), total; }, /** * Get total hidden data sum * @returns {number} * @private */ getHiddenTotalDataSum: function getHiddenTotalDataSum() { var $$ = this, api = $$.api, hiddenTargetIds = $$.state.hiddenTargetIds, total = 0; return hiddenTargetIds.length && (total = api.data.values.bind(api)(hiddenTargetIds).reduce(function (p, c) { return p + c; })), total; }, /** * Get filtered data by value * @param {object} data Data * @param {number} value Value to be filtered * @returns {Array} filtered array data * @private */ getFilteredDataByValue: function getFilteredDataByValue(data, value) { var _this = this; return data.filter(function (t) { return _this.getBaseValue(t) === value; }); }, /** * Return the max length of the data * @returns {number} max data length * @private */ getMaxDataCount: function getMaxDataCount() { return Math.max.apply(Math, this.data.targets.map(function (t) { return t.values.length; })); }, getMaxDataCountTarget: function getMaxDataCountTarget() { var target = this.filterTargetsToShow() || [], length = target.length; return length > 1 ? (target = target.map(function (t) { return t.values; }).reduce(function (a, b) { return a.concat(b); }).map(function (v) { return v.x; }), target = sortValue(getUnique(target)).map(function (x, index) { return { x: x, index: index }; })) : length && (target = target[0].values), target; }, mapToIds: function mapToIds(targets) { return targets.map(function (d) { return d.id; }); }, mapToTargetIds: function mapToTargetIds(ids) { var $$ = this; return ids ? isArray(ids) ? ids.concat() : [ids] : $$.mapToIds($$.data.targets); }, hasTarget: function hasTarget(targets, id) { var ids = this.mapToIds(targets); for (var val, i = 0; val = ids[i]; i++) if (val === id) return !0; return !1; }, isTargetToShow: function isTargetToShow(targetId) { return this.state.hiddenTargetIds.indexOf(targetId) < 0; }, isLegendToShow: function isLegendToShow(targetId) { return this.state.hiddenLegendIds.indexOf(targetId) < 0; }, filterTargetsToShow: function filterTargetsToShow(targets) { var $$ = this; return (targets || $$.data.targets).filter(function (t) { return $$.isTargetToShow(t.id); }); }, mapTargetsToUniqueXs: function mapTargetsToUniqueXs(targets) { var $$ = this, axis = $$.axis, xs = []; return targets && targets.length && (xs = getUnique(mergeArray(targets.map(function (t) { return t.values.map(function (v) { return +v.x; }); }))), xs = axis && axis.isTimeSeries() ? xs.map(function (x) { return new Date(+x); }) : xs.map(function (x) { return +x; })), sortValue(xs); }, addHiddenTargetIds: function addHiddenTargetIds(targetIds) { this.state.hiddenTargetIds = this.state.hiddenTargetIds.concat(targetIds); }, removeHiddenTargetIds: function removeHiddenTargetIds(targetIds) { this.state.hiddenTargetIds = this.state.hiddenTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); }, addHiddenLegendIds: function addHiddenLegendIds(targetIds) { this.state.hiddenLegendIds = this.state.hiddenLegendIds.concat(targetIds); }, removeHiddenLegendIds: function removeHiddenLegendIds(targetIds) { this.state.hiddenLegendIds = this.state.hiddenLegendIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); }, getValuesAsIdKeyed: function getValuesAsIdKeyed(targets) { var $$ = this, hasAxis = $$.state.hasAxis, ys = {}, isMultipleX = $$.isMultipleX(), xs = isMultipleX ? $$.mapTargetsToUniqueXs(targets).map(function (v) { return isString(v) ? v : +v; }) : null; return targets.forEach(function (t) { var data = []; t.values.filter(function (v) { return isValue(v.value); }).forEach(function (v) { var value = v.value; // exclude 'volume' value to correct mis domain calculation $$.isCandlestickType(v) && (value = isArray(value) ? value.slice(0, 4) : [value.open, value.high, value.low, value.close]), isArray(value) ? data.push.apply(data, value) : isObject(value) && "high" in value ? data.push.apply(data, Object.values(value)) : $$.isBubbleZType(v) ? data.push(hasAxis && $$.getBubbleZData(value, "y")) : isMultipleX ? data[$$.getIndexByX(v.x, xs)] = value : data.push(value); }), ys[t.id] = data; }), ys; }, checkValueInTargets: function checkValueInTargets(targets, checker) { var values, ids = Object.keys(targets); for (var i = 0; i < ids.length; i++) { values = targets[ids[i]].values; for (var j = 0; j < values.length; j++) if (checker(values[j].value)) return !0; } return !1; }, hasMultiTargets: function hasMultiTargets() { return this.filterTargetsToShow().length > 1; }, hasNegativeValueInTargets: function hasNegativeValueInTargets(targets) { return this.checkValueInTargets(targets, function (v) { return v < 0; }); }, hasPositiveValueInTargets: function hasPositiveValueInTargets(targets) { return this.checkValueInTargets(targets, function (v) { return v > 0; }); }, _checkOrder: function _checkOrder(type) { var config = this.config, order = config.data_order; return isString(order) && order.toLowerCase() === type; }, isOrderDesc: function isOrderDesc() { return this._checkOrder("desc"); }, isOrderAsc: function isOrderAsc() { return this._checkOrder("asc"); }, /** * Sort targets data * @param {Array} targetsValue Target value * @returns {Array} * @private */ orderTargets: function orderTargets(targetsValue) { var $$ = this, targets = [].concat(targetsValue), fn = $$.getSortCompareFn(); return fn && targets.sort(fn), targets; }, /** * Get data.order compare function * @param {boolean} isArc Is for Arc type sort or not * @returns {Function} compare function * @private */ getSortCompareFn: function getSortCompareFn(isArc) { isArc === void 0 && (isArc = !1); var fn, $$ = this, config = $$.config, orderAsc = $$.isOrderAsc(), orderDesc = $$.isOrderDesc(); return orderAsc || orderDesc ? fn = function (t1, t2) { var reducer = function (p, c) { return p + Math.abs(c.value); }, t1Sum = t1.values.reduce(reducer, 0), t2Sum = t2.values.reduce(reducer, 0); return isArc ? orderAsc ? t1Sum - t2Sum : t2Sum - t1Sum : orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum; } : isFunction(config.data_order) && (fn = config.data_order.bind($$.api)), fn || null; }, filterByX: function filterByX(targets, x) { return mergeArray(targets.map(function (t) { return t.values; })).filter(function (v) { return v.x - x === 0; }); }, filterRemoveNull: function filterRemoveNull(data) { var _this2 = this; return data.filter(function (d) { return isValue(_this2.getBaseValue(d)); }); }, filterByXDomain: function filterByXDomain(targets, xDomain) { return targets.map(function (t) { return { id: t.id, id_org: t.id_org, values: t.values.filter(function (v) { return xDomain[0] <= v.x && v.x <= xDomain[1]; }) }; }); }, hasDataLabel: function hasDataLabel() { var dataLabels = this.config.data_labels; return isboolean(dataLabels) && dataLabels || isObjectType(dataLabels) && notEmpty(dataLabels); }, /** * Get data index from the event coodinates * @param {Event} event Event object * @returns {number} */ getDataIndexFromEvent: function getDataIndexFromEvent(event) { var $$ = this, config = $$.config, _$$$state = $$.state, inputType = _$$$state.inputType, _$$$state$eventReceiv = _$$$state.eventReceiver, coords = _$$$state$eventReceiv.coords, rect = _$$$state$eventReceiv.rect, isRotated = config.axis_rotated, e = inputType === "touch" && event.changedTouches ? event.changedTouches[0] : event, index = findIndex(coords, isRotated ? e.clientY - rect.top : e.clientX - rect.left, 0, coords.length - 1, isRotated); return index; }, getDataLabelLength: function getDataLabelLength(min, max, key) { var $$ = this, lengths = [0, 0]; return $$.$el.chart.select("svg").selectAll(".dummy").data([min, max]).enter().append("text").text(function (d) { return $$.dataLabelFormat(d.id)(d); }).each(function (d, i) { lengths[i] = this.getBoundingClientRect()[key] * 1.3; }).remove(), lengths; }, isNoneArc: function isNoneArc(d) { return this.hasTarget(this.data.targets, d.id); }, isArc: function isArc(d) { return "data" in d && this.hasTarget(this.data.targets, d.data.id); }, findSameXOfValues: function findSameXOfValues(values, index) { var i, targetX = values[index].x, sames = []; for (i = index - 1; i >= 0 && !(targetX !== values[i].x); i--) sames.push(values[i]); for (i = index; i < values.length && !(targetX !== values[i].x); i++) sames.push(values[i]); return sames; }, findClosestFromTargets: function findClosestFromTargets(targets, pos) { var $$ = this, candidates = targets.map(function (target) { return $$.findClosest(target.values, pos); }); // map to array of closest points of each target // decide closest point and return return $$.findClosest(candidates, pos); }, findClosest: function findClosest(values, pos) { var closest, $$ = this, config = $$.config, main = $$.$el.main, data = values.filter(function (v) { return v && isValue(v.value); }), minDist = config.point_sensitivity; return data.filter(function (v) { return $$.isBarType(v.id); }).forEach(function (v) { var shape = main.select("." + config_classes.bars + $$.getTargetSelectorSuffix(v.id) + " ." + config_classes.bar + "-" + v.index).node(); !closest && $$.isWithinBar(shape) && (closest = v); }), data.filter(function (v) { return !$$.isBarType(v.id); }).forEach(function (v) { var d = $$.dist(v, pos); d < minDist && (minDist = d, closest = v); }), closest; }, dist: function dist(data, pos) { var $$ = this, isRotated = $$.config.axis_rotated, scale = $$.scale, xIndex = isRotated ? 1 : 0, yIndex = isRotated ? 0 : 1, y = $$.circleY(data, data.index), x = (scale.zoom || scale.x)(data.x); return Math.sqrt(Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2)); }, /** * Convert data for step type * @param {Array} values Object data values * @returns {Array} * @private */ convertValuesToStep: function convertValuesToStep(values) { var $$ = this, axis = $$.axis, config = $$.config, stepType = config.line_step_type, isCategorized = !!axis && axis.isCategorized(), converted = isArray(values) ? values.concat() : [values]; if (!(isCategorized || /step\-(after|before)/.test(stepType))) return values; // insert & append cloning first/last value to be fully rendered covering on each gap sides var head = converted[0], tail = converted[converted.length - 1], id = head.id, x = head.x; return converted.unshift({ x: --x, value: head.value, id: id }), isCategorized && stepType === "step-after" && converted.unshift({ x: --x, value: head.value, id: id }), x = tail.x, converted.push({ x: ++x, value: tail.value, id: id }), isCategorized && stepType === "step-before" && converted.push({ x: ++x, value: tail.value, id: id }), converted; }, convertValuesToRange: function convertValuesToRange(values) { var converted = isArray(values) ? values.concat() : [values], ranges = []; return converted.forEach(function (range) { var x = range.x, id = range.id; ranges.push({ x: x, id: id, value: range.value[0] }), ranges.push({ x: x, id: id, value: range.value[2] }); }), ranges; }, updateDataAttributes: function updateDataAttributes(name, attrs) { var $$ = this, config = $$.config, current = config["data_" + name]; return isUndefined(attrs) ? current : (Object.keys(attrs).forEach(function (id) { current[id] = attrs[id]; }), $$.redraw({ withLegend: !0 }), current); }, getRangedData: function getRangedData(d, key, type) { key === void 0 && (key = ""), type === void 0 && (type = "areaRange"); var value = d == null ? void 0 : d.value; if (isArray(value)) { // @ts-ignore var index = { areaRange: ["high", "mid", "low"], candlestick: ["open", "high", "low", "close", "volume"] }[type].indexOf(key); return index >= 0 && value ? value[index] : undefined; } return value ? value[key] : value; }, /** * Get ratio value * @param {string} type Ratio for given type * @param {object} d Data value object * @param {boolean} asPercent Convert the return as percent or not * @returns {number} Ratio value * @private */ getRatio: function getRatio(type, d, asPercent) { var $$ = this, config = $$.config, state = $$.state, api = $$.api, ratio = 0; if (d && api.data.shown().length) if (ratio = d.ratio || d.value, type === "arc") { // if has padAngle set, calculate rate based on value if ($$.pie.padAngle()()) ratio = d.value / $$.getTotalDataSum(!0);else { var gaugeArcLength = config.gauge_fullCircle ? $$.getArcLength() : $$.getStartAngle() * -2, arcLength = $$.hasType("gauge") ? gaugeArcLength : Math.PI * 2; ratio = (d.endAngle - d.startAngle) / arcLength; } } else if (type === "index") { var dataValues = api.data.values.bind(api), total = this.getTotalPerIndex(); if (state.hiddenTargetIds.length) { var hiddenSum = dataValues(state.hiddenTargetIds, !1); hiddenSum.length && (hiddenSum = hiddenSum.reduce(function (acc, curr) { return acc.map(function (v, i) { return (isNumber(v) ? v : 0) + curr[i]; }); }), total = total.map(function (v, i) { return v - hiddenSum[i]; })); } d.ratio = isNumber(d.value) && total && total[d.index] > 0 ? d.value / total[d.index] : 0, ratio = d.ratio; } else if (type === "radar") ratio = parseFloat(Math.max(d.value, 0) + "") / state.current.dataMax * config.radar_size_ratio;else if (type === "bar") { var yScale = $$.getYScaleById.bind($$)(d.id), max = yScale.domain().reduce(function (a, c) { return c - a; }); ratio = Math.abs(d.value) / max; } return asPercent && ratio ? ratio * 100 : ratio; }, /** * Sort data index to be aligned with x axis. * @param {Array} tickValues Tick array values * @private */ updateDataIndexByX: function updateDataIndexByX(tickValues) { var $$ = this, tickValueMap = tickValues.reduce(function (out, tick, index) { return out[+tick.x] = index, out; }, {}); $$.data.targets.forEach(function (t) { t.values.forEach(function (value, valueIndex) { var index = tickValueMap[+value.x]; index === undefined && (index = valueIndex), value.index = index; }); }); }, /** * Determine if bubble has dimension data * @param {object|Array} d data value * @returns {boolean} * @private */ isBubbleZType: function isBubbleZType(d) { var $$ = this; return $$.isBubbleType(d) && (isObject(d.value) && ("z" in d.value || "y" in d.value) || isArray(d.value) && d.value.length === 2); }, /** * Get data object by id * @param {string} id data id * @returns {object} * @private */ getDataById: function getDataById(id) { var d = this.cache.get(id) || this.api.data(id); return isArray(d) ? d[0] : d; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/data/load.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var load = ({ load: function load(rawTargets, args) { var $$ = this, targets = rawTargets; // Set targets // Redraw with new targets // Update current state chart type and elements list after redraw targets && (args.filter && (targets = targets.filter(args.filter)), (args.type || args.types) && targets.forEach(function (t) { var type = args.types && args.types[t.id] || args.type; $$.setTargetType(t.id, type); }), $$.data.targets.forEach(function (d) { for (var i = 0; i < targets.length; i++) if (d.id === targets[i].id) { d.values = targets[i].values, targets.splice(i, 1); break; } }), $$.data.targets = $$.data.targets.concat(targets)), $$.updateTargets($$.data.targets), $$.redraw({ withUpdateOrgXDomain: !0, withUpdateXDomain: !0, withLegend: !0 }), $$.updateTypesElements(), args.done && args.done.call($$.api); }, loadFromArgs: function loadFromArgs(args) { var $$ = this; // prevent load when chart is already destroyed if ($$.config) { $$.cache.reset(); var data = args.data || $$.convertData(args, function (d) { return $$.load($$.convertDataToTargets(d), args); }); data && $$.load($$.convertDataToTargets(data), args); } // reset internally cached data }, unload: function unload(rawTargetIds, customDoneCb) { var $$ = this, state = $$.state, $el = $$.$el, done = customDoneCb, targetIds = rawTargetIds; // If no target, call done and return return $$.cache.reset(), done || (done = function () {}), targetIds = targetIds.filter(function (id) { return $$.hasTarget($$.data.targets, id); }), targetIds && targetIds.length !== 0 ? void ( // Update current state chart type and elements list after redraw $el.svg.selectAll(targetIds.map(function (id) { return $$.selectorTarget(id); })).transition().style("opacity", "0").remove().call(endall, done), targetIds.forEach(function (id) { state.withoutFadeIn[id] = !1, $el.legend && $el.legend.selectAll("." + config_classes.legendItem + $$.getTargetSelectorSuffix(id)).remove(), $$.data.targets = $$.data.targets.filter(function (t) { return t.id !== id; }); }), $$.updateTypesElements()) : void done(); } }); // EXTERNAL MODULE: external {"commonjs":"d3-drag","commonjs2":"d3-drag","amd":"d3-drag","root":"d3"} var external_commonjs_d3_drag_commonjs2_d3_drag_amd_d3_drag_root_d3_ = __webpack_require__(7); ;// CONCATENATED MODULE: ./src/ChartInternal/interactions/interaction.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var interactions_interaction = ({ selectRectForSingle: function selectRectForSingle(context, eventRect, index) { var $$ = this, config = $$.config, main = $$.$el.main, isSelectionEnabled = config.data_selection_enabled, isSelectionGrouped = config.data_selection_grouped, isSelectable = config.data_selection_isselectable, isTooltipGrouped = config.tooltip_grouped, selectedData = $$.getAllValuesOnIndex(index); isTooltipGrouped && ($$.showTooltip(selectedData, context), $$.showGridFocus && $$.showGridFocus(selectedData), !isSelectionEnabled || isSelectionGrouped) || main.selectAll("." + config_classes.shape + "-" + index).each(function () { (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).classed(config_classes.EXPANDED, !0), isSelectionEnabled && eventRect.style("cursor", isSelectionGrouped ? "pointer" : null), isTooltipGrouped || ($$.hideGridFocus && $$.hideGridFocus(), $$.hideTooltip(), !isSelectionGrouped && $$.setExpand(index)); }).filter(function (d) { return $$.isWithinShape(this, d); }).call(function (selected) { var d = selected.data(); isSelectionEnabled && (isSelectionGrouped || isSelectable && isSelectable.bind($$.api)(d)) && eventRect.style("cursor", "pointer"), isTooltipGrouped || ($$.showTooltip(d, context), $$.showGridFocus && $$.showGridFocus(d), $$.unexpandCircles && $$.unexpandCircles(), selected.each(function (d) { return $$.setExpand(index, d.id); })); }); }, /** * Expand data shape/point * @param {number} index Index number * @param {string} id Data id * @param {boolean} reset Reset expand state * @private */ setExpand: function setExpand(index, id, reset) { var $$ = this, config = $$.config, circle = $$.$el.circle; // bar, candlestick circle && config.point_focus_expand_enabled && $$.expandCircles(index, id, reset), $$.expandBarTypeShapes(!0, index, id, reset); }, /** * Expand/Unexpand bar type shapes * @param {boolean} expand Expand or unexpand * @param {number} i Shape index * @param {string} id Data id * @param {boolean} reset Reset expand style * @private */ expandBarTypeShapes: function expandBarTypeShapes(expand, i, id, reset) { expand === void 0 && (expand = !0); var $$ = this; ["bar", "candlestick"].filter(function (v) { return $$.$el[v]; }).forEach(function (v) { reset && $$.$el[v].classed(config_classes.EXPANDED, !1), $$.getShapeByIndex(v, i, id).classed(config_classes.EXPANDED, expand); }); }, /** * Handle data.onover/out callback options * @param {boolean} isOver Over or not * @param {number|object} d data object * @private */ setOverOut: function setOverOut(isOver, d) { var $$ = this, config = $$.config, hasRadar = $$.state.hasRadar, main = $$.$el.main, isArc = isObject(d); // Call event handler if (isArc || d !== -1) { var callback = config[isOver ? "data_onover" : "data_onout"].bind($$.api); if (config.color_onover && $$.setOverColor(isOver, d, isArc), isArc) callback(d, main.select("." + config_classes.arc + $$.getTargetSelectorSuffix(d.id)).node());else if (!config.tooltip_grouped) { var last = $$.cache.get(KEY.setOverOut) || [], shape = main.selectAll("." + config_classes.shape + "-" + d).filter(function (d) { return $$.isWithinShape(this, d); }); shape.each(function (d) { var _this = this; (last.length === 0 || last.every(function (v) { return v !== _this; })) && (callback(d, this), last.push(this)); }), last.length > 0 && shape.empty() && (callback = config.data_onout.bind($$.api), last.forEach(function (v) { return callback((0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(v).datum(), v); }), last = []), $$.cache.add(KEY.setOverOut, last); } else isOver && (config.point_focus_only && hasRadar ? $$.showCircleFocus($$.getAllValuesOnIndex(d, !0)) : $$.setExpand(d, null, !0)), $$.isMultipleX() || main.selectAll("." + config_classes.shape + "-" + d).each(function (d) { callback(d, this); }); } }, /** * Call data.onover/out callback for touch event * @param {number|object} d target index or data object for Arc type * @private */ callOverOutForTouch: function callOverOutForTouch(d) { var $$ = this, last = $$.cache.get(KEY.callOverOutForTouch); (isObject(d) && last ? d.id !== last.id : d !== last) && ((last || isNumber(last)) && $$.setOverOut(!1, last), (d || isNumber(d)) && $$.setOverOut(!0, d), $$.cache.add(KEY.callOverOutForTouch, d)); }, /** * Return draggable selection function * @returns {Function} * @private */ getDraggableSelection: function getDraggableSelection() { var $$ = this, config = $$.config, state = $$.state; return config.interaction_enabled && config.data_selection_draggable && $$.drag ? (0,external_commonjs_d3_drag_commonjs2_d3_drag_amd_d3_drag_root_d3_.drag)().on("drag", function (event) { state.event = event, $$.drag(getPointer(event, this)); }).on("start", function (event) { state.event = event, $$.dragstart(getPointer(event, this)); }).on("end", function (event) { state.event = event, $$.dragend(); }) : function () {}; }, /** * Dispatch a mouse event. * @private * @param {string} type event type * @param {number} index Index of eventRect * @param {Array} mouse x and y coordinate value */ dispatchEvent: function dispatchEvent(type, index, mouse) { var $$ = this, config = $$.config, _$$$state = $$.state, eventReceiver = _$$$state.eventReceiver, hasAxis = _$$$state.hasAxis, hasRadar = _$$$state.hasRadar, _$$$$el = $$.$el, eventRect = _$$$$el.eventRect, arcs = _$$$$el.arcs, radar = _$$$$el.radar, isMultipleX = $$.isMultipleX(), element = (hasRadar ? radar.axes.select("." + config_classes.axis + "-" + index + " text") : eventRect || arcs.selectAll("." + config_classes.target + " path").filter(function (d, i) { return i === index; })).node(), _element$getBoundingC = element.getBoundingClientRect(), width = _element$getBoundingC.width, left = _element$getBoundingC.left, top = _element$getBoundingC.top; if (hasAxis && !hasRadar && !isMultipleX) { var coords = eventReceiver.coords[index]; width = coords.w, left += coords.x, top += coords.y; } var x = left + (mouse ? mouse[0] : 0) + (isMultipleX || config.axis_rotated ? 0 : width / 2), y = top + (mouse ? mouse[1] : 0); emulateEvent[/^(mouse|click)/.test(type) ? "mouse" : "touch"](element, type, { screenX: x, screenY: y, clientX: x, clientY: y }); }, setDragStatus: function setDragStatus(isDragging) { this.state.dragging = isDragging; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/class.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var internals_class = ({ generateClass: function generateClass(prefix, targetId) { return " " + prefix + " " + (prefix + this.getTargetSelectorSuffix(targetId)); }, /** * Get class string * @param {string} type Shape type * @param {boolean} withShape Get with shape prefix * @returns {string} Class string * @private */ getClass: function getClass(type, withShape) { var _this = this, isPlural = /s$/.test(type), useIdKey = /^(area|arc|line)s?$/.test(type), key = isPlural ? "id" : "index"; return function (d) { var data = d.data || d, result = (withShape ? _this.generateClass(config_classes[isPlural ? "shapes" : "shape"], data[key]) : "") + _this.generateClass(config_classes[type], data[useIdKey ? "id" : key]); return result.trim(); }; }, /** * Get chart class string * @param {string} type Shape type * @returns {string} Class string * @private */ getChartClass: function getChartClass(type) { var _this2 = this; return function (d) { return config_classes["chart" + type] + _this2.classTarget((d.data ? d.data : d).id); }; }, generateExtraLineClass: function generateExtraLineClass() { var $$ = this, classes = $$.config.line_classes || [], ids = []; return function (d) { var id = d.id || d.data && d.data.id || d; return ids.indexOf(id) < 0 && ids.push(id), classes[ids.indexOf(id) % classes.length]; }; }, classRegion: function classRegion(d, i) { return this.generateClass(config_classes.region, i) + " " + ("class" in d ? d.class : ""); }, classTarget: function classTarget(id) { var additionalClassSuffix = this.config.data_classes[id], additionalClass = ""; return additionalClassSuffix && (additionalClass = " " + config_classes.target + "-" + additionalClassSuffix), this.generateClass(config_classes.target, id) + additionalClass; }, classFocus: function classFocus(d) { return this.classFocused(d) + this.classDefocused(d); }, classFocused: function classFocused(d) { return " " + (this.state.focusedTargetIds.indexOf(d.id) >= 0 ? config_classes.focused : ""); }, classDefocused: function classDefocused(d) { return " " + (this.state.defocusedTargetIds.indexOf(d.id) >= 0 ? config_classes.defocused : ""); }, getTargetSelectorSuffix: function getTargetSelectorSuffix(targetId) { return targetId || targetId === 0 ? ("-" + targetId).replace(/[\s?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\]/g, "-") : ""; }, selectorTarget: function selectorTarget(id, prefix) { var pfx = prefix || "", target = this.getTargetSelectorSuffix(id); // select target & circle return pfx + "." + (config_classes.target + target) + ", " + pfx + "." + (config_classes.circles + target); }, selectorTargets: function selectorTargets(idsValue, prefix) { var _this3 = this, ids = idsValue || []; return ids.length ? ids.map(function (id) { return _this3.selectorTarget(id, prefix); }) : null; }, selectorLegend: function selectorLegend(id) { return "." + (config_classes.legendItem + this.getTargetSelectorSuffix(id)); }, selectorLegends: function selectorLegends(ids) { var _this4 = this; return ids && ids.length ? ids.map(function (id) { return _this4.selectorLegend(id); }) : null; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/category.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var category = ({ /** * Category Name * @param {number} i Index number * @returns {string} category Name * @private */ categoryName: function categoryName(i) { var categories = this.config.axis_x_categories; return categories && i < categories.length ? categories[i] : i; } }); // EXTERNAL MODULE: external {"commonjs":"d3-scale","commonjs2":"d3-scale","amd":"d3-scale","root":"d3"} var external_commonjs_d3_scale_commonjs2_d3_scale_amd_d3_scale_root_d3_ = __webpack_require__(6); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/color.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Set pattern's background color * (it adds a <rect> element to simulate bg-color) * @param {SVGPatternElement} pattern SVG pattern element * @param {string} color Color string * @param {string} id ID to be set * @returns {{id: string, node: SVGPatternElement}} * @private */ var colorizePattern = function (pattern, color, id) { var node = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(pattern.cloneNode(!0)); return node.attr("id", id).insert("rect", ":first-child").attr("width", node.attr("width")).attr("height", node.attr("height")).style("fill", color), { id: id, node: node.node() }; }, schemeCategory10 = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]; // Replacement of d3.schemeCategory10. // Contained differently depend on d3 version: v4(d3-scale), v5(d3-scale-chromatic) /* harmony default export */ var internals_color = ({ /** * Get color pattern from CSS file * CSS should be defined as: background-image: url("#00c73c;#fa7171; ..."); * @returns {Array} * @private */ getColorFromCss: function getColorFromCss() { var cacheKey = KEY.colorPattern, body = browser_doc.body, pattern = body[cacheKey]; if (!pattern) { var span = browser_doc.createElement("span"); span.className = config_classes.colorPattern, span.style.display = "none", body.appendChild(span); var content = win.getComputedStyle(span).backgroundImage; span.parentNode.removeChild(span), content.indexOf(";") > -1 && (pattern = content.replace(/url[^#]*|["'()]|(\s|%20)/g, "").split(";").map(function (v) { return v.trim().replace(/[\"'\s]/g, ""); }).filter(Boolean), body[cacheKey] = pattern); } return pattern; }, generateColor: function generateColor() { var $$ = this, config = $$.config, colors = config.data_colors, callback = config.data_color, ids = [], pattern = notEmpty(config.color_pattern) ? config.color_pattern : (0,external_commonjs_d3_scale_commonjs2_d3_scale_amd_d3_scale_root_d3_.scaleOrdinal)($$.getColorFromCss() || schemeCategory10).range(), originalColorPattern = pattern; if (isFunction(config.color_tiles)) { var tiles = config.color_tiles.bind($$.api)(), colorizedPatterns = pattern.map(function (p, index) { var color = p.replace(/[#\(\)\s,]/g, ""), id = $$.state.datetimeId + "-pattern-" + color + "-" + index; return colorizePattern(tiles[index % tiles.length], p, id); }); // Add background color to patterns pattern = colorizedPatterns.map(function (p) { return "url(#" + p.id + ")"; }), $$.patterns = colorizedPatterns; } return function (d) { var color, id = d.id || d.data && d.data.id || d, isLine = $$.isTypeOf(id, ["line", "spline", "step"]) || !config.data_types[id]; return isFunction(colors[id]) ? color = colors[id].bind($$.api)(d) : colors[id] ? color = colors[id] : (ids.indexOf(id) < 0 && ids.push(id), color = isLine ? originalColorPattern[ids.indexOf(id) % originalColorPattern.length] : pattern[ids.indexOf(id) % pattern.length], colors[id] = color), isFunction(callback) ? callback.bind($$.api)(color, d) : color; }; }, generateLevelColor: function generateLevelColor() { var $$ = this, config = $$.config, colors = config.color_pattern, threshold = config.color_threshold, asValue = threshold.unit === "value", max = threshold.max || 100, values = threshold.values && threshold.values.length ? threshold.values : []; return notEmpty(threshold) ? function (value) { var v = asValue ? value : value * 100 / max, color = colors[colors.length - 1]; for (var i = 0, l = values.length; i < l; i++) if (v <= values[i]) { color = colors[i]; break; } return color; } : null; }, /** * Set the data over color. * When is out, will restate in its previous color value * @param {boolean} isOver true: set overed color, false: restore * @param {number|object} d target index or data object for Arc type * @private */ setOverColor: function setOverColor(isOver, d) { var $$ = this, config = $$.config, main = $$.$el.main, onover = config.color_onover, color = isOver ? onover : $$.color; isObject(color) ? color = function (_ref) { var id = _ref.id; return id in onover ? onover[id] : $$.color(id); } : isString(color) ? color = function () { return onover; } : isFunction(onover) && (color = color.bind($$.api)), main.selectAll(isObject(d) ? // when is Arc type "." + config_classes.arc + $$.getTargetSelectorSuffix(d.id) : "." + config_classes.shape + "-" + d).style("fill", color); } }); ;// CONCATENATED MODULE: ./src/config/const.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Chart type constant * @private */ var TYPE = { AREA: "area", AREA_LINE_RANGE: "area-line-range", AREA_SPLINE: "area-spline", AREA_SPLINE_RANGE: "area-spline-range", AREA_STEP: "area-step", BAR: "bar", BUBBLE: "bubble", CANDLESTICK: "candlestick", DONUT: "donut", GAUGE: "gauge", LINE: "line", PIE: "pie", RADAR: "radar", SCATTER: "scatter", SPLINE: "spline", STEP: "step" }; /** * chart types by category * @private */ var TYPE_BY_CATEGORY = { Area: [TYPE.AREA, TYPE.AREA_SPLINE, TYPE.AREA_SPLINE_RANGE, TYPE.AREA_LINE_RANGE, TYPE.AREA_STEP], AreaRange: [TYPE.AREA_SPLINE_RANGE, TYPE.AREA_LINE_RANGE], Arc: [TYPE.PIE, TYPE.DONUT, TYPE.GAUGE, TYPE.RADAR], Line: [TYPE.LINE, TYPE.SPLINE, TYPE.AREA, TYPE.AREA_SPLINE, TYPE.AREA_SPLINE_RANGE, TYPE.AREA_LINE_RANGE, TYPE.STEP, TYPE.AREA_STEP], Step: [TYPE.STEP, TYPE.AREA_STEP], Spline: [TYPE.SPLINE, TYPE.AREA_SPLINE, TYPE.AREA_SPLINE_RANGE] }; ;// CONCATENATED MODULE: ./src/ChartInternal/internals/domain.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var domain = ({ getYDomainMinMax: function getYDomainMinMax(targets, type) { var $$ = this, axis = $$.axis, config = $$.config, isMin = type === "min", dataGroups = config.data_groups, ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets); return dataGroups.length > 0 && function () { for (var idsInGroup, _ret, hasValue = $$["has" + (isMin ? "Negative" : "Positive") + "ValueInTargets"](targets), _loop = function (j, _idsInGroup) { if (_idsInGroup = _idsInGroup.filter(function (v) { return ids.indexOf(v) >= 0; }), _idsInGroup.length === 0) return idsInGroup = _idsInGroup, "continue"; var baseId = _idsInGroup[0], baseAxisId = axis.getId(baseId); hasValue && ys[baseId] && (ys[baseId] = ys[baseId].map(function (v) { return (isMin ? v < 0 : v > 0) ? v : 0; })); for (var id, _ret2, _loop2 = function (k, id) { if (!ys[id]) return "continue"; var axisId = axis.getId(id); ys[id].forEach(function (v, i) { var val = +v, meetCondition = isMin ? val > 0 : val < 0; axisId !== baseAxisId || hasValue && meetCondition || (ys[baseId][i] += val); }); }, k = 1; id = _idsInGroup[k]; k++) _ret2 = _loop2(k, id), _ret2 === "continue"; idsInGroup = _idsInGroup; }, j = 0; idsInGroup = dataGroups[j]; j++) _ret = _loop(j, idsInGroup), _ret === "continue"; }(), getMinMax(type, Object.keys(ys).map(function (key) { return getMinMax(type, ys[key]); })); }, getYDomainMin: function getYDomainMin(targets) { return this.getYDomainMinMax(targets, "min"); }, getYDomainMax: function getYDomainMax(targets) { return this.getYDomainMinMax(targets, "max"); }, /** * Check if hidden targets bound to the given axis id * @param {string} id ID to be checked * @returns {boolean} * @private */ isHiddenTargetWithYDomain: function isHiddenTargetWithYDomain(id) { var $$ = this; return $$.state.hiddenTargetIds.some(function (v) { return $$.axis.getId(v) === id; }); }, getYDomain: function getYDomain(targets, axisId, xDomain) { var $$ = this, axis = $$.axis, config = $$.config, scale = $$.scale, pfx = "axis_" + axisId; if ($$.isStackNormalized()) return [0, 100]; var isLog = scale && scale[axisId] && scale[axisId].type === "log", targetsByAxisId = targets.filter(function (t) { return axis.getId(t.id) === axisId; }), yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId; if (yTargets.length === 0) // use domain of the other axis if target of axisId is none return $$.isHiddenTargetWithYDomain(axisId) ? scale[axisId].domain() : axisId === "y2" ? scale.y.domain() : // When all data bounds to y2, y Axis domain is called prior y2. // So, it needs to call to get y2 domain here $$.getYDomain(targets, "y2", xDomain); var yMin = config[pfx + "_min"], yMax = config[pfx + "_max"], yDomainMin = $$.getYDomainMin(yTargets), yDomainMax = $$.getYDomainMax(yTargets), center = config[pfx + "_center"], isZeroBased = [TYPE.BAR, TYPE.BUBBLE, TYPE.SCATTER].concat(TYPE_BY_CATEGORY.Line).some(function (v) { var type = v.indexOf("area") > -1 ? "area" : v; return $$.hasType(v, yTargets) && config[type + "_zerobased"]; }), isInverted = config[pfx + "_inverted"], showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated, showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated; yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? yDomainMin < yMax ? yDomainMin : yMax - 10 : yDomainMin, yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? yMin < yDomainMax ? yDomainMax : yMin + 10 : yDomainMax, isNaN(yDomainMin) && (yDomainMin = 0), isNaN(yDomainMax) && (yDomainMax = yDomainMin), yDomainMin === yDomainMax && (yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0); var isAllPositive = yDomainMin >= 0 && yDomainMax >= 0, isAllNegative = yDomainMin <= 0 && yDomainMax <= 0; (isValue(yMin) && isAllPositive || isValue(yMax) && isAllNegative) && (isZeroBased = !1), isZeroBased && (isAllPositive && (yDomainMin = 0), isAllNegative && (yDomainMax = 0)); var domainLength = Math.abs(yDomainMax - yDomainMin), padding = { top: domainLength * .1, bottom: domainLength * .1 }; if (isDefined(center)) { var yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax)); yDomainMax = center + yDomainAbs, yDomainMin = center - yDomainAbs; } // add padding for data label if (showHorizontalDataLabel) { var diff = diffDomain(scale.y.range()), ratio = $$.getDataLabelLength(yDomainMin, yDomainMax, "width").map(function (v) { return v / diff; }); ["bottom", "top"].forEach(function (v, i) { padding[v] += domainLength * (ratio[i] / (1 - ratio[0] - ratio[1])); }); } else if (showVerticalDataLabel) { var lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, "height"); ["bottom", "top"].forEach(function (v, i) { padding[v] += axis.convertPixelsToAxisPadding(lengths[i], domainLength); }); } // if padding is set, the domain will be updated relative the current domain value // ex) $$.height=300, padding.top=150, domainLength=4 --> domain=6 var p = config[pfx + "_padding"]; notEmpty(p) && ["bottom", "top"].forEach(function (v) { padding[v] = axis.getPadding(p, v, padding[v], domainLength); }), isZeroBased && (isAllPositive && (padding.bottom = yDomainMin), isAllNegative && (padding.top = -yDomainMax)); var domain = isLog ? [yDomainMin, yDomainMax].map(function (v) { return v < 0 ? 0 : v; }) : [yDomainMin - padding.bottom, yDomainMax + padding.top]; return isInverted ? domain.reverse() : domain; }, getXDomainMinMax: function getXDomainMinMax(targets, type) { var $$ = this, configValue = $$.config["axis_x_" + type], dataValue = getMinMax(type, targets.map(function (t) { return getMinMax(type, t.values.map(function (v) { return v.x; })); })), value = isObject(configValue) ? configValue.value : configValue; return value = isDefined(value) && $$.axis.isTimeSeries() ? parseDate.bind(this)(value) : value, isObject(configValue) && configValue.fit && (type === "min" && value < dataValue || type === "max" && value > dataValue) && (value = undefined), isDefined(value) ? value : dataValue; }, getXDomainMin: function getXDomainMin(targets) { return this.getXDomainMinMax(targets, "min"); }, getXDomainMax: function getXDomainMax(targets) { return this.getXDomainMinMax(targets, "max"); }, getXDomainPadding: function getXDomainPadding(domain) { var maxDataCount, padding, $$ = this, axis = $$.axis, config = $$.config, diff = domain[1] - domain[0], xPadding = config.axis_x_padding; axis.isCategorized() ? padding = 0 : $$.hasType("bar") ? (maxDataCount = $$.getMaxDataCount(), padding = maxDataCount > 1 ? diff / (maxDataCount - 1) / 2 : .5) : padding = diff * .01; var left = padding, right = padding; return isObject(xPadding) && notEmpty(xPadding) ? (left = isValue(xPadding.left) ? xPadding.left : padding, right = isValue(xPadding.right) ? xPadding.right : padding) : isNumber(config.axis_x_padding) && (left = xPadding, right = xPadding), { left: left, right: right }; }, getXDomain: function getXDomain(targets) { var $$ = this, isLog = $$.scale.x.type === "log", xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)], min = 0, max = 0; if (isLog) min = xDomain[0], max = xDomain[1];else { var isCategorized = $$.axis.isCategorized(), isTimeSeries = $$.axis.isTimeSeries(), padding = $$.getXDomainPadding(xDomain), _xDomain = xDomain, firstX = _xDomain[0], lastX = _xDomain[1]; firstX - lastX !== 0 || isCategorized || (isTimeSeries ? (firstX = new Date(firstX.getTime() * .5), lastX = new Date(lastX.getTime() * 1.5)) : (firstX = firstX === 0 ? 1 : firstX * .5, lastX = lastX === 0 ? -1 : lastX * 1.5)), (firstX || firstX === 0) && (min = isTimeSeries ? new Date(firstX.getTime() - padding.left) : firstX - padding.left), (lastX || lastX === 0) && (max = isTimeSeries ? new Date(lastX.getTime() + padding.right) : lastX + padding.right); } return [min, max]; }, updateXDomain: function updateXDomain(targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) { var $$ = this, config = $$.config, org = $$.org, _$$$scale = $$.scale, x = _$$$scale.x, subX = _$$$scale.subX, zoomEnabled = config.zoom_enabled; if (withUpdateOrgXDomain && (x.domain(domain || sortValue($$.getXDomain(targets))), org.xDomain = x.domain(), zoomEnabled && $$.zoom.updateScaleExtent(), subX.domain(x.domain()), $$.brush && $$.brush.scale(subX)), withUpdateXDomain) { var domainValue = domain || !$$.brush || brushEmpty($$) ? org.xDomain : getBrushSelection($$).map(subX.invert); x.domain(domainValue), zoomEnabled && $$.zoom.updateScaleExtent(); } // Trim domain when too big by zoom mousemove event return withTrim && x.domain($$.trimXDomain(x.orgDomain())), x.domain(); }, trimXDomain: function trimXDomain(domain) { var zoomDomain = this.getZoomDomain(), min = zoomDomain[0], max = zoomDomain[1]; return domain[0] <= min && (domain[1] = +domain[1] + (min - domain[0]), domain[0] = min), max <= domain[1] && (domain[0] = +domain[0] - (domain[1] - max), domain[1] = max), domain; }, /** * Get zoom domain * @returns {Array} zoom domain * @private */ getZoomDomain: function getZoomDomain() { var $$ = this, config = $$.config, org = $$.org, _org$xDomain = org.xDomain, min = _org$xDomain[0], max = _org$xDomain[1]; return isDefined(config.zoom_x_min) && (min = getMinMax("min", [min, config.zoom_x_min])), isDefined(config.zoom_x_max) && (max = getMinMax("max", [max, config.zoom_x_max])), [min, max]; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/format.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Get formatted * @param {object} $$ Context * @param {string} typeValue Axis type * @param {number} v Value to be formatted * @returns {number | string} * @private */ function getFormat($$, typeValue, v) { var config = $$.config, type = "axis_" + typeValue + "_tick_format", format = config[type] ? config[type] : $$.defaultValueFormat; return format(v); } /* harmony default export */ var format = ({ getYFormat: function getYFormat(forArc) { var $$ = this, yFormat = $$.yFormat, y2Format = $$.y2Format; return forArc && !$$.hasType("gauge") && (yFormat = $$.defaultArcValueFormat, y2Format = $$.defaultArcValueFormat), function (v, ratio, id) { var format = $$.axis && $$.axis.getId(id) === "y2" ? y2Format : yFormat; return format.call($$, v, ratio); }; }, yFormat: function yFormat(v) { return getFormat(this, "y", v); }, y2Format: function y2Format(v) { return getFormat(this, "y2", v); }, defaultValueFormat: function defaultValueFormat(v) { return isValue(v) ? +v : ""; }, defaultArcValueFormat: function defaultArcValueFormat(v, ratio) { return (ratio * 100).toFixed(1) + "%"; }, dataLabelFormat: function dataLabelFormat(targetId) { var $$ = this, dataLabels = $$.config.data_labels, defaultFormat = function (v) { return isValue(v) ? +v : ""; }, format = defaultFormat; return isFunction(dataLabels.format) ? format = dataLabels.format : isObjectType(dataLabels.format) && (dataLabels.format[targetId] ? format = dataLabels.format[targetId] === !0 ? defaultFormat : dataLabels.format[targetId] : format = function () { return ""; }), format.bind($$.api); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/legend.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var internals_legend = ({ /** * Initialize the legend. * @private */ initLegend: function initLegend() { var $$ = this, config = $$.config, $el = $$.$el; $$.legendItemTextBox = {}, $$.state.legendHasRendered = !1, config.legend_show ? (!config.legend_contents_bindto && ($el.legend = $$.$el.svg.append("g").classed(config_classes.legend, !0).attr("transform", $$.getTranslate("legend"))), $$.updateLegend()) : $$.state.hiddenLegendIds = $$.mapToIds($$.data.targets); }, /** * Update legend element * @param {Array} targetIds ID's of target * @param {object} options withTransform : Whether to use the transform property / withTransitionForTransform: Whether transition is used when using the transform property / withTransition : whether or not to transition. * @param {object} transitions Return value of the generateTransitions * @private */ updateLegend: function updateLegend(targetIds, options, transitions) { var $$ = this, config = $$.config, state = $$.state, scale = $$.scale, $el = $$.$el, optionz = options || { withTransform: !1, withTransitionForTransform: !1, withTransition: !1 }; // toggle legend state // Update size and scale // Update g positions optionz.withTransition = getOption(optionz, "withTransition", !0), optionz.withTransitionForTransform = getOption(optionz, "withTransitionForTransform", !0), config.legend_contents_bindto && config.legend_contents_template ? $$.updateLegendTemplate() : $$.updateLegendElement(targetIds || $$.mapToIds($$.data.targets), optionz, transitions), $el.legend.selectAll("." + config_classes.legendItem).classed(config_classes.legendItemHidden, function (id) { var hide = !$$.isTargetToShow(id); return hide && (this.style.opacity = null), hide; }), $$.updateScales(!1, !scale.zoom), $$.updateSvgSize(), $$.transformAll(optionz.withTransitionForTransform, transitions), state.legendHasRendered = !0; }, /** * Update legend using template option * @private */ updateLegendTemplate: function updateLegendTemplate() { var $$ = this, config = $$.config, $el = $$.$el, wrapper = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(config.legend_contents_bindto), template = config.legend_contents_template; if (!wrapper.empty()) { var targets = $$.mapToIds($$.data.targets), ids = [], html = ""; targets.forEach(function (v) { var content = isFunction(template) ? template.bind($$.api)(v, $$.color(v), $$.api.data(v)[0].values) : tplProcess(template, { COLOR: $$.color(v), TITLE: v }); content && (ids.push(v), html += content); }); var legendItem = wrapper.html(html).selectAll(function () { return this.childNodes; }).data(ids); $$.setLegendItem(legendItem), $el.legend = wrapper; } }, /** * Update the size of the legend. * @param {Obejct} size Size object * @private */ updateSizeForLegend: function updateSizeForLegend(size) { var $$ = this, config = $$.config, _$$$state = $$.state, isLegendTop = _$$$state.isLegendTop, isLegendLeft = _$$$state.isLegendLeft, isLegendRight = _$$$state.isLegendRight, isLegendInset = _$$$state.isLegendInset, current = _$$$state.current, width = size.width, height = size.height, insetLegendPosition = { top: isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : current.height - height - $$.getCurrentPaddingBottom() - config.legend_inset_y, left: isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + .5 : current.width - width - $$.getCurrentPaddingRight() - config.legend_inset_x + .5 }; $$.state.margin3 = { top: isLegendRight ? 0 : isLegendInset ? insetLegendPosition.top : current.height - height, right: NaN, bottom: 0, left: isLegendRight ? current.width - width : isLegendInset ? insetLegendPosition.left : 0 }; }, /** * Transform Legend * @param {boolean} withTransition whether or not to transition. * @private */ transformLegend: function transformLegend(withTransition) { var $$ = this, legend = $$.$el.legend; (withTransition ? legend.transition() : legend).attr("transform", $$.getTranslate("legend")); }, /** * Update the legend step * @param {number} step Step value * @private */ updateLegendStep: function updateLegendStep(step) { this.state.legendStep = step; }, /** * Update legend item width * @param {number} width Width value * @private */ updateLegendItemWidth: function updateLegendItemWidth(width) { this.state.legendItemWidth = width; }, /** * Update legend item height * @param {number} height Height value * @private */ updateLegendItemHeight: function updateLegendItemHeight(height) { this.state.legendItemHeight = height; }, /** * Update legend item color * @param {string} id Corresponding data ID value * @param {string} color Color value * @private */ updateLegendItemColor: function updateLegendItemColor(id, color) { var legend = this.$el.legend; legend && legend.select("." + config_classes.legendItem + "-" + id + " line").style("stroke", color); }, /** * Get the width of the legend * @returns {number} width * @private */ getLegendWidth: function getLegendWidth() { var $$ = this, _$$$state2 = $$.state, width = _$$$state2.current.width, isLegendRight = _$$$state2.isLegendRight, isLegendInset = _$$$state2.isLegendInset, legendItemWidth = _$$$state2.legendItemWidth, legendStep = _$$$state2.legendStep; return $$.config.legend_show ? isLegendRight || isLegendInset ? legendItemWidth * (legendStep + 1) : width : 0; }, /** * Get the height of the legend * @returns {number} height * @private */ getLegendHeight: function getLegendHeight() { var $$ = this, _$$$state3 = $$.state, current = _$$$state3.current, isLegendRight = _$$$state3.isLegendRight, legendItemHeight = _$$$state3.legendItemHeight, legendStep = _$$$state3.legendStep; return $$.config.legend_show ? isLegendRight ? current.height : Math.max(20, legendItemHeight) * (legendStep + 1) : 0; }, /** * Get the opacity of the legend * @param {d3.selection} legendItem Legend item node * @returns {string|null} opacity * @private */ opacityForLegend: function opacityForLegend(legendItem) { return legendItem.classed(config_classes.legendItemHidden) ? null : "1"; }, /** * Get the opacity of the legend that is unfocused * @param {d3.selection} legendItem Legend item node * @returns {string|null} opacity * @private */ opacityForUnfocusedLegend: function opacityForUnfocusedLegend(legendItem) { return legendItem.classed(config_classes.legendItemHidden) ? null : "0.3"; }, /** * Toggles the focus of the legend * @param {Array} targetIds ID's of target * @param {boolean} focus whether or not to focus. * @private */ toggleFocusLegend: function toggleFocusLegend(targetIds, focus) { var $$ = this, legend = $$.$el.legend, targetIdz = $$.mapToTargetIds(targetIds); legend && legend.selectAll("." + config_classes.legendItem).filter(function (id) { return targetIdz.indexOf(id) >= 0; }).classed(config_classes.legendItemFocused, focus).transition().duration(100).style("opacity", function () { return (focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend).call($$, (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this)); }); }, /** * Revert the legend to its default state * @private */ revertLegend: function revertLegend() { var $$ = this, legend = $$.$el.legend; legend && legend.selectAll("." + config_classes.legendItem).classed(config_classes.legendItemFocused, !1).transition().duration(100).style("opacity", function () { return $$.opacityForLegend((0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this)); }); }, /** * Shows the legend * @param {Array} targetIds ID's of target * @private */ showLegend: function showLegend(targetIds) { var $$ = this, config = $$.config, $el = $$.$el; config.legend_show || (config.legend_show = !0, $el.legend ? $el.legend.style("visibility", "visible") : $$.initLegend(), !$$.state.legendHasRendered && $$.updateLegend()), $$.removeHiddenLegendIds(targetIds), $el.legend.selectAll($$.selectorLegends(targetIds)).style("visibility", "visible").transition().style("opacity", function () { return $$.opacityForLegend((0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this)); }); }, /** * Hide the legend * @param {Array} targetIds ID's of target * @private */ hideLegend: function hideLegend(targetIds) { var $$ = this, config = $$.config, legend = $$.$el.legend; config.legend_show && isEmpty(targetIds) && (config.legend_show = !1, legend.style("visibility", "hidden")), $$.addHiddenLegendIds(targetIds), legend.selectAll($$.selectorLegends(targetIds)).style("opacity", "0").style("visibility", "hidden"); }, /** * Get legend item textbox dimension * @param {string} id Data ID * @param {HTMLElement|d3.selection} textElement Text node element * @returns {object} Bounding rect * @private */ getLegendItemTextBox: function getLegendItemTextBox(id, textElement) { var data, $$ = this, cache = $$.cache, state = $$.state, cacheKey = KEY.legendItemTextBox; return id && (data = !state.redrawing && cache.get(cacheKey) || {}, !data[id] && (data[id] = $$.getTextRect(textElement, config_classes.legendItem), cache.add(cacheKey, data)), data = data[id]), data; }, /** * Set legend item style & bind events * @param {d3.selection} item Item node * @private */ setLegendItem: function setLegendItem(item) { var $$ = this, api = $$.api, config = $$.config, state = $$.state, isTouch = state.inputType === "touch", hasGauge = $$.hasType("gauge"); item.attr("class", function (id) { var node = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), itemClass = !node.empty() && node.attr("class") || ""; return itemClass + $$.generateClass(config_classes.legendItem, id); }).style("visibility", function (id) { return $$.isLegendToShow(id) ? "visible" : "hidden"; }), config.interaction_enabled && (item.style("cursor", "pointer").on("click", function (event, id) { callFn(config.legend_item_onclick, api, id) || (event.altKey ? (api.hide(), api.show(id)) : (api.toggle(id), (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).classed(config_classes.legendItemFocused, !1).style("opacity", null))), isTouch && $$.hideTooltip(); }), !isTouch && item.on("mouseout", function (event, id) { callFn(config.legend_item_onout, api, id) || ((0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).classed(config_classes.legendItemFocused, !1), hasGauge && $$.undoMarkOverlapped($$, "." + config_classes.gaugeValue), $$.api.revert()); }).on("mouseover", function (event, id) { callFn(config.legend_item_onover, api, id) || ((0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).classed(config_classes.legendItemFocused, !0), hasGauge && $$.markOverlapped(id, $$, "." + config_classes.gaugeValue), !state.transiting && $$.isTargetToShow(id) && api.focus(id)); })); }, /** * Update the legend * @param {Array} targetIds ID's of target * @param {object} options withTransform : Whether to use the transform property / withTransitionForTransform: Whether transition is used when using the transform property / withTransition : whether or not to transition. * @private */ updateLegendElement: function updateLegendElement(targetIds, options) { var xForLegend, yForLegend, background, $$ = this, config = $$.config, state = $$.state, legend = $$.$el.legend, posMin = 10, tileWidth = config.legend_item_tile_width + 5, maxWidth = 0, maxHeight = 0, totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = [0], steps = {}, step = 0, isLegendRightOrInset = state.isLegendRight || state.isLegendInset, targetIdz = targetIds.filter(function (id) { return !isDefined(config.data_names[id]) || config.data_names[id] !== null; }), withTransition = options.withTransition, updatePositions = function (textElement, id, index) { var margin, isLast = index === targetIdz.length - 1, box = $$.getLegendItemTextBox(id, textElement), itemWidth = box.width + tileWidth + (isLast && !isLegendRightOrInset ? 0 : 10) + config.legend_padding, itemHeight = box.height + 4, itemLength = isLegendRightOrInset ? itemHeight : itemWidth, areaLength = isLegendRightOrInset ? $$.getLegendHeight() : $$.getLegendWidth(), updateValues = function (id2, withoutStep) { withoutStep || (margin = (areaLength - totalLength - itemLength) / 2, margin < posMin && (margin = (areaLength - itemLength) / 2, totalLength = 0, step++)), steps[id2] = step, margins[step] = state.isLegendInset ? 10 : margin, offsets[id2] = totalLength, totalLength += itemLength; }; if (index === 0 && (totalLength = 0, step = 0, maxWidth = 0, maxHeight = 0), config.legend_show && !$$.isLegendToShow(id)) return widths[id] = 0, heights[id] = 0, steps[id] = 0, void (offsets[id] = 0); widths[id] = itemWidth, heights[id] = itemHeight, (!maxWidth || itemWidth >= maxWidth) && (maxWidth = itemWidth), (!maxHeight || itemHeight >= maxHeight) && (maxHeight = itemHeight); var maxLength = isLegendRightOrInset ? maxHeight : maxWidth; config.legend_equally ? (Object.keys(widths).forEach(function (id2) { return widths[id2] = maxWidth; }), Object.keys(heights).forEach(function (id2) { return heights[id2] = maxHeight; }), margin = (areaLength - maxLength * targetIdz.length) / 2, margin < posMin ? (totalLength = 0, step = 0, targetIdz.forEach(function (id2) { return updateValues(id2); })) : updateValues(id, !0)) : updateValues(id); }; state.isLegendInset && (step = config.legend_inset_step ? config.legend_inset_step : targetIdz.length, $$.updateLegendStep(step)), state.isLegendRight ? (xForLegend = function (id) { return maxWidth * steps[id]; }, yForLegend = function (id) { return margins[steps[id]] + offsets[id]; }) : state.isLegendInset ? (xForLegend = function (id) { return maxWidth * steps[id] + 10; }, yForLegend = function (id) { return margins[steps[id]] + offsets[id]; }) : (xForLegend = function (id) { return margins[steps[id]] + offsets[id]; }, yForLegend = function (id) { return maxHeight * steps[id]; }); var xForLegendText = function (id, i) { return xForLegend(id, i) + 4 + config.legend_item_tile_width; }, xForLegendRect = function (id, i) { return xForLegend(id, i); }, x1ForLegendTile = function (id, i) { return xForLegend(id, i) - 2; }, x2ForLegendTile = function (id, i) { return xForLegend(id, i) - 2 + config.legend_item_tile_width; }, yForLegendText = function (id, i) { return yForLegend(id, i) + 9; }, yForLegendRect = function (id, i) { return yForLegend(id, i) - 5; }, yForLegendTile = function (id, i) { return yForLegend(id, i) + 4; }, pos = -200, l = legend.selectAll("." + config_classes.legendItem).data(targetIdz).enter().append("g"); $$.setLegendItem(l), l.append("text").text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }).each(function (id, i) { updatePositions(this, id, i); }).style("pointer-events", "none").attr("x", isLegendRightOrInset ? xForLegendText : pos).attr("y", isLegendRightOrInset ? pos : yForLegendText), l.append("rect").attr("class", config_classes.legendItemEvent).style("fill-opacity", "0").attr("x", isLegendRightOrInset ? xForLegendRect : pos).attr("y", isLegendRightOrInset ? pos : yForLegendRect); var getColor = function (id) { var data = $$.getDataById(id); return $$.levelColor ? $$.levelColor(data.values[0].value) : $$.color(data); }, usePoint = config.legend_usePoint; if (usePoint) { var ids = []; l.append(function (d) { var pattern = notEmpty(config.point_pattern) ? config.point_pattern : [config.point_type]; ids.indexOf(d) === -1 && ids.push(d); var point = pattern[ids.indexOf(d) % pattern.length]; return point === "rectangle" && (point = "rect"), browser_doc.createElementNS(external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.namespaces.svg, "hasValidPointType" in $$ && $$.hasValidPointType(point) ? point : "use"); }).attr("class", config_classes.legendItemPoint).style("fill", getColor).style("pointer-events", "none").attr("href", function (data, idx, selection) { var node = selection[idx], nodeName = node.nodeName.toLowerCase(); return nodeName === "use" ? "#" + state.datetimeId + "-point-" + data : undefined; }); } else l.append("line").attr("class", config_classes.legendItemTile).style("stroke", getColor).style("pointer-events", "none").attr("x1", isLegendRightOrInset ? x1ForLegendTile : pos).attr("y1", isLegendRightOrInset ? pos : yForLegendTile).attr("x2", isLegendRightOrInset ? x2ForLegendTile : pos).attr("y2", isLegendRightOrInset ? pos : yForLegendTile).attr("stroke-width", config.legend_item_tile_height); // Set background for inset legend background = legend.select("." + config_classes.legendBackground + " rect"), state.isLegendInset && maxWidth > 0 && background.size() === 0 && (background = legend.insert("g", "." + config_classes.legendItem).attr("class", config_classes.legendBackground).append("rect")); var texts = legend.selectAll("text").data(targetIdz).text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }) // MEMO: needed for update .each(function (id, i) { updatePositions(this, id, i); }); (withTransition ? texts.transition() : texts).attr("x", xForLegendText).attr("y", yForLegendText); var rects = legend.selectAll("rect." + config_classes.legendItemEvent).data(targetIdz); if ((withTransition ? rects.transition() : rects).attr("width", function (id) { return widths[id]; }).attr("height", function (id) { return heights[id]; }).attr("x", xForLegendRect).attr("y", yForLegendRect), usePoint) { var tiles = legend.selectAll("." + config_classes.legendItemPoint).data(targetIdz); (withTransition ? tiles.transition() : tiles).each(function () { var radius, width, height, nodeName = this.nodeName.toLowerCase(), pointR = config.point_r, x = "x", y = "y", xOffset = 2, yOffset = 2.5; if (nodeName === "circle") { var size = pointR * .2; x = "cx", y = "cy", radius = pointR + size, xOffset = pointR * 2, yOffset = -size; } else if (nodeName === "rect") { var _size = pointR * 2.5; width = _size, height = _size, yOffset = 3; } (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).attr(x, function (d) { return x1ForLegendTile(d) + xOffset; }).attr(y, function (d) { return yForLegendTile(d) - yOffset; }).attr("r", radius).attr("width", width).attr("height", height); }); } else { var _tiles = legend.selectAll("line." + config_classes.legendItemTile).data(targetIdz); (withTransition ? _tiles.transition() : _tiles).style("stroke", getColor).attr("x1", x1ForLegendTile).attr("y1", yForLegendTile).attr("x2", x2ForLegendTile).attr("y2", yForLegendTile); } background && (withTransition ? background.transition() : background).attr("height", $$.getLegendHeight() - 12).attr("width", maxWidth * (step + 1) + 10), $$.updateLegendItemWidth(maxWidth), $$.updateLegendItemHeight(maxHeight), $$.updateLegendStep(step); } }); // EXTERNAL MODULE: external {"commonjs":"d3-transition","commonjs2":"d3-transition","amd":"d3-transition","root":"d3"} var external_commonjs_d3_transition_commonjs2_d3_transition_amd_d3_transition_root_d3_ = __webpack_require__(8); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/redraw.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var redraw = ({ redraw: function redraw(options) { options === void 0 && (options = {}); var $$ = this, config = $$.config, state = $$.state, $el = $$.$el, main = $el.main; state.redrawing = !0; var targetsToShow = $$.filterTargetsToShow($$.data.targets), initializing = options.initializing, flow = options.flow, wth = $$.getWithOption(options), duration = wth.Transition ? config.transition_duration : 0, durationForExit = wth.TransitionForExit ? duration : 0, durationForAxis = wth.TransitionForAxis ? duration : 0, transitions = $$.axis && $$.axis.generateTransitions(durationForAxis); // text // title $$.updateSizes(initializing), wth.Legend && config.legend_show ? (options.withTransition = !!duration, $$.updateLegend($$.mapToIds($$.data.targets), options, transitions)) : wth.Dimension && $$.updateDimension(!0), (!$$.hasArcType() || state.hasRadar) && $$.updateCircleY && ($$.circleY = $$.updateCircleY()), state.hasAxis ? ($$.axis.redrawAxis(targetsToShow, wth, transitions, flow, initializing), config.data_empty_label_text && main.select("text." + config_classes.text + "." + config_classes.empty).attr("x", state.width / 2).attr("y", state.height / 2).text(config.data_empty_label_text).style("display", targetsToShow.length ? "none" : null), $$.hasGrid() && $$.updateGrid(duration), config.regions.length && $$.updateRegion(duration), ["bar", "candlestick", "line", "area"].forEach(function (v) { var name = capitalize(v); (/^(line|area)$/.test(v) && $$.hasTypeOf(name) || $$.hasType(v)) && $$["update" + name](durationForExit); }), $el.text && main.selectAll("." + config_classes.selectedCircles).filter($$.isBarType.bind($$)).selectAll("circle").remove(), config.interaction_enabled && !flow && wth.EventRect && ($$.redrawEventRect(), $$.bindZoomEvent && $$.bindZoomEvent())) : ($el.arcs && $$.redrawArc(duration, durationForExit, wth.Transform), $el.radar && $$.redrawRadar(durationForExit)), !state.resizing && ($$.hasPointType() || state.hasRadar) && $$.updateCircle(), $$.hasDataLabel() && !$$.hasArcType(null, ["radar"]) && $$.updateText(durationForExit), $$.redrawTitle && $$.redrawTitle(), initializing && $$.updateTypesElements(), $$.generateRedrawList(targetsToShow, flow, duration, wth.Subchart), $$.callPluginHook("$redraw", options, duration); }, /** * Generate redraw list * @param {object} targets targets data to be shown * @param {object} flow flow object * @param {number} duration duration value * @param {boolean} withSubchart whether or not to show subchart * @private */ generateRedrawList: function generateRedrawList(targets, flow, duration, withSubchart) { var $$ = this, config = $$.config, state = $$.state, shape = $$.getDrawShape(); state.hasAxis && config.subchart_show && $$.redrawSubchart(withSubchart, duration, shape); // generate flow var flowFn = flow && $$.generateFlow({ targets: targets, flow: flow, duration: flow.duration, shape: shape, xv: $$.xv.bind($$) }), isTransition = (duration || flowFn) && isTabVisible(), redrawList = $$.getRedrawList(shape, flow, flowFn, isTransition), afterRedraw = flow || config.onrendered ? function () { flowFn && flowFn(), state.redrawing = !1, callFn(config.onrendered, $$.api); } : null; if (afterRedraw) // Only use transition when current tab is visible. if (isTransition && redrawList.length) { // Wait for end of transitions for callback var waitForDraw = generateWait(); // transition should be derived from one transition (0,external_commonjs_d3_transition_commonjs2_d3_transition_amd_d3_transition_root_d3_.transition)().duration(duration).each(function () { redrawList.reduce(function (acc, t1) { return acc.concat(t1); }, []).forEach(function (t) { return waitForDraw.add(t); }); }).call(waitForDraw, afterRedraw); } else state.transiting || afterRedraw(); // update fadein condition $$.mapToIds($$.data.targets).forEach(function (id) { state.withoutFadeIn[id] = !0; }); }, getRedrawList: function getRedrawList(shape, flow, flowFn, isTransition) { var $$ = this, config = $$.config, _$$$state = $$.state, hasAxis = _$$$state.hasAxis, hasRadar = _$$$state.hasRadar, grid = $$.$el.grid, _shape$pos = shape.pos, cx = _shape$pos.cx, cy = _shape$pos.cy, xForText = _shape$pos.xForText, yForText = _shape$pos.yForText, list = []; return hasAxis && ((config.grid_x_lines.length || config.grid_y_lines.length) && list.push($$.redrawGrid(isTransition)), config.regions.length && list.push($$.redrawRegion(isTransition)), Object.keys(shape.type).forEach(function (v) { var name = capitalize(v), drawFn = shape.type[v]; (/^(area|line)$/.test(v) && $$.hasTypeOf(name) || $$.hasType(v)) && list.push($$["redraw" + name](drawFn, isTransition)); }), !flow && grid.main && list.push($$.updateGridFocus())), (!$$.hasArcType() || hasRadar) && notEmpty(config.data_labels) && config.data_labels !== !1 && list.push($$.redrawText(xForText, yForText, flow, isTransition)), ($$.hasPointType() || hasRadar) && !config.point_focus_only && $$.redrawCircle && list.push($$.redrawCircle(cx, cy, isTransition, flowFn)), list; }, updateAndRedraw: function updateAndRedraw(options) { options === void 0 && (options = {}); var transitions, $$ = this, config = $$.config, state = $$.state; // same with redraw // NOT same with redraw // Draw with new sizes & scales options.withTransition = getOption(options, "withTransition", !0), options.withTransform = getOption(options, "withTransform", !1), options.withLegend = getOption(options, "withLegend", !1), options.withUpdateXDomain = !0, options.withUpdateOrgXDomain = !0, options.withTransitionForExit = !1, options.withTransitionForTransform = getOption(options, "withTransitionForTransform", options.withTransition), options.withLegend && config.legend_show || (state.hasAxis && (transitions = $$.axis.generateTransitions(options.withTransitionForAxis ? config.transition_duration : 0)), $$.updateScales(), $$.updateSvgSize(), $$.transformAll(options.withTransitionForTransform, transitions)), $$.redraw(options, transitions); }, redrawWithoutRescale: function redrawWithoutRescale() { this.redraw({ withY: !1, withSubchart: !1, withEventRect: !1, withTransitionForAxis: !1 }); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/scale.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Get scale * @param {string} [type='linear'] Scale type * @param {number} [min] Min range * @param {number} [max] Max range * @returns {d3.scaleLinear|d3.scaleTime} scale * @private */ function getScale(type, min, max) { type === void 0 && (type = "linear"), min === void 0 && (min = 0), max === void 0 && (max = 1); var scale = { linear: external_commonjs_d3_scale_commonjs2_d3_scale_amd_d3_scale_root_d3_.scaleLinear, log: external_commonjs_d3_scale_commonjs2_d3_scale_amd_d3_scale_root_d3_.scaleSymlog, _log: external_commonjs_d3_scale_commonjs2_d3_scale_amd_d3_scale_root_d3_.scaleLog, time: external_commonjs_d3_scale_commonjs2_d3_scale_amd_d3_scale_root_d3_.scaleTime }[type](); return scale.type = type, /_?log/.test(type) && scale.clamp(!0), scale.range([min, max]); } /* harmony default export */ var scale = ({ /** * Get x Axis scale function * @param {number} min Min value * @param {number} max Max value * @param {Array} domain Domain value * @param {Function} offset The offset getter to be sum * @returns {Function} scale * @private */ getXScale: function getXScale(min, max, domain, offset) { var $$ = this, scale = $$.scale.zoom || getScale($$.axis.getAxisType("x"), min, max); return $$.getCustomizedScale(domain ? scale.domain(domain) : scale, offset); }, /** * Get y Axis scale function * @param {string} id Axis id: 'y' or 'y2' * @param {number} min Min value * @param {number} max Max value * @param {Array} domain Domain value * @returns {Function} Scale function * @private */ getYScale: function getYScale(id, min, max, domain) { var $$ = this, scale = getScale($$.axis.getAxisType(id), min, max); return domain && scale.domain(domain), scale; }, /** * Get y Axis scale * @param {string} id Axis id * @param {boolean} isSub Weather is sub Axis * @returns {Function} Scale function * @private */ getYScaleById: function getYScaleById(id, isSub) { isSub === void 0 && (isSub = !1); var isY2 = this.axis.getId(id) === "y2", key = isSub ? isY2 ? "subY2" : "subY" : isY2 ? "y2" : "y"; return this.scale[key]; }, /** * Get customized scale * @param {d3.scaleLinear|d3.scaleTime} scaleValue Scale function * @param {Function} offsetValue Offset getter to be sum * @returns {Function} Scale function * @private */ getCustomizedScale: function getCustomizedScale(scaleValue, offsetValue) { var $$ = this, offset = offsetValue || function () { return $$.axis.x.tickOffset(); }, scale = function (d, raw) { var v = scaleValue(d) + offset(); return raw ? v : Math.ceil(v); }; // copy original scale methods for (var key in scaleValue) scale[key] = scaleValue[key]; return scale.orgDomain = function () { return scaleValue.domain(); }, scale.orgScale = function () { return scaleValue; }, $$.axis.isCategorized() && (scale.domain = function (domainValue) { var domain = domainValue; return arguments.length ? (scaleValue.domain(domain), scale) : (domain = this.orgDomain(), [domain[0], domain[1] + 1]); }), scale; }, /** * Update scale * @param {boolean} isInit Param is given at the init rendering * @param {boolean} updateXDomain If update x domain * @private */ updateScales: function updateScales(isInit, updateXDomain) { updateXDomain === void 0 && (updateXDomain = !0); var $$ = this, axis = $$.axis, config = $$.config, format = $$.format, org = $$.org, scale = $$.scale, _$$$state = $$.state, width = _$$$state.width, height = _$$$state.height, width2 = _$$$state.width2, height2 = _$$$state.height2, hasAxis = _$$$state.hasAxis; if (hasAxis) { var isRotated = config.axis_rotated, min = { x: isRotated ? 1 : 0, y: isRotated ? 0 : height, subX: isRotated ? 1 : 0, subY: isRotated ? 0 : height2 }, max = { x: isRotated ? height : width, y: isRotated ? width : 1, subX: isRotated ? height : width, subY: isRotated ? width2 : 1 }, xDomain = updateXDomain && scale.x && scale.x.orgDomain(), xSubDomain = updateXDomain && org.xDomain; // update edges // y Axis scale.x = $$.getXScale(min.x, max.x, xDomain, function () { return axis.x.tickOffset(); }), scale.subX = $$.getXScale(min.x, max.x, xSubDomain, function (d) { return d % 1 ? 0 : axis.subX.tickOffset(); }), format.xAxisTick = axis.getXAxisTickFormat(), axis.setAxis("x", scale.x, config.axis_x_tick_outer, isInit), config.subchart_show && axis.setAxis("subX", scale.subX, config.axis_x_tick_outer, isInit), scale.y = $$.getYScale("y", min.y, max.y, scale.y ? scale.y.domain() : config.axis_y_default), scale.subY = $$.getYScale("y", min.subY, max.subY, scale.subY ? scale.subY.domain() : config.axis_y_default), axis.setAxis("y", scale.y, config.axis_y_tick_outer, isInit), config.axis_y2_show && (scale.y2 = $$.getYScale("y2", min.y, max.y, scale.y2 ? scale.y2.domain() : config.axis_y2_default), scale.subY2 = $$.getYScale("y2", min.subY, max.subY, scale.subY2 ? scale.subY2.domain() : config.axis_y2_default), axis.setAxis("y2", scale.y2, config.axis_y2_tick_outer, isInit)); } else // update for arc $$.updateArc && $$.updateArc(); }, /** * Get the zoom or unzoomed scaled value * @param {Date|number|object} d Data value * @returns {number|null} * @private */ xx: function xx(d) { var $$ = this, config = $$.config, _$$$scale = $$.scale, x = _$$$scale.x, zoom = _$$$scale.zoom, fn = config.zoom_enabled && zoom ? zoom : x; return d ? fn(isValue(d.x) ? d.x : d) : null; }, xv: function xv(d) { var $$ = this, axis = $$.axis, config = $$.config, x = $$.scale.x, value = $$.getBaseValue(d); return axis.isTimeSeries() ? value = parseDate.call($$, value) : axis.isCategorized() && isString(value) && (value = config.axis_x_categories.indexOf(value)), Math.ceil(x(value)); }, yv: function yv(d) { var $$ = this, _$$$scale2 = $$.scale, y = _$$$scale2.y, y2 = _$$$scale2.y2, yScale = d.axis && d.axis === "y2" ? y2 : y; return Math.ceil(yScale($$.getBaseValue(d))); }, subxx: function subxx(d) { return d ? this.scale.subX(d.x) : null; } }); // EXTERNAL MODULE: external {"commonjs":"d3-shape","commonjs2":"d3-shape","amd":"d3-shape","root":"d3"} var external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_ = __webpack_require__(9); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/shape.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var shape = ({ /** * Get the shape draw function * @returns {object} * @private */ getDrawShape: function getDrawShape() { var $$ = this, isRotated = $$.config.axis_rotated, hasRadar = $$.state.hasRadar, shape = { type: {}, indices: {}, pos: {} }; if (["bar", "candlestick", "line", "area"].forEach(function (v) { var name = capitalize(/^(bubble|scatter)$/.test(v) ? "line" : v); if ($$.hasType(v) || $$.hasTypeOf(name) || v === "line" && ($$.hasType("bubble") || $$.hasType("scatter"))) { var indices = $$.getShapeIndices($$["is" + name + "Type"]), drawFn = $$["generateDraw" + name]; shape.indices[v] = indices, shape.type[v] = drawFn ? drawFn.bind($$)(indices, !1) : undefined; } }), !$$.hasArcType() || hasRadar) { // generate circle x/y functions depending on updated params var cx = hasRadar ? $$.radarCircleX : isRotated ? $$.circleY : $$.circleX, cy = hasRadar ? $$.radarCircleY : isRotated ? $$.circleX : $$.circleY; shape.pos = { xForText: $$.generateXYForText(shape.indices, !0), yForText: $$.generateXYForText(shape.indices, !1), cx: (cx || function () {}).bind($$), cy: (cy || function () {}).bind($$) }; } return shape; }, getShapeIndices: function getShapeIndices(typeFilter) { var $$ = this, config = $$.config, xs = config.data_xs, hasXs = notEmpty(xs), indices = {}, i = hasXs ? {} : 0; return hasXs && getUnique(Object.keys(xs).map(function (v) { return xs[v]; })).forEach(function (v) { i[v] = 0, indices[v] = {}; }), $$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) { for (var groups, xKey = (d.id in xs) ? xs[d.id] : "", ind = xKey ? indices[xKey] : indices, j = 0; groups = config.data_groups[j]; j++) if (!(groups.indexOf(d.id) < 0)) for (var _row4, _k4 = 0; _row4 = groups[_k4]; _k4++) if (_row4 in ind) { ind[d.id] = ind[_row4]; break; } isUndefined(ind[d.id]) && (ind[d.id] = xKey ? i[xKey]++ : i++, ind.__max__ = (xKey ? i[xKey] : i) - 1); }), indices; }, /** * Get indices value based on data ID value * @param {object} indices Indices object * @param {string} id Data id value * @returns {object} Indices object * @private */ getIndices: function getIndices(indices, id) { var xs = this.config.data_xs; return notEmpty(xs) ? indices[xs[id]] : indices; }, /** * Get indices max number * @param {object} indices Indices object * @returns {number} Max number * @private */ getIndicesMax: function getIndicesMax(indices) { return notEmpty(this.config.data_xs) ? // if is multiple xs, return total sum of xs' __max__ value Object.keys(indices).map(function (v) { return indices[v].__max__ || 0; }).reduce(function (acc, curr) { return acc + curr; }) : indices.__max__; }, getShapeX: function getShapeX(offset, indices, isSub) { var $$ = this, config = $$.config, scale = $$.scale, currScale = isSub ? scale.subX : scale.zoom || scale.x, barPadding = config.bar_padding, sum = function (p, c) { return p + c; }, halfWidth = isObjectType(offset) && (offset._$total.length ? offset._$total.reduce(sum) / 2 : 0); return function (d) { var ind = $$.getIndices(indices, d.id), index = d.id in ind ? ind[d.id] : 0, targetsNum = (ind.__max__ || 0) + 1, x = 0; if (notEmpty(d.x)) { var xPos = currScale(d.x, !0); x = halfWidth ? xPos - (offset[d.id] || offset._$width) + offset._$total.slice(0, index + 1).reduce(sum) - halfWidth : xPos - (isNumber(offset) ? offset : offset._$width) * (targetsNum / 2 - index); } // adjust x position for bar.padding optionq return offset && x && targetsNum > 1 && barPadding && (index && (x += barPadding * index), targetsNum > 2 ? x -= (targetsNum - 1) * barPadding / 2 : targetsNum === 2 && (x -= barPadding / 2)), x; }; }, getShapeY: function getShapeY(isSub) { var $$ = this, isStackNormalized = $$.isStackNormalized(); return function (d) { var value = d.value; return isNumber(d) ? value = d : isStackNormalized ? value = $$.getRatio("index", d, !0) : $$.isBubbleZType(d) && (value = $$.getBubbleZData(d.value, "y")), $$.getYScaleById(d.id, isSub)(value); }; }, /** * Get shape based y Axis min value * @param {string} id Data id * @returns {number} * @private */ getShapeYMin: function getShapeYMin(id) { var $$ = this, scale = $$.scale[$$.axis.getId(id)], _scale$domain = scale.domain(), yMin = _scale$domain[0]; return !$$.isGrouped(id) && yMin > 0 ? yMin : 0; }, /** * Get Shape's offset data * @param {Function} typeFilter Type filter function * @returns {object} * @private */ getShapeOffsetData: function getShapeOffsetData(typeFilter) { var $$ = this, targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))), isStackNormalized = $$.isStackNormalized(), shapeOffsetTargets = targets.map(function (target) { var rowValues = target.values, values = {}; $$.isStepType(target) && (rowValues = $$.convertValuesToStep(rowValues)); var rowValueMapByXValue = rowValues.reduce(function (out, d) { var key = +d.x; return out[key] = d, values[key] = isStackNormalized ? $$.getRatio("index", d, !0) : d.value, out; }, {}); return { id: target.id, rowValues: rowValues, rowValueMapByXValue: rowValueMapByXValue, values: values }; }), indexMapByTargetId = targets.reduce(function (out, _ref, index) { var id = _ref.id; return out[id] = index, out; }, {}); return { indexMapByTargetId: indexMapByTargetId, shapeOffsetTargets: shapeOffsetTargets }; }, getShapeOffset: function getShapeOffset(typeFilter, indices, isSub) { var $$ = this, _$$$getShapeOffsetDat = $$.getShapeOffsetData(typeFilter), shapeOffsetTargets = _$$$getShapeOffsetDat.shapeOffsetTargets, indexMapByTargetId = _$$$getShapeOffsetDat.indexMapByTargetId; return function (d, idx) { var ind = $$.getIndices(indices, d.id), scale = $$.getYScaleById(d.id, isSub), y0 = scale($$.getShapeYMin(d.id)), dataXAsNumber = +d.x, offset = y0; return shapeOffsetTargets.filter(function (t) { return t.id !== d.id; }).forEach(function (t) { if (ind[t.id] === ind[d.id] && indexMapByTargetId[t.id] < indexMapByTargetId[d.id]) { var row = t.rowValues[idx]; // check if the x values line up row && +row.x === dataXAsNumber || (row = t.rowValueMapByXValue[dataXAsNumber]), row && row.value * d.value >= 0 && (offset += scale(t.values[dataXAsNumber]) - y0); } }), offset; }; }, getBarW: function getBarW(type, axis, targetsNum) { var $$ = this, config = $$.config, org = $$.org, scale = $$.scale, maxDataCount = $$.getMaxDataCount(), isGrouped = type === "bar" && config.data_groups.length, configName = type + "_width", tickInterval = scale.zoom && !$$.axis.isCategorized() ? org.xDomain.map(function (v) { return scale.zoom(v); }).reduce(function (a, c) { return Math.abs(a) + c; }) / maxDataCount : axis.tickInterval(maxDataCount), getWidth = function (id) { var width = id ? config[configName][id] : config[configName], ratio = id ? width.ratio : config[configName + "_ratio"], max = id ? width.max : config[configName + "_max"], w = isNumber(width) ? width : targetsNum ? tickInterval * ratio / targetsNum : 0; return max && w > max ? max : w; }, result = getWidth(); return !isGrouped && isObjectType(config[configName]) && (result = { _$width: result, _$total: [] }, $$.filterTargetsToShow($$.data.targets).forEach(function (v) { config[configName][v.id] && (result[v.id] = getWidth(v.id), result._$total.push(result[v.id] || result._$width)); })), result; }, /** * Get shape element * @param {string} shapeName Shape string * @param {number} i Index number * @param {string} id Data series id * @returns {d3Selection} * @private */ getShapeByIndex: function getShapeByIndex(shapeName, i, id) { var $$ = this, main = $$.$el.main, suffix = isValue(i) ? "-" + i : ""; return (id ? main.selectAll("." + config_classes[shapeName + "s"] + $$.getTargetSelectorSuffix(id)) : main).selectAll("." + config_classes[shapeName] + suffix); }, isWithinShape: function isWithinShape(that, d) { var isWithin, $$ = this, shape = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(that); return $$.isTargetToShow(d.id) ? "hasValidPointType" in $$ && $$.hasValidPointType(that.nodeName) ? isWithin = $$.isStepType(d) ? $$.isWithinStep(that, $$.getYScaleById(d.id)(d.value)) : $$.isWithinCircle(that, $$.isBubbleType(d) ? $$.pointSelectR(d) * 1.5 : 0) : that.nodeName === "path" && (isWithin = !shape.classed(config_classes.bar) || $$.isWithinBar(that)) : isWithin = !1, isWithin; }, getInterpolate: function getInterpolate(d) { var $$ = this, interpolation = $$.getInterpolateType(d); return { "basis": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveBasis, "basis-closed": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveBasisClosed, "basis-open": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveBasisOpen, "bundle": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveBundle, "cardinal": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveCardinal, "cardinal-closed": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveCardinalClosed, "cardinal-open": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveCardinalOpen, "catmull-rom": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveCatmullRom, "catmull-rom-closed": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveCatmullRomClosed, "catmull-rom-open": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveCatmullRomOpen, "monotone-x": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveMonotoneX, "monotone-y": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveMonotoneY, "natural": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveNatural, "linear-closed": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveLinearClosed, "linear": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveLinear, "step": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveStep, "step-after": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveStepAfter, "step-before": external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.curveStepBefore }[interpolation]; }, getInterpolateType: function getInterpolateType(d) { var $$ = this, config = $$.config, type = config.spline_interpolation_type, interpolation = $$.isInterpolationType(type) ? type : "cardinal"; return $$.isSplineType(d) ? interpolation : $$.isStepType(d) ? config.line_step_type : "linear"; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/size.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var size = ({ /** * Update container size * @private */ setContainerSize: function setContainerSize() { var $$ = this, state = $$.state; state.current.width = $$.getCurrentWidth(), state.current.height = $$.getCurrentHeight(); }, getCurrentWidth: function getCurrentWidth() { var $$ = this; return $$.config.size_width || $$.getParentWidth(); }, getCurrentHeight: function getCurrentHeight() { var $$ = this, config = $$.config, h = config.size_height || $$.getParentHeight(); return h > 0 ? h : 320 / ($$.hasType("gauge") && !config.gauge_fullCircle ? 2 : 1); }, getCurrentPaddingTop: function getCurrentPaddingTop() { var $$ = this, config = $$.config, hasAxis = $$.state.hasAxis, $el = $$.$el, axesLen = hasAxis ? config.axis_y2_axes.length : 0, padding = isValue(config.padding_top) ? config.padding_top : 0; return $el.title && $el.title.node() && (padding += $$.getTitlePadding()), axesLen && config.axis_rotated && (padding += $$.getHorizontalAxisHeight("y2") * axesLen), padding; }, getCurrentPaddingBottom: function getCurrentPaddingBottom() { var $$ = this, config = $$.config, hasAxis = $$.state.hasAxis, axisId = config.axis_rotated ? "y" : "x", axesLen = hasAxis ? config["axis_" + axisId + "_axes"].length : 0, padding = isValue(config.padding_bottom) ? config.padding_bottom : 0; return padding + (axesLen ? $$.getHorizontalAxisHeight(axisId) * axesLen : 0); }, getCurrentPaddingLeft: function getCurrentPaddingLeft(withoutRecompute) { var padding, $$ = this, config = $$.config, hasAxis = $$.state.hasAxis, isRotated = config.axis_rotated, axisId = isRotated ? "x" : "y", axesLen = hasAxis ? config["axis_" + axisId + "_axes"].length : 0, axisWidth = hasAxis ? $$.getAxisWidthByAxisId(axisId, withoutRecompute) : 0; return padding = isValue(config.padding_left) ? config.padding_left : hasAxis && isRotated ? config.axis_x_show ? Math.max(ceil10(axisWidth), 40) : 1 : hasAxis && (!config.axis_y_show || config.axis_y_inner) ? $$.axis.getAxisLabelPosition("y").isOuter ? 30 : 1 : ceil10(axisWidth), padding + axisWidth * axesLen; }, getCurrentPaddingRight: function getCurrentPaddingRight(withXAxisTickTextOverflow) { withXAxisTickTextOverflow === void 0 && (withXAxisTickTextOverflow = !1); var padding, $$ = this, config = $$.config, hasAxis = $$.state.hasAxis, defaultPadding = 10, legendWidthOnRight = $$.state.isLegendRight ? $$.getLegendWidth() + 20 : 0, axesLen = hasAxis ? config.axis_y2_axes.length : 0, axisWidth = hasAxis ? $$.getAxisWidthByAxisId("y2") : 0, xAxisTickTextOverflow = withXAxisTickTextOverflow ? $$.axis.getXAxisTickTextY2Overflow(defaultPadding) : 0; return padding = isValue(config.padding_right) ? config.padding_right + 1 : $$.axis && config.axis_rotated ? defaultPadding + legendWidthOnRight : $$.axis && (!config.axis_y2_show || config.axis_y2_inner) ? Math.max(2 + legendWidthOnRight + ($$.axis.getAxisLabelPosition("y2").isOuter ? 20 : 0), xAxisTickTextOverflow) : Math.max(ceil10(axisWidth) + legendWidthOnRight, xAxisTickTextOverflow), padding + axisWidth * axesLen; }, /** * Get the parent rect element's size * @param {string} key property/attribute name * @returns {number} * @private */ getParentRectValue: function getParentRectValue(key) { for (var v, offsetName = "offset" + capitalize(key), parent = this.$el.chart.node(); !v && parent && parent.tagName !== "BODY";) { try { v = parent.getBoundingClientRect()[key]; } catch (e) { offsetName in parent && (v = parent[offsetName]); } parent = parent.parentNode; } if (key === "width") { // Sometimes element's width value is incorrect(ex. flex container) // In this case, use body's offsetWidth instead. var bodyWidth = browser_doc.body.offsetWidth; v > bodyWidth && (v = bodyWidth); } return v; }, getParentWidth: function getParentWidth() { return this.getParentRectValue("width"); }, getParentHeight: function getParentHeight() { var h = this.$el.chart.style("height"); return h.indexOf("px") > 0 ? parseInt(h, 10) : 0; }, getSvgLeft: function getSvgLeft(withoutRecompute) { var $$ = this, config = $$.config, $el = $$.$el, hasLeftAxisRect = config.axis_rotated || !config.axis_rotated && !config.axis_y_inner, leftAxisClass = config.axis_rotated ? config_classes.axisX : config_classes.axisY, leftAxis = $el.main.select("." + leftAxisClass).node(), svgRect = leftAxis && hasLeftAxisRect ? leftAxis.getBoundingClientRect() : { right: 0 }, chartRect = $el.chart.node().getBoundingClientRect(), hasArc = $$.hasArcType(), svgLeft = svgRect.right - chartRect.left - (hasArc ? 0 : $$.getCurrentPaddingLeft(withoutRecompute)); return svgLeft > 0 ? svgLeft : 0; }, updateDimension: function updateDimension(withoutAxis) { var $$ = this, config = $$.config, hasAxis = $$.state.hasAxis, $el = $$.$el; // pass 'withoutAxis' param to not animate at the init rendering hasAxis && !withoutAxis && $$.axis.x && config.axis_rotated && $$.axis.subX && $$.axis.subX.create($el.axis.subX), $$.updateScales(withoutAxis), $$.updateSvgSize(), $$.transformAll(!1); }, updateSvgSize: function updateSvgSize() { var $$ = this, _$$$state = $$.state, clip = _$$$state.clip, current = _$$$state.current, hasAxis = _$$$state.hasAxis, width = _$$$state.width, height = _$$$state.height, svg = $$.$el.svg; if (svg.attr("width", current.width).attr("height", current.height), hasAxis) { var brush = svg.select("." + config_classes.brush + " .overlay"), brushSize = { width: 0, height: 0 }; brush.size() && (brushSize.width = +brush.attr("width"), brushSize.height = +brush.attr("height")), svg.selectAll(["#" + clip.id, "#" + clip.idGrid]).select("rect").attr("width", width).attr("height", height), svg.select("#" + clip.idXAxis).select("rect").call($$.setXAxisClipPath.bind($$)), svg.select("#" + clip.idYAxis).select("rect").call($$.setYAxisClipPath.bind($$)), clip.idSubchart && svg.select("#" + clip.idSubchart).select("rect").attr("width", width).attr("height", brushSize.height); } }, /** * Update size values * @param {boolean} isInit If is called at initialization * @private */ updateSizes: function updateSizes(isInit) { var $$ = this, config = $$.config, state = $$.state, legend = $$.$el.legend, isRotated = config.axis_rotated, hasArc = $$.hasArcType(); isInit || $$.setContainerSize(); var currLegend = { width: legend ? $$.getLegendWidth() : 0, height: legend ? $$.getLegendHeight() : 0 }; !hasArc && config.axis_x_show && config.axis_x_tick_autorotate && $$.updateXAxisTickClip(); var legendHeightForBottom = state.isLegendRight || state.isLegendInset ? 0 : currLegend.height, xAxisHeight = isRotated || hasArc ? 0 : $$.getHorizontalAxisHeight("x"), subchartXAxisHeight = config.subchart_axis_x_show && config.subchart_axis_x_tick_text_show ? xAxisHeight : 30, subchartHeight = config.subchart_show && !hasArc ? config.subchart_size_height + subchartXAxisHeight : 0; state.margin = !hasArc && isRotated ? { top: $$.getHorizontalAxisHeight("y2") + $$.getCurrentPaddingTop(), right: hasArc ? 0 : $$.getCurrentPaddingRight(!0), bottom: $$.getHorizontalAxisHeight("y") + legendHeightForBottom + $$.getCurrentPaddingBottom(), left: subchartHeight + (hasArc ? 0 : $$.getCurrentPaddingLeft()) } : { top: 4 + $$.getCurrentPaddingTop(), // for top tick text right: hasArc ? 0 : $$.getCurrentPaddingRight(!0), bottom: xAxisHeight + subchartHeight + legendHeightForBottom + $$.getCurrentPaddingBottom(), left: hasArc ? 0 : $$.getCurrentPaddingLeft() }, state.margin2 = isRotated ? { top: state.margin.top, right: NaN, bottom: 20 + legendHeightForBottom, left: $$.state.rotatedPadding.left } : { top: state.current.height - subchartHeight - legendHeightForBottom, right: NaN, bottom: subchartXAxisHeight + legendHeightForBottom, left: state.margin.left }, state.margin3 = { top: 0, right: NaN, bottom: 0, left: 0 }, $$.updateSizeForLegend && $$.updateSizeForLegend(currLegend), state.width = state.current.width - state.margin.left - state.margin.right, state.height = state.current.height - state.margin.top - state.margin.bottom, state.width < 0 && (state.width = 0), state.height < 0 && (state.height = 0), state.width2 = isRotated ? state.margin.left - state.rotatedPadding.left - state.rotatedPadding.right : state.width, state.height2 = isRotated ? state.height : state.current.height - state.margin2.top - state.margin2.bottom, state.width2 < 0 && (state.width2 = 0), state.height2 < 0 && (state.height2 = 0); // for arc var hasGauge = $$.hasType("gauge"), isLegendRight = config.legend_show && state.isLegendRight; state.arcWidth = state.width - (isLegendRight ? currLegend.width + 10 : 0), state.arcHeight = state.height - (isLegendRight && !hasGauge ? 0 : 10), hasGauge && !config.gauge_fullCircle && (state.arcHeight += state.height - $$.getPaddingBottomForGauge()), $$.updateRadius && $$.updateRadius(), state.isLegendRight && hasArc && (state.margin3.left = state.arcWidth / 2 + state.radiusExpanded * 1.1); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/text.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var internals_text = ({ opacityForText: function opacityForText(d) { var $$ = this; return $$.isBarType(d) && !$$.meetsLabelThreshold(Math.abs($$.getRatio("bar", d)), "bar") ? "0" : $$.hasDataLabel ? "1" : "0"; }, /** * Initializes the text * @private */ initText: function initText() { var $el = this.$el; $el.main.select("." + config_classes.chart).append("g").attr("class", config_classes.chartTexts); }, /** * Update chartText * @param {object} targets $$.data.targets * @private */ updateTargetsForText: function updateTargetsForText(targets) { var $$ = this, classChartText = $$.getChartClass("Text"), classTexts = $$.getClass("texts", "id"), classFocus = $$.classFocus.bind($$), mainTextUpdate = $$.$el.main.select("." + config_classes.chartTexts).selectAll("." + config_classes.chartText).data(targets).attr("class", function (d) { return classChartText(d) + classFocus(d); }), mainTextEnter = mainTextUpdate.enter().append("g").style("opacity", "0").attr("class", classChartText).style("pointer-events", "none"); mainTextEnter.append("g").attr("class", classTexts); }, /** * Update text * @param {number} durationForExit Fade-out transition duration * @private */ updateText: function updateText(durationForExit) { var $$ = this, config = $$.config, $el = $$.$el, classText = $$.getClass("text", "index"), text = $el.main.selectAll("." + config_classes.texts).selectAll("." + config_classes.text).data($$.labelishData.bind($$)); text.exit().transition().duration(durationForExit).style("fill-opacity", "0").remove(), $el.text = text.enter().append("text").merge(text).attr("class", classText).attr("text-anchor", function (d) { // when value is negative or var isEndAnchor = d.value < 0; if ($$.isCandlestickType(d)) { var data = $$.getCandlestickData(d); isEndAnchor = data && !data._isUp; } return config.axis_rotated ? isEndAnchor ? "end" : "start" : "middle"; }).style("fill", $$.updateTextColor.bind($$)).style("fill-opacity", "0").each(function (d, i, j) { var node = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), value = d.value; if ($$.isBubbleZType(d)) value = $$.getBubbleZData(value, "z");else if ($$.isCandlestickType(d)) { var data = $$.getCandlestickData(d); data && (value = data.close); } value = $$.dataLabelFormat(d.id)(value, d.id, i, j), isNumber(value) ? this.textContent = value : setTextValue(node, value); }); }, updateTextColor: function updateTextColor(d) { var color, $$ = this, config = $$.config, labelColors = config.data_labels_colors, defaultColor = $$.isArcType(d) && !$$.isRadarType(d) ? null : $$.color(d); if (isString(labelColors)) color = labelColors;else if (isObject(labelColors)) { var _ref = d.data || d, id = _ref.id; color = labelColors[id]; } else isFunction(labelColors) && (color = labelColors.bind($$.api)(defaultColor, d)); if ($$.isCandlestickType(d) && !isFunction(labelColors)) { var value = $$.getCandlestickData(d); if (value && !value._isUp) { var downColor = config.candlestick_color_down; color = isObject(downColor) ? downColor[d.id] : downColor; } } return color || defaultColor; }, /** * Redraw chartText * @param {Function} x Positioning function for x * @param {Function} y Positioning function for y * @param {boolean} forFlow Weather is flow * @param {boolean} withTransition transition is enabled * @returns {Array} * @private */ redrawText: function redrawText(x, y, forFlow, withTransition) { var $$ = this, t = getRandom(!0); // need to return 'true' as of being pushed to the redraw list // ref: getRedrawList() return $$.$el.text.style("fill", $$.updateTextColor.bind($$)).style("fill-opacity", forFlow ? 0 : $$.opacityForText.bind($$)).each(function (d, i) { // do not apply transition for newly added text elements var node = withTransition && this.getAttribute("x") ? (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).transition(t) : (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), posX = x.bind(this)(d, i), posY = y.bind(this)(d, i); this.childElementCount ? node.attr("transform", "translate(" + posX + " " + posY + ")") : node.attr("x", posX).attr("y", posY); }), !0; }, /** * Gets the getBoundingClientRect value of the element * @param {HTMLElement|d3.selection} element Target element * @param {string} className Class name * @returns {object} value of element.getBoundingClientRect() * @private */ getTextRect: function getTextRect(element, className) { var $$ = this, base = element.node ? element.node() : element; /text/i.test(base.tagName) || (base = base.querySelector("text")); var text = base.textContent, cacheKey = KEY.textRect + "-" + text.replace(/\W/g, "_"), rect = $$.cache.get(cacheKey); return rect || ($$.$el.svg.append("text").style("visibility", "hidden").style("font", (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(base).style("font")).classed(className, !0).text(text).call(function (v) { rect = getBoundingRect(v.node()); }).remove(), $$.cache.add(cacheKey, rect)), rect; }, /** * Gets the x or y coordinate of the text * @param {object} indices Indices values * @param {boolean} forX whether or not to x * @returns {number} coordinates * @private */ generateXYForText: function generateXYForText(indices, forX) { var $$ = this, types = Object.keys(indices), points = {}, getter = forX ? $$.getXForText : $$.getYForText; return $$.hasType("radar") && types.push("radar"), types.forEach(function (v) { points[v] = $$["generateGet" + capitalize(v) + "Points"](indices[v], !1); }), function (d, i) { var type = $$.isAreaType(d) && "area" || $$.isBarType(d) && "bar" || $$.isCandlestickType(d) && "candlestick" || $$.isRadarType(d) && "radar" || "line"; return getter.call($$, points[type](d, i), d, this); }; }, /** * Get centerized text position for bar type data.label.text * @param {object} d Data object * @param {Array} points Data points position * @param {HTMLElement} textElement Data label text element * @returns {number} Position value * @private */ getCenteredTextPos: function getCenteredTextPos(d, points, textElement) { var $$ = this, config = $$.config, isRotated = config.axis_rotated; if (config.data_labels.centered && $$.isBarType(d)) { var rect = getBoundingRect(textElement), isPositive = d.value >= 0; if (isRotated) { var w = (isPositive ? points[1][1] - points[0][1] : points[0][1] - points[1][1]) / 2 + rect.width / 2; return isPositive ? -w - 3 : w + 2; } var h = (isPositive ? points[0][1] - points[1][1] : points[1][1] - points[0][1]) / 2 + rect.height / 2; return isPositive ? h : -h - 2; } return 0; }, /** * Get data.labels.position value * @param {string} id Data id value * @param {string} type x | y * @returns {number} Position value * @private */ getTextPos: function getTextPos(id, type) { var pos = this.config.data_labels_position; return (id in pos ? pos[id] : pos)[type] || 0; }, /** * Gets the x coordinate of the text * @param {object} points Data points position * @param {object} d Data object * @param {HTMLElement} textElement Data label text element * @returns {number} x coordinate * @private */ getXForText: function getXForText(points, d, textElement) { var $$ = this, config = $$.config, state = $$.state, isRotated = config.axis_rotated, xPos = points[0][0]; if ($$.hasType("candlestick")) isRotated ? xPos = $$.getCandlestickData(d)._isUp ? points[2][2] + 4 : points[2][1] - 4 : xPos += (points[1][0] - xPos) / 2;else if (isRotated) { var padding = $$.isBarType(d) ? 4 : 6; xPos = points[2][1] + padding * (d.value < 0 ? -1 : 1); } else xPos = $$.hasType("bar") ? (points[2][0] + points[0][0]) / 2 : xPos; // show labels regardless of the domain if value is null if (d.value === null) if (xPos > state.width) { var _getBoundingRect = getBoundingRect(textElement), width = _getBoundingRect.width; xPos = state.width - width; } else xPos < 0 && (xPos = 4); return isRotated && (xPos += $$.getCenteredTextPos(d, points, textElement)), xPos + $$.getTextPos(d.id, "x"); }, /** * Gets the y coordinate of the text * @param {object} points Data points position * @param {object} d Data object * @param {HTMLElement} textElement Data label text element * @returns {number} y coordinate * @private */ getYForText: function getYForText(points, d, textElement) { var yPos, $$ = this, config = $$.config, state = $$.state, isRotated = config.axis_rotated, r = config.point_r, rect = getBoundingRect(textElement), value = d.value, baseY = 3; if ($$.isCandlestickType(d)) value = $$.getCandlestickData(d), isRotated ? (yPos = points[0][0], yPos += (points[1][0] - yPos) / 2 + baseY) : yPos = value && value._isUp ? points[2][2] - baseY : points[2][1] + baseY * 4;else if (isRotated) yPos = (points[0][0] + points[2][0] + rect.height * .6) / 2;else if (yPos = points[2][1], isNumber(r) && r > 5 && ($$.isLineType(d) || $$.isScatterType(d)) && (baseY += config.point_r / 2.3), value < 0 || value === 0 && !state.hasPositiveValue && state.hasNegativeValue) yPos += rect.height + ($$.isBarType(d) ? -baseY : baseY);else { var diff = -baseY * 2; $$.isBarType(d) ? diff = -baseY : $$.isBubbleType(d) && (diff = baseY), yPos += diff; } // show labels regardless of the domain if value is null if (d.value === null && !isRotated) { var boxHeight = rect.height; yPos < boxHeight ? yPos = boxHeight : yPos > state.height && (yPos = state.height - 4); } return isRotated || (yPos += $$.getCenteredTextPos(d, points, textElement)), yPos + $$.getTextPos(d.id, "y"); }, /** * Calculate if two or more text nodes are overlapping * Mark overlapping text nodes with "text-overlapping" class * @param {string} id Axis id * @param {ChartInternal} $$ ChartInternal context * @param {string} selector Selector string * @private */ markOverlapped: function markOverlapped(id, $$, selector) { var textNodes = $$.$el.arcs.selectAll(selector), filteredTextNodes = textNodes.filter(function (node) { return node.data.id !== id; }), textNode = textNodes.filter(function (node) { return node.data.id === id; }), translate = getTranslation(textNode.node()), calcHypo = function (x, y) { return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); }; textNode.node() && filteredTextNodes.each(function () { var coordinate = getTranslation(this), filteredTextNode = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), nodeForWidth = calcHypo(translate.e, translate.f) > calcHypo(coordinate.e, coordinate.f) ? textNode : filteredTextNode, overlapsX = Math.ceil(Math.abs(translate.e - coordinate.e)) < Math.ceil(nodeForWidth.node().getComputedTextLength()), overlapsY = Math.ceil(Math.abs(translate.f - coordinate.f)) < parseInt(textNode.style("font-size"), 10); filteredTextNode.classed(config_classes.TextOverlapping, overlapsX && overlapsY); }); }, /** * Calculate if two or more text nodes are overlapping * Remove "text-overlapping" class on selected text nodes * @param {ChartInternal} $$ ChartInternal context * @param {string} selector Selector string * @private */ undoMarkOverlapped: function undoMarkOverlapped($$, selector) { $$.$el.arcs.selectAll(selector).each(function () { (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.selectAll)([this, this.previousSibling]).classed(config_classes.TextOverlapping, !1); }); }, /** * Check if meets the ratio to show data label text * @param {number} ratio ratio to meet * @param {string} type chart type * @returns {boolean} * @private */ meetsLabelThreshold: function meetsLabelThreshold(ratio, type) { ratio === void 0 && (ratio = 0); var $$ = this, config = $$.config, threshold = config[type + "_label_threshold"] || 0; return ratio >= threshold; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/title.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Get the text position * @param {string} pos right, left or center * @param {number} width chart width * @returns {string|number} text-anchor value or position in pixel * @private */ function getTextPos(pos, width) { pos === void 0 && (pos = "left"); var position, isNum = isNumber(width); return position = pos.indexOf("center") > -1 ? isNum ? width / 2 : "middle" : pos.indexOf("right") > -1 ? isNum ? width : "end" : isNum ? 0 : "start", position; } /* harmony default export */ var internals_title = ({ /** * Initializes the title * @private */ initTitle: function initTitle() { var $$ = this, config = $$.config, $el = $$.$el; if (config.title_text) { $el.title = $el.svg.append("g"); var text = $el.title.append("text").style("text-anchor", getTextPos(config.title_position)).attr("class", config_classes.title); setTextValue(text, config.title_text, [.3, 1.5]); } }, /** * Redraw title * @private */ redrawTitle: function redrawTitle() { var $$ = this, config = $$.config, current = $$.state.current, title = $$.$el.title; if (title) { var y = $$.yForTitle.call($$); /g/i.test(title.node().tagName) ? title.attr("transform", "translate(" + getTextPos(config.title_position, current.width) + ", " + y + ")") : title.attr("x", $$.xForTitle.call($$)).attr("y", y); } }, /** * Returns the x attribute value of the title * @returns {number} x attribute value * @private */ xForTitle: function xForTitle() { var x, $$ = this, config = $$.config, current = $$.state.current, position = config.title_position || "left", textRectWidth = $$.getTextRect($$.$el.title, config_classes.title).width; return /(right|center)/.test(position) ? (x = current.width - textRectWidth, position.indexOf("right") >= 0 ? x = current.width - textRectWidth - config.title_padding.right : position.indexOf("center") >= 0 && (x = (current.width - textRectWidth) / 2)) : x = config.title_padding.left || 0, x; }, /** * Returns the y attribute value of the title * @returns {number} y attribute value * @private */ yForTitle: function yForTitle() { var $$ = this; return ($$.config.title_padding.top || 0) + $$.getTextRect($$.$el.title, config_classes.title).height; }, /** * Get title padding * @returns {number} padding value * @private */ getTitlePadding: function getTitlePadding() { var $$ = this; return $$.yForTitle() + ($$.config.title_padding.bottom || 0); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/tooltip.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var internals_tooltip = ({ /** * Initializes the tooltip * @private */ initTooltip: function initTooltip() { var $$ = this, config = $$.config, $el = $$.$el; $el.tooltip = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(config.tooltip_contents.bindto), $el.tooltip.empty() && ($el.tooltip = $el.chart.style("position", "relative").append("div").attr("class", config_classes.tooltipContainer).style("position", "absolute").style("pointer-events", "none").style("display", "none")), $$.bindTooltipResizePos(); }, initShowTooltip: function initShowTooltip() { var $$ = this, config = $$.config, $el = $$.$el, _$$$state = $$.state, hasAxis = _$$$state.hasAxis, hasRadar = _$$$state.hasRadar; // Show tooltip if needed if (config.tooltip_init_show) { var isArc = !(hasAxis && hasRadar); if ($$.axis && $$.axis.isTimeSeries() && isString(config.tooltip_init_x)) { var i, val, targets = $$.data.targets[0]; for (config.tooltip_init_x = parseDate.call($$, config.tooltip_init_x), i = 0; (val = targets.values[i]) && !(val.x - config.tooltip_init_x === 0); i++); config.tooltip_init_x = i; } var data = $$.data.targets.map(function (d) { var x = isArc ? 0 : config.tooltip_init_x; return $$.addName(d.values[x]); }); isArc && (data = [data[config.tooltip_init_x]]), $el.tooltip.html($$.getTooltipHTML(data, $$.axis && $$.axis.getXAxisTickFormat(), $$.getYFormat($$.hasArcType(null, ["radar"])), $$.color)), config.tooltip_contents.bindto || $el.tooltip.style("top", config.tooltip_init_position.top).style("left", config.tooltip_init_position.left).style("display", "block"); } }, /** * Get the tooltip HTML string * @param {Array} args Arguments * @returns {string} Formatted HTML string * @private */ getTooltipHTML: function getTooltipHTML() { var $$ = this, api = $$.api, config = $$.config; return isFunction(config.tooltip_contents) ? config.tooltip_contents.bind(api).apply(void 0, arguments) : $$.getTooltipContent.apply($$, arguments); }, /** * Returns the tooltip content(HTML string) * @param {object} d data * @param {Function} defaultTitleFormat Default title format * @param {Function} defaultValueFormat Default format for each data value in the tooltip. * @param {Function} color Color function * @returns {string} html * @private */ getTooltipContent: function getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color) { var $$ = this, api = $$.api, config = $$.config, state = $$.state, _map = ["title", "name", "value"].map(function (v) { var fn = config["tooltip_format_" + v]; return isFunction(fn) ? fn.bind(api) : fn; }), titleFormat = _map[0], nameFormat = _map[1], valueFormat = _map[2]; titleFormat = titleFormat || defaultTitleFormat, nameFormat = nameFormat || function (name) { return name; }, valueFormat = valueFormat || ($$.isStackNormalized() ? function (v, ratio) { return (ratio * 100).toFixed(2) + "%"; } : defaultValueFormat); var order = config.tooltip_order, getRowValue = function (row) { return $$.axis && $$.isBubbleZType(row) ? $$.getBubbleZData(row.value, "z") : $$.getBaseValue(row); }, getBgColor = $$.levelColor ? function (row) { return $$.levelColor(row.value); } : function (row) { return color(row); }, contents = config.tooltip_contents, tplStr = contents.template, targetIds = $$.mapToTargetIds(); if (order === null && config.data_groups.length) { // for stacked data, order should aligned with the visually displayed data var ids = $$.orderTargets($$.data.targets).map(function (i2) { return i2.id; }).reverse(); d.sort(function (a, b) { var v1 = a ? a.value : null, v2 = b ? b.value : null; return v1 > 0 && v2 > 0 && (v1 = a.id ? ids.indexOf(a.id) : null, v2 = b.id ? ids.indexOf(b.id) : null), v1 - v2; }); } else if (/^(asc|desc)$/.test(order)) { d.sort(function (a, b) { var v1 = a ? getRowValue(a) : null, v2 = b ? getRowValue(b) : null; return order === "asc" ? v1 - v2 : v2 - v1; }); } else isFunction(order) && d.sort(order.bind(api)); var text, row, param, value, i, tpl = $$.getTooltipContentTemplate(tplStr), len = d.length; for (i = 0; i < len; i++) if (row = d[i], row && (getRowValue(row) || getRowValue(row) === 0)) { if (isUndefined(text)) { var title = (state.hasAxis || state.hasRadar) && sanitise(titleFormat ? titleFormat(row.x) : row.x); text = tplProcess(tpl[0], { CLASS_TOOLTIP: config_classes.tooltip, TITLE: isValue(title) ? tplStr ? title : "<tr><th colspan=\"2\">" + title + "</th></tr>" : "" }); } if (!row.ratio && $$.$el.arcs && (row.ratio = $$.getRatio("arc", $$.$el.arcs.select("path." + config_classes.arc + "-" + row.id).data()[0])), param = [row.ratio, row.id, row.index, d], value = sanitise(valueFormat.apply(void 0, [getRowValue(row)].concat(param))), $$.isAreaRangeType(row)) { var _map2 = ["high", "low"].map(function (v) { return sanitise(valueFormat.apply(void 0, [$$.getRangedData(row, v)].concat(param))); }), high = _map2[0], low = _map2[1]; value = "<b>Mid:</b> " + value + " <b>High:</b> " + high + " <b>Low:</b> " + low; } else if ($$.isCandlestickType(row)) { var _map3 = ["open", "high", "low", "close", "volume"].map(function (v) { return sanitise(valueFormat.apply(void 0, [$$.getRangedData(row, v, "candlestick")].concat(param))); }), open = _map3[0], _high = _map3[1], _low = _map3[2], close = _map3[3], volume = _map3[4]; value = "<b>Open:</b> " + open + " <b>High:</b> " + _high + " <b>Low:</b> " + _low + " <b>Close:</b> " + close + (volume ? " <b>Volume:</b> " + volume : ""); } if (value !== undefined) { var _ret = function () { // Skip elements when their name is set to null if (row.name === null) return "continue"; var name = sanitise(nameFormat.apply(void 0, [row.name].concat(param))), color = getBgColor(row), contentValue = { CLASS_TOOLTIP_NAME: config_classes.tooltipName + $$.getTargetSelectorSuffix(row.id), COLOR: tplStr || !$$.patterns ? color : "<svg><rect style=\"fill:" + color + "\" width=\"10\" height=\"10\"></rect></svg>", NAME: name, VALUE: value }; if (tplStr && isObject(contents.text)) { var index = targetIds.indexOf(row.id); Object.keys(contents.text).forEach(function (key) { contentValue[key] = contents.text[key][index]; }); } text += tplProcess(tpl[1], contentValue); }(); if (_ret === "continue") continue; } } return text + "</table>"; }, /** * Get the content template string * @param {string} tplStr Tempalte string * @returns {Array} Template string * @private */ getTooltipContentTemplate: function getTooltipContentTemplate(tplStr) { return (tplStr || "<table class=\"{=CLASS_TOOLTIP}\"><tbody>\n\t\t\t\t{=TITLE}\n\t\t\t\t{{<tr class=\"{=CLASS_TOOLTIP_NAME}\">\n\t\t\t\t\t<td class=\"name\">" + (this.patterns ? "{=COLOR}" : "<span style=\"background-color:{=COLOR}\"></span>") + "{=NAME}</td>\n\t\t\t\t\t<td class=\"value\">{=VALUE}</td>\n\t\t\t\t</tr>}}\n\t\t\t</tbody></table>").replace(/(\r?\n|\t)/g, "").split(/{{(.*)}}/); }, /** * Returns the position of the tooltip * @param {object} dataToShow data * @param {string} tWidth Width value of tooltip element * @param {string} tHeight Height value of tooltip element * @param {HTMLElement} element Tooltip element * @returns {object} top, left value * @private */ tooltipPosition: function tooltipPosition(dataToShow, tWidth, tHeight, element) { var $$ = this, config = $$.config, scale = $$.scale, state = $$.state, _state = state, width = _state.width, height = _state.height, current = _state.current, isLegendRight = _state.isLegendRight, inputType = _state.inputType, event = _state.event, hasGauge = $$.hasType("gauge") && !config.gauge_fullCircle, svgLeft = $$.getSvgLeft(!0), chartRight = svgLeft + current.width - $$.getCurrentPaddingRight(), chartLeft = $$.getCurrentPaddingLeft(!0), size = 20, _getPointer = getPointer(event, element), x = _getPointer[0], y = _getPointer[1]; // Determine tooltip position if ($$.hasArcType()) { var raw = inputType === "touch" || $$.hasType("radar"); raw || (y += hasGauge ? height : height / 2, x += (width - (isLegendRight ? $$.getLegendWidth() : 0)) / 2); } else { var dataScale = scale.x(dataToShow[0].x); config.axis_rotated ? (y = dataScale + size, x += svgLeft + 100, chartRight -= svgLeft) : (y -= 5, x = svgLeft + chartLeft + size + ($$.zoomScale ? x : dataScale)); } // when tooltip left + tWidth > chart's width x + tWidth + 15 > chartRight && (x -= tWidth + chartLeft), y + tHeight > current.height && (y -= hasGauge ? tHeight * 3 : tHeight + 30); var pos = { top: y, left: x }; // make sure to not be positioned out of viewport return Object.keys(pos).forEach(function (v) { pos[v] < 0 && (pos[v] = 0); }), pos; }, /** * Show the tooltip * @param {object} selectedData Data object * @param {HTMLElement} element Tooltip element * @private */ showTooltip: function showTooltip(selectedData, element) { var $$ = this, config = $$.config, state = $$.state, tooltip = $$.$el.tooltip, bindto = config.tooltip_contents.bindto, forArc = $$.hasArcType(null, ["radar"]), dataToShow = selectedData.filter(function (d) { return d && isValue($$.getBaseValue(d)); }); if (tooltip && dataToShow.length !== 0 && config.tooltip_show) { var datum = tooltip.datum(), _ref = datum || {}, _ref$width = _ref.width, width = _ref$width === void 0 ? 0 : _ref$width, _ref$height = _ref.height, height = _ref$height === void 0 ? 0 : _ref$height, dataStr = JSON.stringify(selectedData); if (!datum || datum.current !== dataStr) { var index = selectedData.concat().sort()[0].index; callFn(config.tooltip_onshow, $$.api, selectedData), tooltip.html($$.getTooltipHTML(selectedData, // data $$.axis ? $$.axis.getXAxisTickFormat() : $$.categoryName.bind($$), // defaultTitleFormat $$.getYFormat(forArc), // defaultValueFormat $$.color // color )).style("display", null).style("visibility", null) // for IE9 .datum(datum = { index: index, current: dataStr, width: width = tooltip.property("offsetWidth"), height: height = tooltip.property("offsetHeight") }), callFn(config.tooltip_onshown, $$.api, selectedData), $$._handleLinkedCharts(!0, index); } if (!bindto) { var fnPos = config.tooltip_position || $$.tooltipPosition, pos = fnPos.call(this, dataToShow, width, height, element); // Get tooltip dimensions ["top", "left"].forEach(function (v) { var value = pos[v]; tooltip.style(v, value + "px"), v !== "left" || datum.xPosInPercent || (datum.xPosInPercent = value / state.current.width * 100); }); } } }, /** * Adjust tooltip position on resize event * @private */ bindTooltipResizePos: function bindTooltipResizePos() { var $$ = this, resizeFunction = $$.resizeFunction, state = $$.state, tooltip = $$.$el.tooltip; resizeFunction.add(function () { if (tooltip.style("display") === "block") { var current = state.current, _tooltip$datum = tooltip.datum(), width = _tooltip$datum.width, xPosInPercent = _tooltip$datum.xPosInPercent, _value = current.width / 100 * xPosInPercent, diff = current.width - (_value + width); diff < 0 && (_value += diff), tooltip.style("left", _value + "px"); } }); }, /** * Hide the tooltip * @param {boolean} force Force to hide * @private */ hideTooltip: function hideTooltip(force) { var $$ = this, api = $$.api, config = $$.config, tooltip = $$.$el.tooltip; if (tooltip && tooltip.style("display") !== "none" && (!config.tooltip_doNotHide || force)) { var selectedData = JSON.parse(tooltip.datum().current); // hide tooltip callFn(config.tooltip_onhide, api, selectedData), tooltip.style("display", "none").style("visibility", "hidden") // for IE9 .datum(null), callFn(config.tooltip_onhidden, api, selectedData); } }, /** * Toggle display for linked chart instances * @param {boolean} show true: show, false: hide * @param {number} index x Axis index * @private */ _handleLinkedCharts: function _handleLinkedCharts(show, index) { var $$ = this, charts = $$.charts, config = $$.config, event = $$.state.event; // Prevent propagation among instances if isn't instantiated from the user's event // https://github.com/naver/billboard.js/issues/1979 if (event && event.isTrusted && config.tooltip_linked && charts.length > 1) { var linkedName = config.tooltip_linked_name; charts.filter(function (c) { return c !== $$.api; }).forEach(function (c) { var _c$internal = c.internal, config = _c$internal.config, $el = _c$internal.$el, isLinked = config.tooltip_linked, name = config.tooltip_linked_name, isInDom = browser_doc.body.contains($el.chart.node()); if (isLinked && linkedName === name && isInDom) { var data = $el.tooltip.data()[0], isNotSameIndex = index !== (data && data.index); try { c.tooltip[show && isNotSameIndex ? "show" : "hide"]({ index: index }); } catch (e) {} } }); } } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/transform.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var transform = ({ getTranslate: function getTranslate(target, index) { index === void 0 && (index = 0); var x, y, $$ = this, config = $$.config, state = $$.state, isRotated = config.axis_rotated, padding = 0; if (index && /^(x|y2?)$/.test(target) && (padding = $$.getAxisSize(target) * index), target === "main") x = asHalfPixel(state.margin.left), y = asHalfPixel(state.margin.top);else if (target === "context") x = asHalfPixel(state.margin2.left), y = asHalfPixel(state.margin2.top);else if (target === "legend") x = state.margin3.left, y = state.margin3.top;else if (target === "x") x = isRotated ? -padding : 0, y = isRotated ? 0 : state.height + padding;else if (target === "y") x = isRotated ? 0 : -padding, y = isRotated ? state.height + padding : 0;else if (target === "y2") x = isRotated ? 0 : state.width + padding, y = isRotated ? 1 - padding : 0;else if (target === "subX") x = 0, y = isRotated ? 0 : state.height2;else if (target === "arc") x = state.arcWidth / 2, y = state.arcHeight / 2;else if (target === "radar") { var _$$$getRadarSize = $$.getRadarSize(), width = _$$$getRadarSize[0]; x = state.width / 2 - width, y = asHalfPixel(state.margin.top); } return "translate(" + x + ", " + y + ")"; }, transformMain: function transformMain(withTransition, transitions) { var xAxis, yAxis, y2Axis, $$ = this, main = $$.$el.main; transitions && transitions.axisX ? xAxis = transitions.axisX : (xAxis = main.select("." + config_classes.axisX), withTransition && (xAxis = xAxis.transition())), transitions && transitions.axisY ? yAxis = transitions.axisY : (yAxis = main.select("." + config_classes.axisY), withTransition && (yAxis = yAxis.transition())), transitions && transitions.axisY2 ? y2Axis = transitions.axisY2 : (y2Axis = main.select("." + config_classes.axisY2), withTransition && (y2Axis = y2Axis.transition())), (withTransition ? main.transition() : main).attr("transform", $$.getTranslate("main")), xAxis.attr("transform", $$.getTranslate("x")), yAxis.attr("transform", $$.getTranslate("y")), y2Axis.attr("transform", $$.getTranslate("y2")), main.select("." + config_classes.chartArcs).attr("transform", $$.getTranslate("arc")); }, transformAll: function transformAll(withTransition, transitions) { var $$ = this, config = $$.config, hasAxis = $$.state.hasAxis, $el = $$.$el; $$.transformMain(withTransition, transitions), hasAxis && config.subchart_show && $$.transformContext(withTransition, transitions), $el.legend && $$.transformLegend(withTransition); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/type.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var type = ({ setTargetType: function setTargetType(targetIds, type) { var $$ = this, config = $$.config, withoutFadeIn = $$.state.withoutFadeIn; $$.mapToTargetIds(targetIds).forEach(function (id) { withoutFadeIn[id] = type === config.data_types[id], config.data_types[id] = type; }), targetIds || (config.data_type = type); }, /** * Updte current used chart types * @private */ updateTypesElements: function updateTypesElements() { var $$ = this, current = $$.state.current; // Update current chart elements reference Object.keys(TYPE).forEach(function (v) { var t = TYPE[v], has = $$.hasType(t, null, !0), idx = current.types.indexOf(t); idx === -1 && has ? current.types.push(t) : idx > -1 && !has && current.types.splice(idx, 1); }), $$.setChartElements(); }, /** * Check if given chart types exists * @param {string} type Chart type * @param {Array} targetsValue Data array * @param {boolean} checkFromData Force to check type cotains from data targets * @returns {boolean} * @private */ hasType: function hasType(type, targetsValue, checkFromData) { checkFromData === void 0 && (checkFromData = !1); var $$ = this, config = $$.config, current = $$.state.current, types = config.data_types, targets = targetsValue || $$.data.targets, has = !1; return !checkFromData && current.types.length && current.types.indexOf(type) > -1 ? has = !0 : targets && targets.length ? targets.forEach(function (target) { var t = types[target.id]; t !== type && (t || type !== "line") || (has = !0); }) : Object.keys(types).length ? Object.keys(types).forEach(function (id) { types[id] === type && (has = !0); }) : has = config.data_type === type, has; }, /** * Check if contains given chart types * @param {string} type Type key * @param {object} targets Target data * @param {Array} exclude Excluded types * @returns {boolean} * @private */ hasTypeOf: function hasTypeOf(type, targets, exclude) { var _this = this; return exclude === void 0 && (exclude = []), !!(type in TYPE_BY_CATEGORY) && !TYPE_BY_CATEGORY[type].filter(function (v) { return exclude.indexOf(v) === -1; }).every(function (v) { return !_this.hasType(v, targets); }); }, /** * Check if given data is certain chart type * @param {object} d Data object * @param {string|Array} type chart type * @returns {boolean} * @private */ isTypeOf: function isTypeOf(d, type) { var id = isString(d) ? d : d.id, dataType = this.config.data_types[id] || this.config.data_type; return isArray(type) ? type.indexOf(dataType) >= 0 : dataType === type; }, hasPointType: function hasPointType() { var $$ = this; return $$.hasTypeOf("Line") || $$.hasType("bubble") || $$.hasType("scatter"); }, /** * Check if contains arc types chart * @param {object} targets Target data * @param {Array} exclude Excluded types * @returns {boolean} * @private */ hasArcType: function hasArcType(targets, exclude) { return this.hasTypeOf("Arc", targets, exclude); }, hasMultiArcGauge: function hasMultiArcGauge() { return this.hasType("gauge") && this.config.gauge_type === "multi"; }, isLineType: function isLineType(d) { var id = isString(d) ? d : d.id; return !this.config.data_types[id] || this.isTypeOf(id, TYPE_BY_CATEGORY.Line); }, isStepType: function isStepType(d) { return this.isTypeOf(d, TYPE_BY_CATEGORY.Step); }, isSplineType: function isSplineType(d) { return this.isTypeOf(d, TYPE_BY_CATEGORY.Spline); }, isAreaType: function isAreaType(d) { return this.isTypeOf(d, TYPE_BY_CATEGORY.Area); }, isAreaRangeType: function isAreaRangeType(d) { return this.isTypeOf(d, TYPE_BY_CATEGORY.AreaRange); }, isBarType: function isBarType(d) { return this.isTypeOf(d, "bar"); }, isBubbleType: function isBubbleType(d) { return this.isTypeOf(d, "bubble"); }, isCandlestickType: function isCandlestickType(d) { return this.isTypeOf(d, "candlestick"); }, isScatterType: function isScatterType(d) { return this.isTypeOf(d, "scatter"); }, isPieType: function isPieType(d) { return this.isTypeOf(d, "pie"); }, isGaugeType: function isGaugeType(d) { return this.isTypeOf(d, "gauge"); }, isDonutType: function isDonutType(d) { return this.isTypeOf(d, "donut"); }, isRadarType: function isRadarType(d) { return this.isTypeOf(d, "radar"); }, isArcType: function isArcType(d) { return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d) || this.isRadarType(d); }, // determine if is 'circle' data point isCirclePoint: function isCirclePoint(node) { var config = this.config, pattern = config.point_pattern, isCircle = !1; return isCircle = !!(node && node.tagName === "circle") || config.point_type === "circle" && (!pattern || isArray(pattern) && pattern.length === 0), isCircle; }, lineData: function lineData(d) { return this.isLineType(d) ? [d] : []; }, arcData: function arcData(d) { return this.isArcType(d.data) ? [d] : []; }, /** * Get data adapt for data label showing * @param {object} d Data object * @returns {Array} * @private */ labelishData: function labelishData(d) { return this.isBarType(d) || this.isLineType(d) || this.isScatterType(d) || this.isBubbleType(d) || this.isCandlestickType(d) || this.isRadarType(d) ? d.values.filter(function (v) { return isNumber(v.value) || !!v.value; }) : []; }, barLineBubbleData: function barLineBubbleData(d) { return this.isBarType(d) || this.isLineType(d) || this.isBubbleType(d) ? d.values : []; }, // https://github.com/d3/d3-shape#curves isInterpolationType: function isInterpolationType(type) { return ["basis", "basis-closed", "basis-open", "bundle", "cardinal", "cardinal-closed", "cardinal-open", "catmull-rom", "catmull-rom-closed", "catmull-rom-open", "linear", "linear-closed", "monotone-x", "monotone-y", "natural"].indexOf(type) >= 0; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/ChartInternal.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license * @ignore */ // data // interactions // internals // used to retrieve radar Axis name /** * Internal chart class. * - Note: Instantiated internally, not exposed for public. * @class ChartInternal * @ignore * @private */ var ChartInternal = /*#__PURE__*/function () { // API interface // config object // cache instance // elements // state variables // all Chart instances array within page (equivalent of 'bb.instances') // data object // Axis // Axis // scales // original values // formatter function // format function function ChartInternal(api) { this.api = void 0, this.config = void 0, this.cache = void 0, this.$el = void 0, this.state = void 0, this.charts = void 0, this.data = { xs: {}, targets: [] }, this.axis = void 0, this.scale = { x: null, y: null, y2: null, subX: null, subY: null, subY2: null, zoom: null }, this.org = { xScale: null, xDomain: null }, this.color = void 0, this.patterns = void 0, this.levelColor = void 0, this.point = void 0, this.brush = void 0, this.format = { extraLineClasses: null, xAxisTick: null, dataTime: null, // dataTimeFormat defaultAxisTime: null, // defaultAxisTimeFormat axisTime: null // axisTimeFormat }; var $$ = this; $$.api = api, $$.config = new Options(), $$.cache = new Cache(); var store = new Store(); $$.$el = store.getStore("element"), $$.state = store.getStore("state"); } var _proto = ChartInternal.prototype; return _proto.beforeInit = function beforeInit() { var $$ = this; $$.callPluginHook("$beforeInit"), callFn($$.config.onbeforeinit, $$.api); }, _proto.afterInit = function afterInit() { var $$ = this; $$.callPluginHook("$afterInit"), callFn($$.config.onafterinit, $$.api); }, _proto.init = function init() { var $$ = this, config = $$.config, state = $$.state, $el = $$.$el; state.hasAxis = !$$.hasArcType(), state.hasRadar = !state.hasAxis && $$.hasType("radar"), $$.initParams(); var bindto = { element: config.bindto, classname: "bb" }; isObject(config.bindto) && (bindto.element = config.bindto.element || "#chart", bindto.classname = config.bindto.classname || bindto.classname), $el.chart = isFunction(bindto.element.node) ? config.bindto.element : (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(bindto.element || []), $el.chart.empty() && ($el.chart = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(browser_doc.body.appendChild(browser_doc.createElement("div")))), $el.chart.html("").classed(bindto.classname, !0), $$.initToRender(); } /** * Initialize the rendering process * @param {boolean} forced Force to render process * @private */ , _proto.initToRender = function initToRender(forced) { var $$ = this, config = $$.config, state = $$.state, chart = $$.$el.chart, isHidden = function () { return chart.style("display") === "none" || chart.style("visibility") === "hidden"; }, isLazy = config.render.lazy || isHidden(), MutationObserver = win.MutationObserver; if (isLazy && MutationObserver && config.render.observe !== !1 && !forced && new MutationObserver(function (mutation, observer) { isHidden() || (observer.disconnect(), !state.rendered && $$.initToRender(!0)); }).observe(chart.node(), { attributes: !0, attributeFilter: ["class", "style"] }), !isLazy || forced) { var convertedData = $$.convertData(config, $$.initWithData); convertedData && $$.initWithData(convertedData), $$.afterInit(); } }, _proto.initParams = function initParams() { var $$ = this, _ref = $$, config = _ref.config, format = _ref.format, state = _ref.state, isRotated = config.axis_rotated; if (state.datetimeId = "bb-" + +new Date(), $$.color = $$.generateColor(), $$.levelColor = $$.generateLevelColor(), $$.hasPointType() && ($$.point = $$.generatePoint()), state.hasAxis) { $$.initClip(), format.extraLineClasses = $$.generateExtraLineClass(), format.dataTime = config.data_xLocaltime ? external_commonjs_d3_time_format_commonjs2_d3_time_format_amd_d3_time_format_root_d3_.timeParse : external_commonjs_d3_time_format_commonjs2_d3_time_format_amd_d3_time_format_root_d3_.utcParse, format.axisTime = config.axis_x_localtime ? external_commonjs_d3_time_format_commonjs2_d3_time_format_amd_d3_time_format_root_d3_.timeFormat : external_commonjs_d3_time_format_commonjs2_d3_time_format_amd_d3_time_format_root_d3_.utcFormat; var isDragZoom = $$.config.zoom_enabled && $$.config.zoom_type === "drag"; format.defaultAxisTime = function (d) { var _$$$scale = $$.scale, x = _$$$scale.x, zoom = _$$$scale.zoom, isZoomed = isDragZoom ? zoom : zoom && x.orgDomain().toString() !== zoom.domain().toString(), specifier = d.getMilliseconds() && ".%L" || d.getSeconds() && ".:%S" || d.getMinutes() && "%I:%M" || d.getHours() && "%I %p" || d.getDate() !== 1 && "%b %d" || isZoomed && d.getDate() === 1 && "%b\'%y" || d.getMonth() && "%-m/%-d" || "%Y"; return format.axisTime(specifier)(d); }; } state.isLegendRight = config.legend_position === "right", state.isLegendInset = config.legend_position === "inset", state.isLegendTop = config.legend_inset_anchor === "top-left" || config.legend_inset_anchor === "top-right", state.isLegendLeft = config.legend_inset_anchor === "top-left" || config.legend_inset_anchor === "bottom-left", state.rotatedPaddingRight = isRotated && !config.axis_x_show ? 0 : 30, state.inputType = convertInputType(config.interaction_inputType_mouse, config.interaction_inputType_touch); }, _proto.initWithData = function initWithData(data) { var $$ = this, config = $$.config, scale = $$.scale, state = $$.state, $el = $$.$el, org = $$.org, hasAxis = state.hasAxis, hasInteraction = config.interaction_enabled; hasAxis && ($$.axis = $$.getAxisInstance(), config.zoom_enabled && $$.initZoom()), $$.data.xs = {}, $$.data.targets = $$.convertDataToTargets(data), config.data_filter && ($$.data.targets = $$.data.targets.filter(config.data_filter.bind($$.api))), config.data_hide && $$.addHiddenTargetIds(config.data_hide === !0 ? $$.mapToIds($$.data.targets) : config.data_hide), config.legend_hide && $$.addHiddenLegendIds(config.legend_hide === !0 ? $$.mapToIds($$.data.targets) : config.legend_hide), $$.updateSizes(), $$.updateScales(!0); // retrieve scale after the 'updateScales()' is called var x = scale.x, y = scale.y, y2 = scale.y2, subX = scale.subX, subY = scale.subY, subY2 = scale.subY2; // Set domains for each scale if (x && (x.domain(sortValue($$.getXDomain($$.data.targets))), subX.domain(x.domain()), org.xDomain = x.domain()), y && (y.domain($$.getYDomain($$.data.targets, "y")), subY.domain(y.domain())), y2 && (y2.domain($$.getYDomain($$.data.targets, "y2")), subY2 && subY2.domain(y2.domain())), $el.svg = $el.chart.append("svg").style("overflow", "hidden").style("display", "block"), hasInteraction && state.inputType) { var isTouch = state.inputType === "touch"; $el.svg.on(isTouch ? "touchstart" : "mouseenter", function () { return callFn(config.onover, $$.api); }).on(isTouch ? "touchend" : "mouseleave", function () { return callFn(config.onout, $$.api); }); } config.svg_classname && $el.svg.attr("class", config.svg_classname); // Define defs var hasColorPatterns = isFunction(config.color_tiles) && $$.patterns; (hasAxis || hasColorPatterns) && ($el.defs = $el.svg.append("defs"), hasAxis && ["id", "idXAxis", "idYAxis", "idGrid"].forEach(function (v) { $$.appendClip($el.defs, state.clip[v]); }), hasColorPatterns && $$.patterns.forEach(function (p) { return $el.defs.append(function () { return p.node; }); })), $$.updateSvgSize(), $$.bindResize(); // Define regions var main = $el.svg.append("g").classed(config_classes.main, !0).attr("transform", $$.getTranslate("main")); // data.onmin/max callback if ($el.main = main, config.subchart_show && $$.initSubchart(), config.tooltip_show && $$.initTooltip(), config.title_text && $$.initTitle(), config.legend_show && $$.initLegend(), config.data_empty_label_text && main.append("text").attr("class", config_classes.text + " " + config_classes.empty).attr("text-anchor", "middle") // horizontal centering of text at x position in all browsers. .attr("dominant-baseline", "middle"), hasAxis && (config.regions.length && $$.initRegion(), !config.clipPath && $$.axis.init()), main.append("g").attr("class", config_classes.chart).attr("clip-path", state.clip.path), $$.callPluginHook("$init"), hasAxis && (hasInteraction && $$.initEventRect && $$.initEventRect(), $$.initGrid(), config.clipPath && $$.axis && $$.axis.init()), $$.initChartElements(), $$.updateTargets($$.data.targets), $$.updateDimension(), callFn(config.oninit, $$.api), $$.setBackground(), $$.redraw({ withTransition: !1, withTransform: !0, withUpdateXDomain: !0, withUpdateOrgXDomain: !0, withTransitionForAxis: !1, initializing: !0 }), config.data_onmin || config.data_onmax) { var minMax = $$.getMinMaxData(); callFn(config.data_onmin, $$.api, minMax.min), callFn(config.data_onmax, $$.api, minMax.max); } config.tooltip_show && $$.initShowTooltip(), state.rendered = !0; }, _proto.initChartElements = function initChartElements() { var $$ = this, _$$$state = $$.state, hasAxis = _$$$state.hasAxis, hasRadar = _$$$state.hasRadar, types = []; hasAxis ? ["bar", "bubble", "candlestick", "line"].forEach(function (v) { var name = capitalize(v); (v === "line" && $$.hasTypeOf(name) || $$.hasType(v)) && types.push(name); }) : (!hasRadar && types.push("Arc", "Pie"), $$.hasType("gauge") ? types.push("Gauge") : hasRadar && types.push("Radar")), types.forEach(function (v) { $$["init" + v](); }), notEmpty($$.config.data_labels) && !$$.hasArcType(null, ["radar"]) && $$.initText(); }, _proto.setChartElements = function setChartElements() { var $$ = this, _$$$$el = $$.$el, chart = _$$$$el.chart, svg = _$$$$el.svg, defs = _$$$$el.defs, main = _$$$$el.main, tooltip = _$$$$el.tooltip, legend = _$$$$el.legend, title = _$$$$el.title, grid = _$$$$el.grid, arc = _$$$$el.arcs, circles = _$$$$el.circle, bars = _$$$$el.bar, candlestick = _$$$$el.candlestick, lines = _$$$$el.line, areas = _$$$$el.area, texts = _$$$$el.text; $$.api.$ = { chart: chart, svg: svg, defs: defs, main: main, tooltip: tooltip, legend: legend, title: title, grid: grid, arc: arc, circles: circles, bar: { bars: bars }, candlestick: candlestick, line: { lines: lines, areas: areas }, text: { texts: texts } }; } /** * Set background element/image * @private */ , _proto.setBackground = function setBackground() { var $$ = this, bg = $$.config.background, state = $$.state, svg = $$.$el.svg; if (notEmpty(bg)) { var element = svg.select("g").insert(bg.imgUrl ? "image" : "rect", ":first-child"); bg.imgUrl ? element.attr("href", bg.imgUrl) : bg.color && element.style("fill", bg.color).attr("clip-path", state.clip.path), element.attr("class", bg.class || null).attr("width", "100%").attr("height", "100%"); } } /** * Update targeted element with given data * @param {object} targets Data object formatted as 'target' * @private */ , _proto.updateTargets = function updateTargets(targets) { var $$ = this, _$$$state2 = $$.state, hasAxis = _$$$state2.hasAxis, hasRadar = _$$$state2.hasRadar; $$.updateTargetsForText(targets), hasAxis ? (["bar", "candlestick", "line"].forEach(function (v) { var name = capitalize(v); (v === "line" && $$.hasTypeOf(name) || $$.hasType(v)) && $$["updateTargetsFor" + name](targets.filter($$["is" + name + "Type"].bind($$))); }), $$.updateTargetsForSubchart && $$.updateTargetsForSubchart(targets)) : $$.hasArcType(targets) && (hasRadar ? $$.updateTargetsForRadar(targets.filter($$.isRadarType.bind($$))) : $$.updateTargetsForArc(targets.filter($$.isArcType.bind($$)))), ($$.hasType("bubble") || $$.hasType("scatter")) && $$.updateTargetForCircle && $$.updateTargetForCircle(), $$.showTargets(); } /** * Display targeted elements * @private */ , _proto.showTargets = function showTargets() { var $$ = this, config = $$.config, svg = $$.$el.svg; svg.selectAll("." + config_classes.target).filter(function (d) { return $$.isTargetToShow(d.id); }).transition().duration(config.transition_duration).style("opacity", "1"); }, _proto.getWithOption = function getWithOption(options) { var withOptions = { Y: !0, Subchart: !0, Transition: !0, EventRect: !0, Dimension: !0, TrimXDomain: !0, Transform: !1, UpdateXDomain: !1, UpdateOrgXDomain: !1, Legend: !1, UpdateXAxis: "UpdateXDomain", TransitionForExit: "Transition", TransitionForAxis: "Transition" }; return Object.keys(withOptions).forEach(function (key) { var defVal = withOptions[key]; isString(defVal) && (defVal = withOptions[defVal]), withOptions[key] = getOption(options, "with" + key, defVal); }), withOptions; }, _proto.initialOpacity = function initialOpacity(d) { var $$ = this, withoutFadeIn = $$.state.withoutFadeIn; return $$.getBaseValue(d) !== null && withoutFadeIn[d.id] ? "1" : "0"; }, _proto.bindResize = function bindResize() { var $$ = this, config = $$.config, state = $$.state, resizeFunction = generateResize(), list = []; list.push(function () { return callFn(config.onresize, $$, $$.api); }), config.resize_auto && list.push(function () { state.resizing = !0, $$.api.flush(!1); }), list.push(function () { callFn(config.onresized, $$, $$.api), state.resizing = !1; }), list.forEach(function (v) { return resizeFunction.add(v); }), $$.resizeFunction = resizeFunction, win.addEventListener("resize", $$.resizeFunction = resizeFunction); } /** * Call plugin hook * @param {string} phase The lifecycle phase * @param {Array} args Arguments * @private */ , _proto.callPluginHook = function callPluginHook(phase) { for (var _this = this, _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key]; this.config.plugins.forEach(function (v) { phase === "$beforeInit" && (v.$$ = _this, _this.api.plugins.push(v)), v[phase].apply(v, args); }); }, ChartInternal; }(); extend(ChartInternal.prototype, [// common convert, data_data, load, category, internals_class, internals_color, domain, interactions_interaction, format, internals_legend, redraw, scale, shape, size, internals_text, internals_title, internals_tooltip, transform, type]); ;// CONCATENATED MODULE: ./src/config/config.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Load configuration option * @param {object} config User's generation config value * @private */ function loadConfig(config) { var target, keys, read, thisConfig = this.config, find = function () { var key = keys.shift(); return key && target && isObjectType(target) && key in target ? (target = target[key], find()) : key ? undefined : target; }; Object.keys(thisConfig).forEach(function (key) { target = config, keys = key.split("_"), read = find(), isDefined(read) && (thisConfig[key] = read); }); } ;// CONCATENATED MODULE: ./src/Chart/api/chart.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var chart = ({ /** * Resize the chart. * @function resize * @instance * @memberof Chart * @param {object} size This argument should include width and height in pixels. * @param {number} [size.width] width value * @param {number} [size.height] height value * @example * // Resize to 640x480 * chart.resize({ * width: 640, * height: 480 * }); */ resize: function resize(size) { var $$ = this.internal, config = $$.config, state = $$.state; state.rendered && (config.size_width = size ? size.width : null, config.size_height = size ? size.height : null, state.resizing = !0, this.flush(!1, !0), $$.resizeFunction()); }, /** * Force to redraw. * - **NOTE:** When zoom/subchart is used, the zoomed state will be resetted. * @function flush * @instance * @memberof Chart * @param {boolean} [soft] For soft redraw. * @example * chart.flush(); * * // for soft redraw * chart.flush(true); */ flush: function flush(soft) { var $$ = this.internal, state = $$.state; state.rendered ? (state.resizing ? $$.brush && $$.brush.updateResize() : $$.axis && $$.axis.setOrient(), $$.scale.zoom = null, soft ? $$.redraw({ withTransform: !0, withUpdateXDomain: !0, withUpdateOrgXDomain: !0, withLegend: !0 }) : $$.updateAndRedraw({ withLegend: !0, withTransition: !1, withTransitionForTransform: !1 }), !state.resizing && $$.brush && ($$.brush.getSelection().call($$.brush.move), $$.unselectRect())) : $$.initToRender(!0); }, /** * Reset the chart object and remove element and events completely. * @function destroy * @instance * @memberof Chart * @returns {null} * @example * chart.destroy(); */ destroy: function destroy() { var _this = this, $$ = this.internal, _$$$$el = $$.$el, chart = _$$$$el.chart, svg = _$$$$el.svg; if (notEmpty($$)) // release prototype chains for (var _key in $$.callPluginHook("$willDestroy"), $$.charts.splice($$.charts.indexOf(this), 1), svg.select("*").interrupt(), $$.resizeFunction.clear(), win.removeEventListener("resize", $$.resizeFunction), chart.classed("bb", !1).html(""), Object.keys(this).forEach(function (key) { key === "internal" && Object.keys($$).forEach(function (k) { $$[k] = null; }), _this[key] = null, delete _this[key]; }), this) this[_key] = function () {}; return null; }, /** * Get or set single config option value. * @function config * @instance * @memberof Chart * @param {string} name The option key name. * @param {*} [value] The value accepted for indicated option. * @param {boolean} [redraw] Set to redraw with the new option changes. * - **NOTE:** Doesn't guarantee work in all circumstances. It can be applied for limited options only. * @returns {*} * @example * // Getter * chart.config("gauge.max"); * * // Setter * chart.config("gauge.max", 100); * * // Setter & redraw with the new option * chart.config("gauge.max", 100, true); */ config: function (name, value, redraw) { var res, $$ = this.internal, config = $$.config, key = name && name.replace(/\./g, "_"); return key in config && (isDefined(value) ? (config[key] = value, res = value, redraw && this.flush()) : res = config[key]), res; } }); ;// CONCATENATED MODULE: ./src/Chart/api/color.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var api_color = ({ /** * Get the color * @function color * @instance * @memberof Chart * @param {string} id id to get the color * @returns {string} * @example * chart.color("data1"); */ color: function color(id) { return this.internal.color(id); // more patterns } }); ;// CONCATENATED MODULE: ./src/Chart/api/data.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Get data loaded in the chart. * @function data * @instance * @memberof Chart * @param {string|Array} targetIds If this argument is given, this API returns the specified target data. If this argument is not given, all of data will be returned. * @returns {Array} Data objects * @example * // Get only data1 data * chart.data("data1"); * // --> [{id: "data1", id_org: "data1", values: Array(6)}, ...] * * // Get data1 and data2 data * chart.data(["data1", "data2"]); * * // Get all data * chart.data(); */ function api_data_data(targetIds) { var targets = this.internal.data.targets; if (!isUndefined(targetIds)) { var ids = isArray(targetIds) ? targetIds : [targetIds]; return targets.filter(function (t) { return ids.some(function (v) { return v === t.id; }); }); } return targets; } extend(api_data_data, { /** * Get data shown in the chart. * @function dataβ€€shown * @instance * @memberof Chart * @param {string|Array} targetIds If this argument is given, this API filters the data with specified target ids. If this argument is not given, all shown data will be returned. * @returns {Array} Data objects * @example * // Get shown data by filtering to include only data1 data * chart.data.shown("data1"); * // --> [{id: "data1", id_org: "data1", values: Array(6)}, ...] * * // Get shown data by filtering to include data1 and data2 data * chart.data.shown(["data1", "data2"]); * * // Get all shown data * chart.data.shown(); */ shown: function shown(targetIds) { return this.internal.filterTargetsToShow(this.data(targetIds)); }, /** * Get values of the data loaded in the chart. * @function dataβ€€values * @instance * @memberof Chart * @param {string|Array|null} targetIds This API returns the values of specified target. If this argument is not given, null will be retruned * @param {boolean} [flat=true] Get flatten values * @returns {Array} Data values * @example * // Get data1 values * chart.data.values("data1"); * // --> [10, 20, 30, 40] */ values: function (targetIds, flat) { flat === void 0 && (flat = !0); var values = null; if (targetIds) { var targets = this.data(targetIds); targets && isArray(targets) && (values = [], targets.forEach(function (v) { var dataValue = v.values.map(function (d) { return d.value; }); flat ? values = values.concat(dataValue) : values.push(dataValue); })); } return values; }, /** * Get and set names of the data loaded in the chart. * @function dataβ€€names * @instance * @memberof Chart * @param {object} names If this argument is given, the names of data will be updated. If not given, the current names will be returned. The format of this argument is the same as * @returns {object} Corresponding names according its key value, if specified names values. * @example * // Get current names * chart.data.names(); * // --> {data1: "test1", data2: "test2"} * * // Update names * chart.data.names({ * data1: "New Name 1", * data2: "New Name 2" *}); */ names: function names(_names) { var $$ = this.internal; return $$.updateDataAttributes("names", _names); }, /** * Get and set colors of the data loaded in the chart. * @function dataβ€€colors * @instance * @memberof Chart * @param {object} colors If this argument is given, the colors of data will be updated. If not given, the current colors will be returned. The format of this argument is the same as [data.colors](./Options.html#.data%25E2%2580%25A4colors). * @returns {object} Corresponding data color value according its key value. * @example * // Get current colors * chart.data.colors(); * // --> {data1: "#00c73c", data2: "#fa7171"} * * // Update colors * chart.data.colors({ * data1: "#FFFFFF", * data2: "#000000" * }); */ colors: function colors(_colors) { return this.internal.updateDataAttributes("colors", _colors); }, /** * Get and set axes of the data loaded in the chart. * - **NOTE:** If all data is related to one of the axes, the domain of axis without related data will be replaced by the domain from the axis with related data * @function dataβ€€axes * @instance * @memberof Chart * @param {object} axes If this argument is given, the axes of data will be updated. If not given, the current axes will be returned. The format of this argument is the same as * @returns {object} Corresponding axes value for data, if specified axes value. * @example * // Get current axes * chart.data.axes(); * // --> {data1: "y"} * * // Update axes * chart.data.axes({ * data1: "y", * data2: "y2" * }); */ axes: function axes(_axes) { return this.internal.updateDataAttributes("axes", _axes); }, /** * Get the minimum data value bound to the chart * @function dataβ€€min * @instance * @memberof Chart * @returns {Array} Data objects * @example * // Get current axes * chart.data.min(); * // --> [{x: 0, value: 30, id: "data1", index: 0}, ...] */ min: function min() { return this.internal.getMinMaxData().min; }, /** * Get the maximum data value bound to the chart * @function dataβ€€max * @instance * @memberof Chart * @returns {Array} Data objects * @example * // Get current axes * chart.data.max(); * // --> [{x: 3, value: 400, id: "data1", index: 3}, ...] */ max: function max() { return this.internal.getMinMaxData().max; } }); /* harmony default export */ var api_data = ({ data: api_data_data }); ;// CONCATENATED MODULE: ./src/Chart/api/export.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Encode to base64 * @param {string} str string to be encoded * @returns {string} * @private * @see https://developer.mozilla.org/ko/docs/Web/API/WindowBase64/Base64_encoding_and_decoding */ var b64EncodeUnicode = function (str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p) { return String.fromCharCode(+("0x" + p)); })); }; /** * Convert svg node to data url * @param {HTMLElement} node target node * @param {object} option object containing {width, height, preserveAspectRatio} * @param {object} orgSize object containing {width, height} * @returns {string} * @private */ function nodeToSvgDataUrl(node, option, orgSize) { var _ref = option || orgSize, width = _ref.width, height = _ref.height, serializer = new XMLSerializer(), clone = node.cloneNode(!0), cssText = getCssRules(toArray(browser_doc.styleSheets)).filter(function (r) { return r.cssText; }).map(function (r) { return r.cssText; }); clone.setAttribute("xmlns", external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.namespaces.xhtml); var nodeXml = serializer.serializeToString(clone), style = browser_doc.createElement("style"); // escape css for XML style.appendChild(browser_doc.createTextNode(cssText.join("\n"))); var styleXml = serializer.serializeToString(style), dataStr = ("<svg xmlns=\"" + external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.namespaces.svg + "\" width=\"" + width + "\" height=\"" + height + "\" \n\t\tviewBox=\"0 0 " + orgSize.width + " " + orgSize.height + "\" \n\t\tpreserveAspectRatio=\"" + (option && option.preserveAspectRatio === !1 ? "none" : "xMinYMid meet") + "\">\n\t\t\t<foreignObject width=\"100%\" height=\"100%\">\n\t\t\t\t" + styleXml + "\n\t\t\t\t" + nodeXml.replace(/(url\()[^#]+/g, "$1") + "\n\t\t\t</foreignObject></svg>").replace("/\n/g", "%0A"); // foreignObject not supported in IE11 and below // https://msdn.microsoft.com/en-us/library/hh834675(v=vs.85).aspx return "data:image/svg+xml;base64," + b64EncodeUnicode(dataStr); } /* harmony default export */ var api_export = ({ /** * Export chart as an image. * - **NOTE:** * - IE11 and below not work properly due to the lack of the feature(<a href="https://msdn.microsoft.com/en-us/library/hh834675(v=vs.85).aspx">foreignObject</a>) support * - The basic CSS file(ex. billboard.css) should be at same domain as API call context to get correct styled export image. * @function export * @instance * @memberof Chart * @param {object} option Export option * @param {string} [option.mimeType="image/png"] The desired output image format. (ex. 'image/png' for png, 'image/jpeg' for jpeg format) * @param {number} [option.width={currentWidth}] width * @param {number} [option.height={currentHeigth}] height * @param {boolean} [option.preserveAspectRatio=true] Preserve aspect ratio on given size * @param {Function} [callback] The callback to be invoked when export is ready. * @returns {string} dataURI * @example * chart.export(); * // --> "data:image/svg+xml;base64,PHN..." * * // Initialize the download automatically * chart.export({mimeType: "image/png"}, dataUrl => { * const link = document.createElement("a"); * * link.download = `${Date.now()}.png`; * link.href = dataUrl; * link.innerHTML = "Download chart as image"; * * document.body.appendChild(link); * }); * * // Resize the exported image * chart.export( * { * width: 800, * height: 600, * preserveAspectRatio: false, * mimeType: "image/png" * }, * dataUrl => { ... } * ); */ export: function _export(option, callback) { var _this = this, $$ = this.internal, state = $$.state, chart = $$.$el.chart, _state$current = state.current, width = _state$current.width, height = _state$current.height, opt = mergeObj({ width: width, height: height, preserveAspectRatio: !0, mimeType: "image/png" }, option), svgDataUrl = nodeToSvgDataUrl(chart.node(), opt, { width: width, height: height }); if (callback && isFunction(callback)) { var img = new Image(); img.crossOrigin = "Anonymous", img.onload = function () { var canvas = browser_doc.createElement("canvas"), ctx = canvas.getContext("2d"); canvas.width = opt.width || width, canvas.height = opt.height || height, ctx.drawImage(img, 0, 0), callback.bind(_this)(canvas.toDataURL(opt.mimeType)); }, img.src = svgDataUrl; } return svgDataUrl; } }); ;// CONCATENATED MODULE: ./src/Chart/api/focus.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var api_focus = ({ /** * This API highlights specified targets and fade out the others.<br><br> * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be highlighted. * @function focus * @instance * @memberof Chart * @param {string|Array} targetIdsValue Target ids to be highlighted. * @example * // data1 will be highlighted and the others will be faded out * chart.focus("data1"); * * // data1 and data2 will be highlighted and the others will be faded out * chart.focus(["data1", "data2"]); * * // all targets will be highlighted * chart.focus(); */ focus: function focus(targetIdsValue) { var $$ = this.internal, state = $$.state, targetIds = $$.mapToTargetIds(targetIdsValue), candidates = $$.$el.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))); this.revert(), this.defocus(), candidates.classed(config_classes.focused, !0).classed(config_classes.defocused, !1), $$.hasArcType() && !state.hasRadar && ($$.expandArc(targetIds), $$.hasType("gauge") && $$.markOverlapped(targetIdsValue, $$, "." + config_classes.gaugeValue)), $$.toggleFocusLegend(targetIds, !0), state.focusedTargetIds = targetIds, state.defocusedTargetIds = state.defocusedTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); }, /** * This API fades out specified targets and reverts the others.<br><br> * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be faded out. * @function defocus * @instance * @memberof Chart * @param {string|Array} targetIdsValue Target ids to be faded out. * @example * // data1 will be faded out and the others will be reverted. * chart.defocus("data1"); * * // data1 and data2 will be faded out and the others will be reverted. * chart.defocus(["data1", "data2"]); * * // all targets will be faded out. * chart.defocus(); */ defocus: function defocus(targetIdsValue) { var $$ = this.internal, state = $$.state, targetIds = $$.mapToTargetIds(targetIdsValue), candidates = $$.$el.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))); candidates.classed(config_classes.focused, !1).classed(config_classes.defocused, !0), $$.hasArcType() && ($$.unexpandArc(targetIds), $$.hasType("gauge") && $$.undoMarkOverlapped($$, "." + config_classes.gaugeValue)), $$.toggleFocusLegend(targetIds, !1), state.focusedTargetIds = state.focusedTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; }), state.defocusedTargetIds = targetIds; }, /** * This API reverts specified targets.<br><br> * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be reverted. * @function revert * @instance * @memberof Chart * @param {string|Array} targetIdsValue Target ids to be reverted * @example * // data1 will be reverted. * chart.revert("data1"); * * // data1 and data2 will be reverted. * chart.revert(["data1", "data2"]); * * // all targets will be reverted. * chart.revert(); */ revert: function revert(targetIdsValue) { var $$ = this.internal, config = $$.config, state = $$.state, $el = $$.$el, targetIds = $$.mapToTargetIds(targetIdsValue), candidates = $el.svg.selectAll($$.selectorTargets(targetIds)); // should be for all targets candidates.classed(config_classes.focused, !1).classed(config_classes.defocused, !1), $$.hasArcType() && $$.unexpandArc(targetIds), config.legend_show && ($$.showLegend(targetIds.filter($$.isLegendToShow.bind($$))), $el.legend.selectAll($$.selectorLegends(targetIds)).filter(function () { return (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).classed(config_classes.legendItemFocused); }).classed(config_classes.legendItemFocused, !1)), state.focusedTargetIds = [], state.defocusedTargetIds = []; } }); ;// CONCATENATED MODULE: ./src/Chart/api/legend.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Define legend * @ignore */ var legend_legend = { /** * Show legend for each target. * @function legendβ€€show * @instance * @memberof Chart * @param {string|Array} targetIds * - If targetIds is given, specified target's legend will be shown. * - If only one target is the candidate, String can be passed. * - If no argument is given, all of target's legend will be shown. * @example * // Show legend for data1. * chart.legend.show("data1"); * * // Show legend for data1 and data2. * chart.legend.show(["data1", "data2"]); * * // Show all legend. * chart.legend.show(); */ show: function show(targetIds) { var $$ = this.internal; $$.showLegend($$.mapToTargetIds(targetIds)), $$.updateAndRedraw({ withLegend: !0 }); }, /** * Hide legend for each target. * @function legendβ€€hide * @instance * @memberof Chart * @param {string|Array} targetIds * - If targetIds is given, specified target's legend will be hidden. * - If only one target is the candidate, String can be passed. * - If no argument is given, all of target's legend will be hidden. * @example * // Hide legend for data1. * chart.legend.hide("data1"); * * // Hide legend for data1 and data2. * chart.legend.hide(["data1", "data2"]); * * // Hide all legend. * chart.legend.hide(); */ hide: function hide(targetIds) { var $$ = this.internal; $$.hideLegend($$.mapToTargetIds(targetIds)), $$.updateAndRedraw({ withLegend: !0 }); } }; /* harmony default export */ var api_legend = ({ legend: legend_legend }); ;// CONCATENATED MODULE: ./src/Chart/api/load.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var api_load = ({ /** * Load data to the chart.<br><br> * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be toggles. * - <b>Note:</b> * - unload should be used if some data needs to be unloaded simultaneously. * If you call unload API soon after/before load instead of unload param, chart will not be rendered properly because of cancel of animation.<br> * - done will be called after data loaded, but it's not after rendering. * It's because rendering will finish after some transition and there is some time lag between loading and rendering * @function load * @instance * @memberof Chart * @param {object} args The object can consist with following members:<br> * * | Key | Description | * | --- | --- | * | - url<br>- json<br>- rows<br>- columns | The data will be loaded. If data that has the same target id is given, the chart will be updated. Otherwise, new target will be added | * | data | Data objects to be loaded. Checkout the example. | * | names | Same as data.names() | * | xs | Same as data.xs option | * | classes | The classes specified by data.classes will be updated. classes must be Object that has target id as keys. | * | categories | The categories specified by axis.x.categories or data.x will be updated. categories must be Array. | * | axes | The axes specified by data.axes will be updated. axes must be Object that has target id as keys. | * | colors | The colors specified by data.colors will be updated. colors must be Object that has target id as keys. | * | headers | Set request header if loading via `data.url`.<br>@see [dataβ€€headers](Options.html#.data%25E2%2580%25A4headers) | * | keys | Choose which JSON objects keys correspond to desired data.<br>**NOTE:** Only for JSON object given as array.<br>@see [dataβ€€keys](Options.html#.data%25E2%2580%25A4keys) | * | mimeType | Set 'json' if loading JSON via url.<br>@see [dataβ€€mimeType](Options.html#.data%25E2%2580%25A4mimeType) | * | - type<br>- types | The type of targets will be updated. type must be String and types must be Object. | * | unload | Specify the data will be unloaded before loading new data. If true given, all of data will be unloaded. If target ids given as String or Array, specified targets will be unloaded. If absent or false given, unload will not occur. | * | done | The specified function will be called after data loaded.| * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.DataFromURL) * @example * // Load data1 and unload data2 and data3 * chart.load({ * columns: [ * ["data1", 100, 200, 150, ...], * ... * ], * unload: ["data2", "data3"], * url: "...", * done: function() { ... } * }); * @example * // myAPI.json * // { * // "data1": [220, 240, 270, 250, 280], * // "data2": [180, 150, 300, 70, 120] * // } * * chart.load({ * url: './data/myAPI.json', * mimeType: "json", * * // set request header if is needed * headers: { * "Content-Type": "text/json" * } * }); * @example * chart.load({ * data: [ * // equivalent as: columns: [["data1", 30, 200, 100]] * {"data1": 30}, {"data1": 200}, {"data1": 100} * * // or * // equivalent as: columns: [["data1", 10, 20], ["data2", 13, 30]] * // {"data1": 10, "data2": 13}, {"data1": 20, "data2": 30}} * ] * }); * @example * chart.load({ * json: [ * {name: "www.site1.com", upload: 800, download: 500, total: 400}, * ], * keys: { * x: "name", * value: ["upload", "download"] * } * }); */ load: function load(args) { var $$ = this.internal, config = $$.config; // update xs if specified // update names if exists // update classes if exists // update axes if exists // update colors if exists args.xs && $$.addXs(args.xs), "names" in args && this.data.names(args.names), "classes" in args && Object.keys(args.classes).forEach(function (id) { config.data_classes[id] = args.classes[id]; }), "categories" in args && $$.axis.isCategorized() && (config.axis_x_categories = args.categories), "axes" in args && Object.keys(args.axes).forEach(function (id) { config.data_axes[id] = args.axes[id]; }), "colors" in args && Object.keys(args.colors).forEach(function (id) { config.data_colors[id] = args.colors[id]; }), "unload" in args && args.unload !== !1 ? $$.unload($$.mapToTargetIds(args.unload === !0 ? null : args.unload), function () { return $$.loadFromArgs(args); }) : $$.loadFromArgs(args); }, /** * Unload data to the chart.<br><br> * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be toggles. * - <b>Note:</b> * If you call load API soon after/before unload, unload param of load should be used. Otherwise chart will not be rendered properly because of cancel of animation.<br> * `done` will be called after data loaded, but it's not after rendering. It's because rendering will finish after some transition and there is some time lag between loading and rendering. * @function unload * @instance * @memberof Chart * @param {object} argsValue * | key | Type | Description | * | --- | --- | --- | * | ids | String &vert; Array | Target id data to be unloaded. If not given, all data will be unloaded. | * | done | Fuction | Callback after data is unloaded. | * @example * // Unload data2 and data3 * chart.unload({ * ids: ["data2", "data3"], * done: function() { * // called after the unloaded * } * }); */ unload: function unload(argsValue) { var _this = this, $$ = this.internal, args = argsValue || {}; isArray(args) ? args = { ids: args } : isString(args) && (args = { ids: [args] }); var ids = $$.mapToTargetIds(args.ids); $$.unload(ids, function () { $$.redraw({ withUpdateOrgXDomain: !0, withUpdateXDomain: !0, withLegend: !0 }), $$.cache.remove(ids), args.done && args.done.call(_this); }); } }); ;// CONCATENATED MODULE: ./src/Chart/api/show.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Show/Hide data series * @param {boolean} show Show or hide * @param {Array} targetIdsValue Target id values * @param {object} options Options * @private */ function showHide(show, targetIdsValue, options) { var $$ = this.internal, targetIds = $$.mapToTargetIds(targetIdsValue); $$.state.toggling = !0, $$[(show ? "remove" : "add") + "HiddenTargetIds"](targetIds); var targets = $$.$el.svg.selectAll($$.selectorTargets(targetIds)), opacity = show ? "1" : "0"; show && targets.style("display", null), targets.transition().style("opacity", opacity, "important").call(endall, function () { // https://github.com/naver/billboard.js/issues/1758 show || targets.style("display", "none"), targets.style("opacity", opacity); }), options.withLegend && $$[(show ? "show" : "hide") + "Legend"](targetIds), $$.redraw({ withUpdateOrgXDomain: !0, withUpdateXDomain: !0, withLegend: !0 }), $$.state.toggling = !1; } /* harmony default export */ var show = ({ /** * Show data series on chart * @function show * @instance * @memberof Chart * @param {string|Array} [targetIdsValue] The target id value. * @param {object} [options] The object can consist with following members:<br> * * | Key | Type | default | Description | * | --- | --- | --- | --- | * | withLegend | boolean | false | whether or not display legend | * * @example * // show 'data1' * chart.show("data1"); * * // show 'data1' and 'data3' * chart.show(["data1", "data3"]); */ show: function show(targetIdsValue, options) { options === void 0 && (options = {}), showHide.call(this, !0, targetIdsValue, options); }, /** * Hide data series from chart * @function hide * @instance * @memberof Chart * @param {string|Array} [targetIdsValue] The target id value. * @param {object} [options] The object can consist with following members:<br> * * | Key | Type | default | Description | * | --- | --- | --- | --- | * | withLegend | boolean | false | whether or not display legend | * * @example * // hide 'data1' * chart.hide("data1"); * * // hide 'data1' and 'data3' * chart.hide(["data1", "data3"]); */ hide: function hide(targetIdsValue, options) { options === void 0 && (options = {}), showHide.call(this, !1, targetIdsValue, options); }, /** * Toggle data series on chart. When target data is hidden, it will show. If is shown, it will hide in vice versa. * @function toggle * @instance * @memberof Chart * @param {string|Array} [targetIds] The target id value. * @param {object} [options] The object can consist with following members:<br> * * | Key | Type | default | Description | * | --- | --- | --- | --- | * | withLegend | boolean | false | whether or not display legend | * * @example * // toggle 'data1' * chart.toggle("data1"); * * // toggle 'data1' and 'data3' * chart.toggle(["data1", "data3"]); */ toggle: function toggle(targetIds, options) { var _this = this; options === void 0 && (options = {}); var $$ = this.internal, targets = { show: [], hide: [] }; // sort show & hide target ids // perform show & hide task separately // https://github.com/naver/billboard.js/issues/454 $$.mapToTargetIds(targetIds).forEach(function (id) { return targets[$$.isTargetToShow(id) ? "hide" : "show"].push(id); }), targets.show.length && this.show(targets.show, options), targets.hide.length && setTimeout(function () { return _this.hide(targets.hide, options); }, 0); } }); ;// CONCATENATED MODULE: ./src/Chart/api/tooltip.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Define tooltip * @ignore */ var tooltip_tooltip = { /** * Show tooltip * @function tooltipβ€€show * @instance * @memberof Chart * @param {object} args The object can consist with following members:<br> * * | Key | Type | Description | * | --- | --- | --- | * | index | Number | Determine focus by index | * | x | Number &vert; Date | Determine focus by x Axis index | * | mouse | Array | Determine x and y coordinate value relative the targeted '.bb-event-rect' x Axis.<br>It should be used along with `data`, `index` or `x` value. The default value is set as `[0,0]` | * | data | Object | When [data.xs](Options.html#.data%25E2%2580%25A4xs) option is used or [tooltip.grouped](Options.html#.tooltip) set to 'false', `should be used giving this param`.<br><br>**Key:**<br>- x {number &verbar; Date}: x Axis value<br>- index {number}: x Axis index (useless for data.xs)<br>- id {string}: data id<br>- value {number}: The corresponding value for tooltip. | * * @example * // show the 2nd x Axis coordinate tooltip * // for Arc(gauge, donut & pie) and radar type, approch showing tooltip by using "index" number. * chart.tooltip.show({ * index: 1 * }); * * // show tooltip for the 3rd x Axis in x:50 and y:100 coordinate of '.bb-event-rect' of the x Axis. * chart.tooltip.show({ * x: 2, * mouse: [50, 100] * }); * * // show tooltip for timeseries x axis * chart.tooltip.show({ * x: new Date("2018-01-02 00:00") * }); * * // when data.xs is used * chart.tooltip.show({ * data: { * x: 3, // x Axis value * id: "data1", // data id * value: 500 // data value * } * }); * * // when data.xs isn't used, but tooltip.grouped=false is set * chart.tooltip.show({ * data: { * index: 3, // or 'x' key value * id: "data1", // data id * value: 500 // data value * } * }); */ show: function show(args) { var index, mouse, $$ = this.internal, config = $$.config, inputType = $$.state.inputType; // determine focus data if (args.mouse && (mouse = args.mouse), args.data) { var data = args.data, y = $$.getYScaleById(data.id)(data.value); $$.isMultipleX() ? mouse = [$$.scale.x(data.x), y] : (!config.tooltip_grouped && (mouse = [0, y]), index = isValue(data.index) ? data.index : $$.getIndexByX(data.x)); } else isDefined(args.x) ? index = $$.getIndexByX(args.x) : isDefined(args.index) && (index = args.index); (inputType === "mouse" ? ["mouseover", "mousemove"] : ["touchstart"]).forEach(function (eventName) { $$.dispatchEvent(eventName, index, mouse); }); }, /** * Hide tooltip * @function tooltipβ€€hide * @instance * @memberof Chart */ hide: function hide() { var $$ = this.internal, inputType = $$.state.inputType, tooltip = $$.$el.tooltip, data = tooltip && tooltip.datum(); if (data) { var index = JSON.parse(data.current)[0].index; // make to finalize, possible pending event flow set from '.tooltip.show()' call (inputType === "mouse" ? ["mouseout"] : ["touchend"]).forEach(function (eventName) { $$.dispatchEvent(eventName, index); }); } // reset last touch point index inputType === "touch" && $$.callOverOutForTouch(), $$.hideTooltip(!0), $$.hideGridFocus(), $$.unexpandCircles && $$.unexpandCircles(), $$.expandBarTypeShapes(!1); } }; /* harmony default export */ var api_tooltip = ({ tooltip: tooltip_tooltip }); ;// CONCATENATED MODULE: ./src/Chart/Chart.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Main chart class. * - Note: Instantiated via `bb.generate()`. * @class Chart * @example * var chart = bb.generate({ * data: { * columns: [ * ["x", "2015-11-02", "2015-12-01", "2016-01-01", "2016-02-01", "2016-03-01"], * ["count1", 11, 8, 7, 6, 5 ], * ["count2", 9, 3, 6, 2, 8 ] * ]} * } * @see {@link bb.generate} for the initialization. */ /** * Access instance's primary node elements * @member {object} $ * @property {object} $ Access instance's primary node elements * @property {d3.selection} $.chart Wrapper element * @property {d3.selection} $.svg Main svg element * @property {d3.selection} $.defs Definition element * @property {d3.selection} $.main Main grouping element * @property {d3.selection} $.tooltip Tooltip element * @property {d3.selection} $.legend Legend element * @property {d3.selection} $.title Title element * @property {d3.selection} $.grid Grid element * @property {d3.selection} $.arc Arc element * @property {d3.selection} $.circles Data point circle elements * @property {object} $.bar Bar element object * @property {d3.selection} $.bar.bars Bar elements * @property {d3.selection} $.candlestick Candlestick elements * @property {object} $.line Line element object * @property {d3.selection} $.line.lines Line elements * @property {d3.selection} $.line.areas Areas elements * @property {object} $.text Text element object * @property {d3.selection} $.text.texts Data label text elements * @memberof Chart * @example * var chart = bb.generate({ ... }); * * chart.$.chart; // wrapper element * chart.$.line.circles; // all data point circle elements */ /** * Plugin instance array * @member {Array} plugins * @memberof Chart * @example * var chart = bb.generate({ * ... * plugins: [ * new bb.plugin.stanford({ ... }), * new PluginA() * ] * }); * * chart.plugins; // [Stanford, PluginA] - instance array */ var Chart = function Chart(options) { this.plugins = [], this.internal = void 0; var $$ = new ChartInternal(this); // bind to namespaced APIs this.internal = $$, function bindThis(fn, target, argThis) { Object.keys(fn).forEach(function (key) { var isFunc = isFunction(fn[key]), isChild = target !== argThis, hasChild = Object.keys(fn[key]).length > 0; isFunc && (!isChild && hasChild || isChild) ? target[key] = fn[key].bind(argThis) : !isFunc && (target[key] = {}), hasChild && bindThis(fn[key], target[key], argThis); }); }(Chart.prototype, this, this), loadConfig.call($$, options), $$.beforeInit(), $$.init(); }; // extend common APIs as part of Chart class extend(Chart.prototype, [chart, api_color, api_data, api_export, api_focus, api_legend, api_load, show, api_tooltip]); ;// CONCATENATED MODULE: ./src/Chart/api/axis.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Set the min/max value * @param {Chart} $$ Chart instance * @param {string} type Set type 'min' or 'max' * @param {object} value Value to be set * @private */ function setMinMax($$, type, value) { var config = $$.config, axisY = "axis_y_" + type, axisY2 = "axis_y2_" + type; isDefined(value) && (isObjectType(value) ? (isValue(value.x) && (config["axis_x_" + type] = value.x), isValue(value.y) && (config[axisY] = value.y), isValue(value.y2) && (config[axisY2] = value.y2)) : (config[axisY] = value, config[axisY2] = value), $$.redraw({ withUpdateOrgXDomain: !0, withUpdateXDomain: !0 })); } /** * Get the min/max value * @param {Chart} $$ Chart instance * @param {string} type Set type 'min' or 'max' * @returns {{x, y, y2}} * @private */ function axis_getMinMax($$, type) { var config = $$.config; return { x: config["axis_x_" + type], y: config["axis_y_" + type], y2: config["axis_y2_" + type] }; } /** * Define axis * @ignore */ var axis = { /** * Get and set axis labels. * @function axisβ€€labels * @instance * @memberof Chart * @param {object} labels specified axis' label to be updated. * @param {string} [labels.x] x Axis string * @param {string} [labels.y] y Axis string * @param {string} [labels.y2] y2 Axis string * @returns {object|undefined} axis labels text object * @example * // Update axis' label * chart.axis.labels({ * x: "New X Axis Label", * y: "New Y Axis Label", * y2: "New Y2 Axis Label" * }); * * chart.axis.labels(); * // --> { * // x: "New X Axis Label", * // y: "New Y Axis Label", * // y2: "New Y2 Axis Label" * // } */ labels: function labels(_labels) { var labelText, $$ = this.internal; return _labels && (Object.keys(_labels).forEach(function (axisId) { $$.axis.setLabelText(axisId, _labels[axisId]); }), $$.axis.updateLabels()), ["x", "y", "y2"].forEach(function (v) { var text = $$.axis.getLabelText(v); text && (!labelText && (labelText = {}), labelText[v] = text); }), labelText; }, /** * Get and set axis min value. * @function axisβ€€min * @instance * @memberof Chart * @param {object} min If min is given, specified axis' min value will be updated.<br> * If no argument is given, the min values set on generating option for each axis will be returned. * If not set any min values on generation, it will return `undefined`. * @returns {object|undefined} * @example * // Update axis' min * chart.axis.min({ * x: -10, * y: 1000, * y2: 100 * }); */ min: function min(_min) { var $$ = this.internal; return isValue(_min) ? setMinMax($$, "min", _min) : axis_getMinMax($$, "min"); }, /** * Get and set axis max value. * @function axisβ€€max * @instance * @memberof Chart * @param {object} max If max is given, specified axis' max value will be updated.<br> * If no argument is given, the max values set on generating option for each axis will be returned. * If not set any max values on generation, it will return `undefined`. * @returns {object|undefined} * @example * // Update axis' label * chart.axis.max({ * x: 100, * y: 1000, * y2: 10000 * }); */ max: function max(_max) { var $$ = this.internal; return arguments.length ? setMinMax($$, "max", _max) : axis_getMinMax($$, "max"); }, /** * Get and set axis min and max value. * @function axisβ€€range * @instance * @memberof Chart * @param {object} range If range is given, specified axis' min and max value will be updated. If no argument is given, the current min and max values for each axis will be returned. * @returns {object|undefined} * @example * // Update axis' label * chart.axis.range({ * min: { * x: -10, * y: -1000, * y2: -10000 * }, * max: { * x: 100, * y: 1000, * y2: 10000 * }, * }); */ range: function range(_range) { var axis = this.axis; if (arguments.length) isDefined(_range.max) && axis.max(_range.max), isDefined(_range.min) && axis.min(_range.min);else return { max: axis.max(), min: axis.min() }; return undefined; } }; /* harmony default export */ var api_axis = ({ axis: axis }); ;// CONCATENATED MODULE: ./src/Chart/api/category.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var api_category = ({ /** * Set specified category name on category axis. * @function category * @instance * @memberof Chart * @param {number} i index of category to be changed * @param {string} category category value to be changed * @returns {string} * @example * chart.category(2, "Category 3"); */ category: function category(i, _category) { var $$ = this.internal, config = $$.config; return arguments.length > 1 && (config.axis_x_categories[i] = _category, $$.redraw()), config.axis_x_categories[i]; }, /** * Set category names on category axis. * @function categories * @instance * @memberof Chart * @param {Array} categories This must be an array that includes category names in string. If category names are included in the date by data.x option, this is not required. * @returns {Array} * @example * chart.categories([ * "Category 1", "Category 2", ... * ]); */ categories: function categories(_categories) { var $$ = this.internal, config = $$.config; return arguments.length ? (config.axis_x_categories = _categories, $$.redraw(), config.axis_x_categories) : config.axis_x_categories; } }); ;// CONCATENATED MODULE: ./src/Chart/api/grid.x.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Update x grid lines. * @function xgrids * @instance * @memberof Chart * @param {Array} grids X grid lines will be replaced with this argument. The format of this argument is the same as grid.x.lines. * @returns {object} * @example * // Show 2 x grid lines * chart.xgrids([ * {value: 1, text: "Label 1"}, * {value: 4, text: "Label 4"} * ]); * // --> Returns: [{value: 1, text: "Label 1"}, {value: 4, text: "Label 4"}] */ function xgrids(grids) { var $$ = this.internal, config = $$.config; return grids ? (config.grid_x_lines = grids, $$.redrawWithoutRescale(), config.grid_x_lines) : config.grid_x_lines; } extend(xgrids, { /** * Add x grid lines.<br> * This API adds new x grid lines instead of replacing like xgrids. * @function xgridsβ€€add * @instance * @memberof Chart * @param {Array|object} grids New x grid lines will be added. The format of this argument is the same as grid.x.lines and it's possible to give an Object if only one line will be added. * @returns {object} * @example * // Add a new x grid line * chart.xgrids.add( * {value: 4, text: "Label 4"} * ); * * // Add new x grid lines * chart.xgrids.add([ * {value: 2, text: "Label 2"}, * {value: 4, text: "Label 4"} * ]); */ add: function add(grids) { return this.xgrids(this.internal.config.grid_x_lines.concat(grids || [])); }, /** * Remove x grid lines.<br> * This API removes x grid lines. * @function xgridsβ€€remove * @instance * @memberof Chart * @param {object} params This argument should include value or class. If value is given, the x grid lines that have specified x value will be removed. If class is given, the x grid lines that have specified class will be removed. If args is not given, all of x grid lines will be removed. * @example * // x grid line on x = 2 will be removed * chart.xgrids.remove({value: 2}); * * // x grid lines that have 'grid-A' will be removed * chart.xgrids.remove({ * class: "grid-A" * }); * * // all of x grid lines will be removed * chart.xgrids.remove(); */ remove: function remove(params) { // TODO: multiple this.internal.removeGridLines(params, !0); } }); /* harmony default export */ var grid_x = ({ xgrids: xgrids }); ;// CONCATENATED MODULE: ./src/Chart/api/grid.y.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Update y grid lines. * @function ygrids * @instance * @memberof Chart * @param {Array} grids Y grid lines will be replaced with this argument. The format of this argument is the same as grid.y.lines. * @returns {object} * @example * // Show 2 y grid lines * chart.ygrids([ * {value: 100, text: "Label 1"}, * {value: 400, text: "Label 4"} * ]); * // --> Returns: [{value: 100, text: "Label 1"}, {value: 400, text: "Label 4"}] */ function ygrids(grids) { var $$ = this.internal, config = $$.config; return grids ? (config.grid_y_lines = grids, $$.redrawWithoutRescale(), config.grid_y_lines) : config.grid_y_lines; } extend(ygrids, { /** * Add y grid lines.<br> * This API adds new y grid lines instead of replacing like ygrids. * @function ygridsβ€€add * @instance * @memberof Chart * @param {Array|object} grids New y grid lines will be added. The format of this argument is the same as grid.y.lines and it's possible to give an Object if only one line will be added. * @returns {object} * @example * // Add a new x grid line * chart.ygrids.add( * {value: 400, text: "Label 4"} * ); * * // Add new x grid lines * chart.ygrids.add([ * {value: 200, text: "Label 2"}, * {value: 400, text: "Label 4"} * ]); */ add: function add(grids) { return this.ygrids(this.internal.config.grid_y_lines.concat(grids || [])); }, /** * Remove y grid lines.<br> * This API removes x grid lines. * @function ygridsβ€€remove * @instance * @memberof Chart * @param {object} params This argument should include value or class. If value is given, the y grid lines that have specified y value will be removed. If class is given, the y grid lines that have specified class will be removed. If args is not given, all of y grid lines will be removed. * @param {number} [params.value] target value * @param {string} [params.class] target class * @example * // y grid line on y = 200 will be removed * chart.ygrids.remove({value: 200}); * * // y grid lines that have 'grid-A' will be removed * chart.ygrids.remove({ * class: "grid-A" * }); * * // all of y grid lines will be removed * chart.ygrids.remove(); */ remove: function remove(params) { // TODO: multiple this.internal.removeGridLines(params, !1); } }); /* harmony default export */ var grid_y = ({ ygrids: ygrids }); ;// CONCATENATED MODULE: ./src/Chart/api/group.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var group = ({ /** * Update groups for the targets. * @function groups * @instance * @memberof Chart * @param {Array} groups This argument needs to be an Array that includes one or more Array that includes target ids to be grouped. * @returns {Array} Grouped data names array * @example * // data1 and data2 will be a new group. * chart.groups([ * ["data1", "data2"] * ]); */ groups: function groups(_groups) { var $$ = this.internal, config = $$.config; return isUndefined(_groups) ? config.data_groups : (config.data_groups = _groups, $$.redraw(), config.data_groups); } }); ;// CONCATENATED MODULE: ./src/Chart/api/regions.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Update regions. * @function regions * @instance * @memberof Chart * @param {Array} regions Regions will be replaced with this argument. The format of this argument is the same as regions. * @returns {Array} regions * @example * // Show 2 regions * chart.regions([ * {axis: "x", start: 5, class: "regionX"}, * {axis: "y", end: 50, class: "regionY"} * ]); */ function regions(regions) { var $$ = this.internal, config = $$.config; return regions ? (config.regions = regions, $$.redrawWithoutRescale(), regions) : config.regions; } extend(regions, { /** * Add new region.<br><br> * This API adds new region instead of replacing like regions. * @function regionsβ€€add * @instance * @memberof Chart * @param {Array|object} regions New region will be added. The format of this argument is the same as regions and it's possible to give an Object if only one region will be added. * @returns {Array} regions * @example * // Add a new region * chart.regions.add( * {axis: "x", start: 5, class: "regionX"} * ); * * // Add new regions * chart.regions.add([ * {axis: "x", start: 5, class: "regionX"}, * {axis: "y", end: 50, class: "regionY"} *]); */ add: function add(regions) { var $$ = this.internal, config = $$.config; return regions ? (config.regions = config.regions.concat(regions), $$.redrawWithoutRescale(), config.regions) : config.regions; }, /** * Remove regions.<br><br> * This API removes regions. * @function regionsβ€€remove * @instance * @memberof Chart * @param {object} optionsValue This argument should include classes. If classes is given, the regions that have one of the specified classes will be removed. If args is not given, all of regions will be removed. * @returns {Array} regions Removed regions * @example * // regions that have 'region-A' or 'region-B' will be removed. * chart.regions.remove({ * classes: [ * "region-A", "region-B" * ] * }); * * // all of regions will be removed. * chart.regions.remove(); */ remove: function remove(optionsValue) { var $$ = this.internal, config = $$.config, options = optionsValue || {}, duration = getOption(options, "duration", config.transition_duration), classes = getOption(options, "classes", [config_classes.region]), regions = $$.$el.main.select("." + config_classes.regions).selectAll(classes.map(function (c) { return "." + c; })); return (duration ? regions.transition().duration(duration) : regions).style("opacity", "0").remove(), regions = config.regions, Object.keys(options).length ? (regions = regions.filter(function (region) { var found = !1; return !region.class || (region.class.split(" ").forEach(function (c) { classes.indexOf(c) >= 0 && (found = !0); }), !found); }), config.regions = regions) : config.regions = [], regions; } }); /* harmony default export */ var api_regions = ({ regions: regions }); ;// CONCATENATED MODULE: ./src/Chart/api/x.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var x = ({ /** * Get and set x values for the chart. * @function x * @instance * @memberof Chart * @param {Array} x If x is given, x values of every target will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. * @returns {object} xs * @example * // Get current x values * chart.x(); * * // Update x values for all targets * chart.x([100, 200, 300, 400, ...]); */ x: function x(_x) { var $$ = this.internal, axis = $$.axis, data = $$.data, isCategorized = axis.isCustomX() && axis.isCategorized(); return isArray(_x) && (isCategorized ? this.categories(_x) : ($$.updateTargetX(data.targets, _x), $$.redraw({ withUpdateOrgXDomain: !0, withUpdateXDomain: !0 }))), isCategorized ? this.categories() : data.xs; }, /** * Get and set x values for the chart. * @function xs * @instance * @memberof Chart * @param {Array} xs If xs is given, specified target's x values will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. * @returns {object} xs * @example * // Get current x values * chart.xs(); * * // Update x values for all targets * chart.xs({ * data1: [10, 20, 30, 40, ...], * data2: [100, 200, 300, 400, ...] * }); */ xs: function xs(_xs) { var $$ = this.internal; return isObject(_xs) && ($$.updateTargetXs($$.data.targets, _xs), $$.redraw({ withUpdateOrgXDomain: !0, withUpdateXDomain: !0 })), $$.data.xs; } }); ;// CONCATENATED MODULE: ./src/Chart/api/flow.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var flow = ({ /** * Flow data to the chart.<br><br> * By this API, you can append new data points to the chart. * @function flow * @instance * @memberof Chart * @param {object} args The object can consist with following members:<br> * * | Key | Type | Description | * | --- | --- | --- | * | json | Object | Data as JSON format (@see [dataβ€€json](Options.html#.data%25E2%2580%25A4json)) | * | rows | Array | Data in array as row format (@see [dataβ€€rows](Options.html#.data%25E2%2580%25A4json)) | * | columns | Array | Data in array as column format (@see [dataβ€€columns](Options.html#.data%25E2%2580%25A4columns)) | * | to | String | The lower x edge will move to that point. If not given, the lower x edge will move by the number of given data points | * | length | Number | The lower x edge will move by the number of this argument | * | duration | Number | The duration of the transition will be specified value. If not given, transition.duration will be used as default | * | done | Function | The specified function will be called when flow ends | * * - **NOTE:** * - If json, rows and columns given, the data will be loaded. * - If data that has the same target id is given, the chart will be appended. * - Otherwise, new target will be added. One of these is required when calling. * - If json specified, keys is required as well as data.json. * - If tab isn't visible(by evaluating `document.hidden`), will not be executed to prevent unnecessary work. * @example * // 2 data points will be apprended to the tail and popped from the head. * // After that, 4 data points will be appended and no data points will be poppoed. * chart.flow({ * columns: [ * ["x", "2018-01-11", "2018-01-21"], * ["data1", 500, 200], * ["data2", 100, 300], * ["data3", 200, 120] * ], * to: "2013-01-11", * done: function () { * chart.flow({ * columns: [ * ["x", "2018-02-11", "2018-02-12", "2018-02-13", "2018-02-14"], * ["data1", 200, 300, 100, 250], * ["data2", 100, 90, 40, 120], * ["data3", 100, 100, 300, 500] * ], * length: 2, * duration: 1500 * }); * } * }); */ flow: function flow(args) { var data, domain, diff, to, $$ = this.internal, length = 0, tail = 0; if ((args.json || args.rows || args.columns) && (data = $$.convertData(args)), data && isTabVisible()) { var notfoundIds = [], orgDataCount = $$.getMaxDataCount(), targets = $$.convertDataToTargets(data, !0), isTimeSeries = $$.axis.isTimeSeries(); $$.data.targets.forEach(function (t) { for (var found = !1, i = 0; i < targets.length; i++) if (t.id === targets[i].id) { found = !0, t.values[t.values.length - 1] && (tail = t.values[t.values.length - 1].index + 1), length = targets[i].values.length; for (var _j3 = 0; _j3 < length; _j3++) targets[i].values[_j3].index = tail + _j3, isTimeSeries || (targets[i].values[_j3].x = tail + _j3); t.values = t.values.concat(targets[i].values), targets.splice(i, 1); break; } found || notfoundIds.push(t.id); }), $$.data.targets.forEach(function (t) { for (var _i = 0; _i < notfoundIds.length; _i++) if (t.id === notfoundIds[_i]) { tail = t.values[t.values.length - 1].index + 1; for (var _j4 = 0; _j4 < length; _j4++) t.values.push({ id: t.id, index: tail + _j4, x: isTimeSeries ? $$.getOtherTargetX(tail + _j4) : tail + _j4, value: null }); } }), $$.data.targets.length && targets.forEach(function (t) { for (var missing = [], i = $$.data.targets[0].values[0].index; i < tail; i++) missing.push({ id: t.id, index: i, x: isTimeSeries ? $$.getOtherTargetX(i) : i, value: null }); t.values.forEach(function (v) { v.index += tail, isTimeSeries || (v.x += tail); }), t.values = missing.concat(t.values); }), $$.data.targets = $$.data.targets.concat(targets); // add remained // check data count because behavior needs to change when it"s only one // const dataCount = $$.getMaxDataCount(); var baseTarget = $$.data.targets[0], baseValue = baseTarget.values[0]; isDefined(args.to) ? (length = 0, to = isTimeSeries ? parseDate.call($$, args.to) : args.to, baseTarget.values.forEach(function (v) { v.x < to && length++; })) : isDefined(args.length) && (length = args.length), orgDataCount ? orgDataCount === 1 && isTimeSeries && (diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2, domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)]) : (diff = isTimeSeries ? baseTarget.values.length > 1 ? baseTarget.values[baseTarget.values.length - 1].x - baseValue.x : baseValue.x - $$.getXDomain($$.data.targets)[0] : 1, domain = [baseValue.x - diff, baseValue.x]), domain && $$.updateXDomain(null, !0, !0, !1, domain), $$.updateTargets($$.data.targets), $$.redraw({ flow: { index: baseValue.index, length: length, duration: isValue(args.duration) ? args.duration : $$.config.transition_duration, done: args.done, orgDataCount: orgDataCount }, withLegend: !0, withTransition: orgDataCount > 1, withTrimXDomain: !1, withUpdateXAxis: !0 }); } } }); // EXTERNAL MODULE: external {"commonjs":"d3-axis","commonjs2":"d3-axis","amd":"d3-axis","root":"d3"} var external_commonjs_d3_axis_commonjs2_d3_axis_amd_d3_axis_root_d3_ = __webpack_require__(10); ;// CONCATENATED MODULE: ./src/ChartInternal/Axis/AxisRendererHelper.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license * @ignore */ var AxisRendererHelper = /*#__PURE__*/function () { function AxisRendererHelper(owner) { this.owner = void 0, this.config = void 0, this.scale = void 0; var scale = getScale(), config = owner.config, params = owner.params; this.owner = owner, this.config = config, this.scale = scale, (config.noTransition || !params.config.transition_duration) && (config.withoutTransition = !0), config.range = this.scaleExtent((params.orgXScale || scale).range()); } /** * Compute a character dimension * @param {d3.selection} node <g class=tick> node * @returns {{w: number, h: number}} * @private */ AxisRendererHelper.getSizeFor1Char = function getSizeFor1Char(node) { // default size for one character var size = { w: 5.5, h: 11.5 }; return node.empty() || node.select("text").text("0").call(function (el) { try { var _el$node$getBBox = el.node().getBBox(), width = _el$node$getBBox.width, height = _el$node$getBBox.height; width && height && (size.w = width, size.h = height); } catch (e) {} finally { el.text(""); } }), this.getSizeFor1Char = function () { return size; }, size; } /** * Get tick transform setter function * @param {string} id Axis id * @returns {Function} transfrom setter function * @private */ ; var _proto = AxisRendererHelper.prototype; return _proto.getTickTransformSetter = function getTickTransformSetter(id) { var config = this.config, fn = id === "x" ? function (value) { return "translate(" + (value + config.tickOffset) + ",0)"; } : function (value) { return "translate(0," + value + ")"; }; return function (selection, scale) { selection.attr("transform", function (d) { return fn(Math.ceil(scale(d))); }); }; }, _proto.scaleExtent = function scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [start, stop] : [stop, start]; }, _proto.generateTicks = function generateTicks(scale, isYAxes) { var tickStepSize = this.owner.params.tickStepSize, _scale$domain = scale.domain(), start = _scale$domain[0], end = _scale$domain[1], ticks = []; // When 'axis[y|y2].tick.stepSize' option is set if (isYAxes && tickStepSize) for (var interval = start; interval <= end;) ticks.push(interval), interval += tickStepSize;else if (scale.ticks) { var tickArguments = this.config.tickArguments; // adjust excessive tick count show if (scale.type === "log" && !tickArguments) { // nicer symlog ticks didn't implemented yet: https://github.com/d3/d3-scale/issues/162 // get ticks values from logScale var s = getScale("_log").domain([start > 0 ? start : 1, end]).range(scale.range()); ticks = s.ticks(); for (var cnt = end.toFixed().length; ticks.length > 15; cnt--) ticks = s.ticks(cnt); ticks.splice(0, 1, start), ticks.splice(ticks.length - 1, 1, end); } else ticks = scale.ticks.apply(scale, this.config.tickArguments || []); ticks = ticks.map(function (v) { // round the tick value if is number var r = isString(v) && isNumber(v) && !isNaN(v) && Math.round(v * 10) / 10 || v; return r; }); } else { for (var i = Math.ceil(start); i < end; i++) ticks.push(i); ticks.length > 0 && ticks[0] > 0 && ticks.unshift(ticks[0] - (ticks[1] - ticks[0])); } return ticks; }, _proto.copyScale = function copyScale() { var newScale = this.scale.copy(); return newScale.domain().length || newScale.domain(this.scale.domain()), newScale.type = this.scale.type, newScale; }, _proto.textFormatted = function textFormatted(v) { var tickFormat = this.config.tickFormat, value = /\d+\.\d+0{5,}\d$/.test(v) ? +(v + "").replace(/0+\d$/, "") : v, formatted = tickFormat ? tickFormat(value) : value; // to round float numbers from 'binary floating point' // https://en.wikipedia.org/wiki/Double-precision_floating-point_format // https://stackoverflow.com/questions/17849101/laymans-explanation-for-why-javascript-has-weird-floating-math-ieee-754-stand return isDefined(formatted) ? formatted : ""; }, _proto.transitionise = function transitionise(selection) { var config = this.config; return config.withoutTransition ? selection.interrupt() : selection.transition(config.transition); }, AxisRendererHelper; }(); ;// CONCATENATED MODULE: ./src/ChartInternal/Axis/AxisRenderer.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license * @ignore */ var AxisRenderer = /*#__PURE__*/function () { function AxisRenderer(params) { params === void 0 && (params = {}), this.helper = void 0, this.config = void 0, this.params = void 0, this.g = void 0; var config = { innerTickSize: 6, outerTickSize: params.outerTick ? 6 : 0, orient: "bottom", range: [], tickArguments: null, tickCentered: null, tickCulling: !0, tickFormat: null, tickLength: 9, tickOffset: 0, tickPadding: 3, tickValues: null, transition: null, noTransition: params.noTransition }; config.tickLength = Math.max(config.innerTickSize, 0) + config.tickPadding, this.config = config, this.params = params, this.helper = new AxisRendererHelper(this); } /** * Create axis element * @param {d3.selection} g Axis selection * @private */ var _proto = AxisRenderer.prototype; return _proto.create = function create(g) { var ctx = this, config = this.config, helper = this.helper, params = this.params, scale = helper.scale, orient = config.orient, splitTickText = this.splitTickText.bind(this), isLeftRight = /^(left|right)$/.test(orient), isTopBottom = /^(top|bottom)$/.test(orient), tickTransform = helper.getTickTransformSetter(isTopBottom ? "x" : "y"), axisPx = tickTransform === helper.axisX ? "y" : "x", sign = /^(top|left)$/.test(orient) ? -1 : 1, rotate = params.tickTextRotate; this.config.range = scale.rangeExtent ? scale.rangeExtent() : helper.scaleExtent((params.orgXScale || scale).range()); var $g, _config2 = config, innerTickSize = _config2.innerTickSize, tickLength = _config2.tickLength, range = _config2.range, id = params.id, tickTextPos = id && /^(x|y|y2)$/.test(id) ? params.config["axis_" + id + "_tick_text_position"] : { x: 0, y: 0 }, prefix = id === "subX" ? "subchart_axis_x" : "axis_" + id, axisShow = params.config[prefix + "_show"], tickShow = { tick: !!axisShow && params.config[prefix + "_tick_show"], text: !!axisShow && params.config[prefix + "_tick_text_show"] }; // // get the axis' tick position configuration g.each(function () { var g = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), scale0 = this.__chart__ || scale, scale1 = helper.copyScale(); $g = g, this.__chart__ = scale1, config.tickOffset = params.isCategory ? Math.ceil((scale1(1) - scale1(0)) / 2) : 0; // update selection - data join var path = g.selectAll(".domain").data([0]); // enter + update selection if (path.enter().append("path").attr("class", "domain") // https://observablehq.com/@d3/d3-selection-2-0 .merge(helper.transitionise(path).selection()).attr("d", function () { var outerTickSized = config.outerTickSize * sign; return isTopBottom ? "M" + range[0] + "," + outerTickSized + "V0H" + range[1] + "V" + outerTickSized : "M" + outerTickSized + "," + range[0] + "H0V" + range[1] + "H" + outerTickSized; }), tickShow.tick || tickShow.text) { // count of tick data in array var ticks = config.tickValues || helper.generateTicks(scale1, isLeftRight), tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", "1"), tickExit = tick.exit().remove(); // update selection tick = tickEnter.merge(tick), tickShow.tick && tickEnter.append("line"), tickShow.text && tickEnter.append("text"); var sizeFor1Char = AxisRendererHelper.getSizeFor1Char(tick), counts = [], tspan = tick.select("text").selectAll("tspan").data(function (d, index) { var split = params.tickMultiline ? splitTickText(d, scale1, ticks, isLeftRight, sizeFor1Char.w) : isArray(helper.textFormatted(d)) ? helper.textFormatted(d).concat() : [helper.textFormatted(d)]; return counts[index] = split.length, split.map(function (splitted) { return { index: index, splitted: splitted }; }); }); tspan.exit().remove(), tspan = tspan.enter().append("tspan").merge(tspan).text(function (d) { return d.splitted; }), tspan.attr("x", isTopBottom ? 0 : tickLength * sign).attr("dx", function () { var dx = 0; return /(top|bottom)/.test(orient) && rotate && (dx = 8 * Math.sin(Math.PI * (rotate / 180)) * (orient === "top" ? -1 : 1)), dx + (tickTextPos.x || 0); }()).attr("dy", function (d, i) { var dy = 0; return orient !== "top" && (dy = sizeFor1Char.h, i === 0 && (dy = isLeftRight ? -((counts[d.index] - 1) * (sizeFor1Char.h / 2) - 3) : tickTextPos.y === 0 ? ".71em" : 0)), isNumber(dy) && tickTextPos.y ? dy + tickTextPos.y : dy || ".71em"; }); var lineUpdate = tick.select("line"), textUpdate = tick.select("text"); // Append <title> for tooltip display if (tickEnter.select("line").attr(axisPx + "2", innerTickSize * sign), tickEnter.select("text").attr(axisPx, tickLength * sign), ctx.setTickLineTextPosition(lineUpdate, textUpdate), params.tickTitle) { var title = textUpdate.select("title"); (title.empty() ? textUpdate.append("title") : title).text(function (index) { return params.tickTitle[index]; }); } if (scale1.bandwidth) { var x = scale1, dx = x.bandwidth() / 2; scale0 = function (d) { return x(d) + dx; }, scale1 = scale0; } else scale0.bandwidth ? scale0 = scale1 : tickTransform(tickExit, scale1); tickTransform(tickEnter, scale0), tickTransform(helper.transitionise(tick).style("opacity", "1"), scale1); } }), this.g = $g; } /** * Get tick x/y coordinate * @returns {{x: number, y: number}} * @private */ , _proto.getTickXY = function getTickXY() { var config = this.config, pos = { x: 0, y: 0 }; return this.params.isCategory && (pos.x = config.tickCentered ? 0 : config.tickOffset, pos.y = config.tickCentered ? config.tickOffset : 0), pos; } /** * Get tick size * @param {object} d data object * @returns {number} * @private */ , _proto.getTickSize = function getTickSize(d) { var scale = this.helper.scale, config = this.config, _config3 = config, innerTickSize = _config3.innerTickSize, range = _config3.range, tickPosition = scale(d) + (config.tickCentered ? 0 : config.tickOffset); return range[0] < tickPosition && tickPosition < range[1] ? innerTickSize : 0; } /** * Set tick's line & text position * @param {d3.selection} lineUpdate Line selection * @param {d3.selection} textUpdate Text selection * @private */ , _proto.setTickLineTextPosition = function setTickLineTextPosition(lineUpdate, textUpdate) { var tickPos = this.getTickXY(), _this$config = this.config, innerTickSize = _this$config.innerTickSize, orient = _this$config.orient, tickLength = _this$config.tickLength, tickOffset = _this$config.tickOffset, rotate = this.params.tickTextRotate, textAnchorForText = function (r) { var value = ["start", "end"]; return orient === "top" && value.reverse(), r ? r > 0 ? value[0] : value[1] : "middle"; }, textTransform = function (r) { return r ? "rotate(" + r + ")" : null; }, yForText = function (r) { var r2 = r / (orient === "bottom" ? 15 : 23); return r ? 11.5 - 2.5 * r2 * (r > 0 ? 1 : -1) : tickLength; }; orient === "bottom" ? (lineUpdate.attr("x1", tickPos.x).attr("x2", tickPos.x).attr("y2", this.getTickSize.bind(this)), textUpdate.attr("x", 0).attr("y", yForText(rotate)).style("text-anchor", textAnchorForText(rotate)).attr("transform", textTransform(rotate))) : orient === "top" ? (lineUpdate.attr("x2", 0).attr("y2", -innerTickSize), textUpdate.attr("x", 0).attr("y", -yForText(rotate) * 2).style("text-anchor", textAnchorForText(rotate)).attr("transform", textTransform(rotate))) : orient === "left" ? (lineUpdate.attr("x2", -innerTickSize).attr("y1", tickPos.y).attr("y2", tickPos.y), textUpdate.attr("x", -tickLength).attr("y", tickOffset).style("text-anchor", "end")) : orient === "right" ? (lineUpdate.attr("x2", innerTickSize).attr("y2", 0), textUpdate.attr("x", tickLength).attr("y", 0).style("text-anchor", "start")) : void 0; } // this should be called only when category axis , _proto.splitTickText = function splitTickText(d, scale, ticks, isLeftRight, charWidth) { // split given text by tick width size // eslint-disable-next-line function split(splitted, text) { for (var subtext, spaceIndex, textWidth, i = 1; i < text.length; i++) // if text width gets over tick width, split by space index or current index if (text.charAt(i) === " " && (spaceIndex = i), subtext = text.substr(0, i + 1), textWidth = charWidth * subtext.length, tickWidth < textWidth) return split(splitted.concat(text.substr(0, spaceIndex || i)), text.slice(spaceIndex ? spaceIndex + 1 : i)); return splitted.concat(text); } var params = this.params, tickText = this.helper.textFormatted(d), splitted = isString(tickText) && tickText.indexOf("\n") > -1 ? tickText.split("\n") : []; if (splitted.length) return splitted; if (isArray(tickText)) return tickText; var tickWidth = params.tickWidth; return (!tickWidth || tickWidth <= 0) && (tickWidth = isLeftRight ? 95 : params.isCategory ? Math.ceil(scale(ticks[1]) - scale(ticks[0])) - 12 : 110), split(splitted, tickText + ""); }, _proto.scale = function scale(x) { return arguments.length ? (this.helper.scale = x, this) : this.helper.scale; }, _proto.orient = function orient(x) { return arguments.length ? (this.config.orient = x in { top: 1, right: 1, bottom: 1, left: 1 } ? x + "" : "bottom", this) : this.config.orient; }, _proto.tickFormat = function tickFormat(format) { var config = this.config; return arguments.length ? (config.tickFormat = format, this) : config.tickFormat; }, _proto.tickCentered = function tickCentered(isCentered) { var config = this.config; return arguments.length ? (config.tickCentered = isCentered, this) : config.tickCentered; } /** * Return tick's offset value. * The value will be set for 'category' axis type. * @returns {number} * @private */ , _proto.tickOffset = function tickOffset() { return this.config.tickOffset; } /** * Get tick interval count * @private * @param {number} size Total data size * @returns {number} */ , _proto.tickInterval = function tickInterval(size) { var interval, _this = this; if (this.params.isCategory) interval = this.config.tickOffset * 2;else { var length = this.g.select("path.domain").node().getTotalLength() - this.config.outerTickSize * 2; interval = length / (size || this.g.selectAll("line").size()); // get the interval by its values var intervalByValue = this.config.tickValues.map(function (v, i, arr) { var next = i + 1; return next < arr.length ? _this.helper.scale(arr[next]) - _this.helper.scale(v) : null; }).filter(Boolean); interval = Math.min.apply(Math, intervalByValue.concat([interval])); } return interval === Infinity ? 0 : interval; }, _proto.ticks = function ticks() { for (var config = this.config, _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return args.length ? (config.tickArguments = toArray(args), this) : config.tickArguments; }, _proto.tickCulling = function tickCulling(culling) { var config = this.config; return arguments.length ? (config.tickCulling = culling, this) : config.tickCulling; }, _proto.tickValues = function tickValues(x) { var _this2 = this, config = this.config; if (isFunction(x)) config.tickValues = function () { return x(_this2.helper.scale.domain()); };else { if (!arguments.length) return config.tickValues; config.tickValues = x; } return this; }, _proto.setTransition = function setTransition(t) { return this.config.transition = t, this; }, AxisRenderer; }(); ;// CONCATENATED MODULE: ./src/ChartInternal/Axis/Axis.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var Axis = ({ getAxisInstance: function getAxisInstance() { return this.axis || new Axis_Axis(this); } }); var Axis_Axis = /*#__PURE__*/function () { function Axis(owner) { this.owner = void 0, this.x = void 0, this.subX = void 0, this.y = void 0, this.y2 = void 0, this.axesList = {}, this.tick = { x: null, y: null, y2: null }, this.xs = [], this.orient = { x: "bottom", y: "left", y2: "right", subX: "bottom" }, this.owner = owner, this.setOrient(); } var _proto = Axis.prototype; return _proto.getAxisClassName = function getAxisClassName(id) { return config_classes.axis + " " + config_classes["axis" + capitalize(id)]; }, _proto.isHorizontal = function isHorizontal($$, forHorizontal) { var isRotated = $$.config.axis_rotated; return forHorizontal ? isRotated : !isRotated; }, _proto.isCategorized = function isCategorized() { var _this$owner = this.owner, config = _this$owner.config, state = _this$owner.state; return config.axis_x_type.indexOf("category") >= 0 || state.hasRadar; }, _proto.isCustomX = function isCustomX() { var config = this.owner.config; return !this.isTimeSeries() && (config.data_x || notEmpty(config.data_xs)); }, _proto.isTimeSeries = function isTimeSeries(id) { return id === void 0 && (id = "x"), this.owner.config["axis_" + id + "_type"] === "timeseries"; }, _proto.isLog = function isLog(id) { return id === void 0 && (id = "x"), this.owner.config["axis_" + id + "_type"] === "log"; }, _proto.isTimeSeriesY = function isTimeSeriesY() { return this.isTimeSeries("y"); }, _proto.getAxisType = function getAxisType(id) { id === void 0 && (id = "x"); var type = "linear"; return this.isTimeSeries(id) ? type = "time" : this.isLog(id) && (type = "log"), type; }, _proto.init = function init() { var _this = this, $$ = this.owner, config = $$.config, _$$$$el = $$.$el, main = _$$$$el.main, axis = _$$$$el.axis, clip = $$.state.clip, isRotated = config.axis_rotated, target = ["x", "y"]; config.axis_y2_show && target.push("y2"), target.forEach(function (v) { var classAxis = _this.getAxisClassName(v), classLabel = config_classes["axis" + v.toUpperCase() + "Label"]; axis[v] = main.append("g").attr("class", classAxis).attr("clip-path", function () { var res = null; return v === "x" ? res = clip.pathXAxis : v === "y" && (res = clip.pathYAxis), res; }).attr("transform", $$.getTranslate(v)).style("visibility", config["axis_" + v + "_show"] ? "visible" : "hidden"), axis[v].append("text").attr("class", classLabel).attr("transform", ["rotate(-90)", null][v === "x" ? +!isRotated : +isRotated]).style("text-anchor", function () { return _this.textAnchorForAxisLabel(v); }), _this.generateAxes(v); }); } /** * Set axis orient according option value * @private */ , _proto.setOrient = function setOrient() { var $$ = this.owner, _$$$config = $$.config, isRotated = _$$$config.axis_rotated, yInner = _$$$config.axis_y_inner, y2Inner = _$$$config.axis_y2_inner; this.orient = { x: isRotated ? "left" : "bottom", y: isRotated ? yInner ? "top" : "bottom" : yInner ? "right" : "left", y2: isRotated ? y2Inner ? "bottom" : "top" : y2Inner ? "left" : "right", subX: isRotated ? "left" : "bottom" }; } /** * Generate axes * It's used when axis' axes option is set * @param {string} id Axis id * @private */ , _proto.generateAxes = function generateAxes(id) { var d3Axis, $$ = this.owner, config = $$.config, axes = [], axesConfig = config["axis_" + id + "_axes"], isRotated = config.axis_rotated; id === "x" ? d3Axis = isRotated ? external_commonjs_d3_axis_commonjs2_d3_axis_amd_d3_axis_root_d3_.axisLeft : external_commonjs_d3_axis_commonjs2_d3_axis_amd_d3_axis_root_d3_.axisBottom : id === "y" ? d3Axis = isRotated ? external_commonjs_d3_axis_commonjs2_d3_axis_amd_d3_axis_root_d3_.axisBottom : external_commonjs_d3_axis_commonjs2_d3_axis_amd_d3_axis_root_d3_.axisLeft : id === "y2" && (d3Axis = isRotated ? external_commonjs_d3_axis_commonjs2_d3_axis_amd_d3_axis_root_d3_.axisTop : external_commonjs_d3_axis_commonjs2_d3_axis_amd_d3_axis_root_d3_.axisRight), axesConfig.length && axesConfig.forEach(function (v) { var tick = v.tick || {}, scale = $$.scale[id].copy(); v.domain && scale.domain(v.domain), axes.push(d3Axis(scale).ticks(tick.count).tickFormat(isFunction(tick.format) ? tick.format.bind($$.api) : function (x) { return x; }).tickValues(tick.values).tickSizeOuter(tick.outer === !1 ? 0 : 6)); }), this.axesList[id] = axes; } /** * Update axes nodes * @private */ , _proto.updateAxes = function updateAxes() { var _this2 = this, $$ = this.owner, config = $$.config, main = $$.$el.main; Object.keys(this.axesList).forEach(function (id) { var axesConfig = config["axis_" + id + "_axes"], scale = $$.scale[id].copy(), range = scale.range(); _this2.axesList[id].forEach(function (v, i) { var axisRange = v.scale().range(); // adjust range value with the current // https://github.com/naver/billboard.js/issues/859 range.every(function (v, i) { return v === axisRange[i]; }) || v.scale().range(range); var className = _this2.getAxisClassName(id) + "-" + (i + 1), g = main.select("." + className.replace(/\s/, ".")); g.empty() ? g = main.append("g").attr("class", className).style("visibility", config["axis_" + id + "_show"] ? "visible" : "hidden").call(v) : (axesConfig[i].domain && scale.domain(axesConfig[i].domain), _this2.x.helper.transitionise(g).call(v.scale(scale))), g.attr("transform", $$.getTranslate(id, i + 1)); }); }); } /** * Set Axis & tick values * called from: updateScales() * @param {string} id Axis id string * @param {d3Scale} scale Scale * @param {boolean} outerTick If show outer tick * @param {boolean} noTransition If with no transition * @private */ , _proto.setAxis = function setAxis(id, scale, outerTick, noTransition) { var $$ = this.owner; id !== "subX" && (this.tick[id] = this.getTickValues(id)), this[id] = this.getAxis(id, scale, outerTick, // do not transit x Axis on zoom and resizing // https://github.com/naver/billboard.js/issues/1949 !!(id === "x" && ($$.scale.zoom || $$.config.subchart_show || $$.state.resizing)) || noTransition); } // called from : getMaxTickWidth() , _proto.getAxis = function getAxis(id, scale, outerTick, noTransition, noTickTextRotate) { var tickFormat, $$ = this.owner, config = $$.config, isX = /^(x|subX)$/.test(id), type = isX ? "x" : id, isCategory = isX && this.isCategorized(), orient = this.orient[id], tickTextRotate = noTickTextRotate ? 0 : $$.getAxisTickRotate(type); if (isX) tickFormat = $$.format.xAxisTick;else { var fn = config["axis_" + id + "_tick_format"]; isFunction(fn) && (tickFormat = fn.bind($$.api)); } var tickValues = this.tick[type], axisParams = mergeObj({ outerTick: outerTick, noTransition: noTransition, config: config, id: id, tickTextRotate: tickTextRotate }, isX && { isCategory: isCategory, tickMultiline: config.axis_x_tick_multiline, tickWidth: config.axis_x_tick_width, tickTitle: isCategory && config.axis_x_tick_tooltip && $$.api.categories(), orgXScale: $$.scale.x }); isX || (axisParams.tickStepSize = config["axis_" + type + "_tick_stepSize"]); var axis = new AxisRenderer(axisParams).scale(isX && $$.scale.zoom || scale).orient(orient); if (isX && this.isTimeSeries() && tickValues && !isFunction(tickValues)) { var _fn = parseDate.bind($$); tickValues = tickValues.map(function (v) { return _fn(v); }); } else !isX && this.isTimeSeriesY() && ( // https://github.com/d3/d3/blob/master/CHANGES.md#time-intervals-d3-time axis.ticks(config.axis_y_tick_time_value), tickValues = null); tickValues && axis.tickValues(tickValues), axis.tickFormat(tickFormat || !isX && $$.isStackNormalized() && function (x) { return x + "%"; }), isCategory && (axis.tickCentered(config.axis_x_tick_centered), isEmpty(config.axis_x_tick_culling) && (config.axis_x_tick_culling = !1)); var tickCount = config["axis_" + type + "_tick_count"]; return tickCount && axis.ticks(tickCount), axis; }, _proto.updateXAxisTickValues = function updateXAxisTickValues(targets, axis) { var values, $$ = this.owner, config = $$.config, fit = config.axis_x_tick_fit, count = config.axis_x_tick_count; return (fit || count && fit) && (values = $$.mapTargetsToUniqueXs(targets), this.isCategorized() && count > values.length && (count = values.length), values = this.generateTickValues(values, count, this.isTimeSeries())), axis ? axis.tickValues(values) : this.x && (this.x.tickValues(values), this.subX && this.subX.tickValues(values)), values; }, _proto.getId = function getId(id) { var _this$owner2 = this.owner, config = _this$owner2.config, scale = _this$owner2.scale, axis = config.data_axes[id]; return axis && scale[axis] || (axis = "y"), axis; }, _proto.getXAxisTickFormat = function getXAxisTickFormat() { var currFormat, $$ = this.owner, config = $$.config, format = $$.format, tickFormat = config.axis_x_tick_format, isTimeSeries = this.isTimeSeries(), isCategorized = this.isCategorized(); return tickFormat ? isFunction(tickFormat) ? currFormat = tickFormat.bind($$.api) : isTimeSeries && (currFormat = function (date) { return date ? format.axisTime(tickFormat)(date) : ""; }) : currFormat = isTimeSeries ? format.defaultAxisTime : isCategorized ? $$.categoryName : function (v) { return v < 0 ? v.toFixed(0) : v; }, isFunction(currFormat) ? function (v) { return currFormat.apply($$, isCategorized ? [v, $$.categoryName(v)] : [v]); } : currFormat; }, _proto.getTickValues = function getTickValues(id) { var $$ = this.owner, tickValues = $$.config["axis_" + id + "_tick_values"], axis = $$[id + "Axis"]; return (isFunction(tickValues) ? tickValues.call($$.api) : tickValues) || (axis ? axis.tickValues() : undefined); }, _proto.getLabelOptionByAxisId = function getLabelOptionByAxisId(id) { return this.owner.config["axis_" + id + "_label"]; }, _proto.getLabelText = function getLabelText(id) { var option = this.getLabelOptionByAxisId(id); return isString(option) ? option : option ? option.text : null; }, _proto.setLabelText = function setLabelText(id, text) { var $$ = this.owner, config = $$.config, option = this.getLabelOptionByAxisId(id); isString(option) ? config["axis_" + id + "_label"] = text : option && (option.text = text); }, _proto.getLabelPosition = function getLabelPosition(id, defaultPosition) { var isRotated = this.owner.config.axis_rotated, option = this.getLabelOptionByAxisId(id), position = isObjectType(option) && option.position ? option.position : defaultPosition[+!isRotated], has = function (v) { return !!~position.indexOf(v); }; return { isInner: has("inner"), isOuter: has("outer"), isLeft: has("left"), isCenter: has("center"), isRight: has("right"), isTop: has("top"), isMiddle: has("middle"), isBottom: has("bottom") }; }, _proto.getAxisLabelPosition = function getAxisLabelPosition(id) { return this.getLabelPosition(id, id === "x" ? ["inner-top", "inner-right"] : ["inner-right", "inner-top"]); }, _proto.getLabelPositionById = function getLabelPositionById(id) { return this.getAxisLabelPosition(id); }, _proto.xForAxisLabel = function xForAxisLabel(id) { var $$ = this.owner, _$$$state = $$.state, width = _$$$state.width, height = _$$$state.height, position = this.getAxisLabelPosition(id), x = position.isMiddle ? -height / 2 : 0; return this.isHorizontal($$, id !== "x") ? x = position.isLeft ? 0 : position.isCenter ? width / 2 : width : position.isBottom && (x = -height), x; }, _proto.dxForAxisLabel = function dxForAxisLabel(id) { var $$ = this.owner, position = this.getAxisLabelPosition(id), dx = position.isBottom ? "0.5em" : "0"; return this.isHorizontal($$, id !== "x") ? dx = position.isLeft ? "0.5em" : position.isRight ? "-0.5em" : "0" : position.isTop && (dx = "-0.5em"), dx; }, _proto.textAnchorForAxisLabel = function textAnchorForAxisLabel(id) { var $$ = this.owner, position = this.getAxisLabelPosition(id), anchor = position.isMiddle ? "middle" : "end"; return this.isHorizontal($$, id !== "x") ? anchor = position.isLeft ? "start" : position.isCenter ? "middle" : "end" : position.isBottom && (anchor = "start"), anchor; }, _proto.dyForAxisLabel = function dyForAxisLabel(id) { var dy, $$ = this.owner, config = $$.config, isRotated = config.axis_rotated, isInner = this.getAxisLabelPosition(id).isInner, tickRotate = config["axis_" + id + "_tick_rotate"] ? $$.getHorizontalAxisHeight(id) : 0, maxTickWidth = this.getMaxTickWidth(id); if (id === "x") { var xHeight = config.axis_x_height; dy = isRotated ? isInner ? "1.2em" : -25 - maxTickWidth : isInner ? "-0.5em" : xHeight ? xHeight - 10 : tickRotate ? tickRotate - 10 : "3em"; } else dy = { y: ["-0.5em", 10, "3em", "1.2em", 10], y2: ["1.2em", -20, "-2.2em", "-0.5em", 15] }[id], dy = isRotated ? isInner ? dy[0] : tickRotate ? tickRotate * (id === "y2" ? -1 : 1) - dy[1] : dy[2] : isInner ? dy[3] : (dy[4] + (config["axis_" + id + "_inner"] ? 0 : maxTickWidth + dy[4])) * (id === "y" ? -1 : 1); return dy; }, _proto.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) { var $$ = this.owner, config = $$.config, current = $$.state.current, _$$$$el2 = $$.$el, svg = _$$$$el2.svg, chart = _$$$$el2.chart, currentTickMax = current.maxTickWidths[id], maxWidth = 0; if (withoutRecompute || !config["axis_" + id + "_show"] || $$.filterTargetsToShow().length === 0) return currentTickMax.size; if (svg) { var isYAxis = /^y2?$/.test(id), targetsToShow = $$.filterTargetsToShow($$.data.targets), scale = $$.scale[id].copy().domain($$["get" + (isYAxis ? "Y" : "X") + "Domain"](targetsToShow, id)), domain = scale.domain(), isDomainSame = domain[0] === domain[1] && domain.every(function (v) { return v > 0; }), isCurrentMaxTickDomainSame = isArray(currentTickMax.domain) && currentTickMax.domain[0] === currentTickMax.domain[1] && currentTickMax.domain.every(function (v) { return v > 0; }); // do not compute if domain or currentMaxTickDomain is same if (isDomainSame || isCurrentMaxTickDomainSame) return currentTickMax.size; // reset old max state value to prevent from new data loading currentTickMax.domain = domain, isYAxis || currentTickMax.ticks.splice(0); var axis = this.getAxis(id, scale, !1, !1, !0), tickCount = config["axis_" + id + "_tick_count"], tickValues = config["axis_" + id + "_tick_values"]; !tickValues && tickCount && axis.tickValues(this.generateTickValues(domain, tickCount, isYAxis ? this.isTimeSeriesY() : this.isTimeSeries())), isYAxis || this.updateXAxisTickValues(targetsToShow, axis); var dummy = chart.append("svg").style("visibility", "hidden").style("position", "fixed").style("top", "0px").style("left", "0px"); axis.create(dummy), dummy.selectAll("text").each(function (d, i) { var currentTextWidth = this.getBoundingClientRect().width; maxWidth = Math.max(maxWidth, currentTextWidth), isYAxis || (currentTickMax.ticks[i] = currentTextWidth); }), dummy.remove(); } return maxWidth > 0 && (currentTickMax.size = maxWidth), currentTickMax.size; }, _proto.getXAxisTickTextY2Overflow = function getXAxisTickTextY2Overflow(defaultPadding) { var $$ = this.owner, axis = $$.axis, config = $$.config, state = $$.state, xAxisTickRotate = $$.getAxisTickRotate("x"); if ((axis.isCategorized() || axis.isTimeSeries()) && config.axis_x_tick_fit && !config.axis_x_tick_culling && !config.axis_x_tick_multiline && xAxisTickRotate > 0 && xAxisTickRotate < 90) { var widthWithoutCurrentPaddingLeft = state.current.width - $$.getCurrentPaddingLeft(), maxOverflow = this.getXAxisTickMaxOverflow(xAxisTickRotate, widthWithoutCurrentPaddingLeft - defaultPadding), xAxisTickTextY2Overflow = Math.max(0, maxOverflow) + defaultPadding; // for display inconsistencies between browsers return Math.min(xAxisTickTextY2Overflow, widthWithoutCurrentPaddingLeft / 2); } return 0; }, _proto.getXAxisTickMaxOverflow = function getXAxisTickMaxOverflow(xAxisTickRotate, widthWithoutCurrentPaddingLeft) { for (var $$ = this.owner, axis = $$.axis, config = $$.config, state = $$.state, isTimeSeries = axis.isTimeSeries(), tickTextWidths = state.current.maxTickWidths.x.ticks, tickCount = tickTextWidths.length, _state$axis$x$padding = state.axis.x.padding, left = _state$axis$x$padding.left, right = _state$axis$x$padding.right, maxOverflow = 0, remaining = tickCount - (isTimeSeries && config.axis_x_tick_fit ? .5 : 0), i = 0; i < tickCount; i++) { var tickIndex = i + 1, rotatedTickTextWidth = Math.cos(Math.PI * xAxisTickRotate / 180) * tickTextWidths[i], ticksBeforeTickText = tickIndex - (isTimeSeries ? 1 : .5) + left; // Skip ticks if there are no ticks before them if (!(ticksBeforeTickText <= 0)) { var tickLength = (widthWithoutCurrentPaddingLeft - rotatedTickTextWidth) / ticksBeforeTickText; maxOverflow = Math.max(maxOverflow, rotatedTickTextWidth - tickLength / 2 - ((remaining - tickIndex) * tickLength + right * tickLength)); } } var filteredTargets = $$.filterTargetsToShow($$.data.targets), tickOffset = 0; if (!isTimeSeries && config.axis_x_tick_count <= filteredTargets.length && filteredTargets[0].values.length) { var scale = getScale($$.axis.getAxisType("x"), 0, widthWithoutCurrentPaddingLeft - maxOverflow).domain([left * -1, $$.getXDomainMax($$.data.targets) + 1 + right]); tickOffset = Math.ceil((scale(1) - scale(0)) / 2); } return maxOverflow + tickOffset; } /** * Get x Axis padding * @param {number} tickCount Tick count * @returns {object} Padding object values with 'left' & 'right' key * @private */ , _proto.getXAxisPadding = function getXAxisPadding(tickCount) { var $$ = this.owner, padding = $$.config.axis_x_padding, _ref = isNumber(padding) ? { left: padding, right: padding } : padding, _ref$left = _ref.left, left = _ref$left === void 0 ? 0 : _ref$left, _ref$right = _ref.right, right = _ref$right === void 0 ? 0 : _ref$right; if ($$.axis.isTimeSeries()) { var firstX = +$$.getXDomainMin($$.data.targets), lastX = +$$.getXDomainMax($$.data.targets), timeDiff = lastX - firstX, range = timeDiff + left + right; if (tickCount && range) { var relativeTickWidth = timeDiff / tickCount / range; left = left / range / relativeTickWidth, right = right / range / relativeTickWidth; } } return { left: left, right: right }; }, _proto.updateLabels = function updateLabels(withTransition) { var _this3 = this, $$ = this.owner, main = $$.$el.main, labels = { x: main.select("." + config_classes.axisX + " ." + config_classes.axisXLabel), y: main.select("." + config_classes.axisY + " ." + config_classes.axisYLabel), y2: main.select("." + config_classes.axisY2 + " ." + config_classes.axisY2Label) }; Object.keys(labels).filter(function (id) { return !labels[id].empty(); }).forEach(function (v) { var node = labels[v]; (withTransition ? node.transition() : node).attr("x", function () { return _this3.xForAxisLabel(v); }).attr("dx", function () { return _this3.dxForAxisLabel(v); }).attr("dy", function () { return _this3.dyForAxisLabel(v); }).text(function () { return _this3.getLabelText(v); }); }); }, _proto.getPadding = function getPadding(padding, key, defaultValue, domainLength) { var p = isNumber(padding) ? padding : padding[key]; return isValue(p) ? this.convertPixelsToAxisPadding(p, domainLength) : defaultValue; }, _proto.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) { var $$ = this.owner, config = $$.config, _$$$state2 = $$.state, width = _$$$state2.width, height = _$$$state2.height, length = config.axis_rotated ? width : height; return domainLength * (pixels / length); }, _proto.generateTickValues = function generateTickValues(values, tickCount, forTimeSeries) { var tickValues = values; if (tickCount) { var targetCount = isFunction(tickCount) ? tickCount() : tickCount; // compute ticks according to tickCount if (targetCount === 1) tickValues = [values[0]];else if (targetCount === 2) tickValues = [values[0], values[values.length - 1]];else if (targetCount > 2) { var tickValue, isCategorized = this.isCategorized(), count = targetCount - 2, start = values[0], end = values[values.length - 1]; tickValues = [start]; for (var i = 0; i < count; i++) tickValue = +start + (end - start) / (count + 1) * (i + 1), tickValues.push(forTimeSeries ? new Date(tickValue) : isCategorized ? Math.round(tickValue) : tickValue); tickValues.push(end); } } return forTimeSeries || (tickValues = tickValues.sort(function (a, b) { return a - b; })), tickValues; }, _proto.generateTransitions = function generateTransitions(duration) { var $$ = this.owner, axis = $$.$el.axis, _map = ["x", "y", "y2", "subX"].map(function (v) { var ax = axis[v]; return ax && duration && (ax = ax.transition().duration(duration)), ax; }), axisX = _map[0], axisY = _map[1], axisY2 = _map[2], axisSubX = _map[3]; return { axisX: axisX, axisY: axisY, axisY2: axisY2, axisSubX: axisSubX }; }, _proto.redraw = function redraw(transitions, isHidden, isInit) { var _this4 = this, $$ = this.owner, config = $$.config, $el = $$.$el, opacity = isHidden ? "0" : "1"; ["x", "y", "y2", "subX"].forEach(function (id) { var axis = _this4[id], $axis = $el.axis[id]; axis && $axis && (!isInit && !config.transition_duration && (axis.config.withoutTransition = !0), $axis.style("opacity", opacity), axis.create(transitions["axis" + capitalize(id)])); }), this.updateAxes(); } /** * Redraw axis * @param {Array} targetsToShow targets data to be shown * @param {object} wth option object * @param {d3.Transition} transitions Transition object * @param {object} flow flow object * @param {boolean} isInit called from initialization * @private */ , _proto.redrawAxis = function redrawAxis(targetsToShow, wth, transitions, flow, isInit) { var xDomainForZoom, _this5 = this, $$ = this.owner, config = $$.config, scale = $$.scale, $el = $$.$el, hasZoom = !!scale.zoom; !hasZoom && this.isCategorized() && targetsToShow.length === 0 && scale.x.domain([0, $el.axis.x.selectAll(".tick").size()]), scale.x && targetsToShow.length ? (!hasZoom && $$.updateXDomain(targetsToShow, wth.UpdateXDomain, wth.UpdateOrgXDomain, wth.TrimXDomain), !config.axis_x_tick_values && this.updateXAxisTickValues(targetsToShow)) : this.x && (this.x.tickValues([]), this.subX && this.subX.tickValues([])), config.zoom_rescale && !flow && (xDomainForZoom = scale.x.orgDomain()), ["y", "y2"].forEach(function (key) { var axisScale = scale[key]; if (axisScale) { var tickValues = config["axis_" + key + "_tick_values"], tickCount = config["axis_" + key + "_tick_count"]; if (axisScale.domain($$.getYDomain(targetsToShow, key, xDomainForZoom)), !tickValues && tickCount) { var _axis = $$.axis[key], domain = axisScale.domain(); _axis.tickValues(_this5.generateTickValues(domain, domain.every(function (v) { return v === 0; }) ? 1 : tickCount, _this5.isTimeSeriesY())); } } }), this.redraw(transitions, $$.hasArcType(), isInit), this.updateLabels(wth.Transition), (wth.UpdateXDomain || wth.UpdateXAxis || wth.Y) && targetsToShow.length && this.setCulling(), wth.Y && (scale.subY && scale.subY.domain($$.getYDomain(targetsToShow, "y")), scale.subY2 && scale.subY2.domain($$.getYDomain(targetsToShow, "y2"))); } /** * Set manual culling * @private */ , _proto.setCulling = function setCulling() { var $$ = this.owner, config = $$.config, _$$$state3 = $$.state, clip = _$$$state3.clip, current = _$$$state3.current, $el = $$.$el; ["subX", "x", "y", "y2"].forEach(function (type) { var axis = $el.axis[type], id = type === "subX" ? "x" : type, toCull = config["axis_" + id + "_tick_culling"]; // subchart x axis should be aligned with x axis culling if (axis && toCull) { var intervalForCulling, tickText = axis.selectAll(".tick text"), tickValues = sortValue(tickText.data()), tickSize = tickValues.length, cullingMax = config["axis_" + id + "_tick_culling_max"]; if (tickSize) { for (var i = 1; i < tickSize; i++) if (tickSize / i < cullingMax) { intervalForCulling = i; break; } tickText.each(function (d) { this.style.display = tickValues.indexOf(d) % intervalForCulling ? "none" : "block"; }); } else tickText.style("display", "block"); // set/unset x_axis_tick_clippath if (type === "x") { var clipPath = current.maxTickWidths.x.clipPath ? clip.pathXAxisTickTexts : null; $el.svg.selectAll("." + config_classes.axisX + " .tick text").attr("clip-path", clipPath); } } }); }, Axis; }(); ;// CONCATENATED MODULE: ./src/ChartInternal/interactions/eventrect.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var eventrect = ({ /** * Initialize the area that detects the event. * Add a container for the zone that detects the event. * @private */ initEventRect: function initEventRect() { var $$ = this; $$.$el.main.select("." + config_classes.chart).append("g").attr("class", config_classes.eventRects).style("fill-opacity", "0"); }, /** * Redraws the area that detects the event. * @private */ redrawEventRect: function redrawEventRect() { var $$ = this, config = $$.config, state = $$.state, $el = $$.$el, isMultipleX = $$.isMultipleX(); if ($el.eventRect) $$.updateEventRect($el.eventRect, !0);else { var eventRects = $$.$el.main.select("." + config_classes.eventRects).style("cursor", config.zoom_enabled && config.zoom_type !== "drag" ? config.axis_rotated ? "ns-resize" : "ew-resize" : null).classed(config_classes.eventRectsMultiple, isMultipleX).classed(config_classes.eventRectsSingle, !isMultipleX), eventRectUpdate = eventRects.selectAll("." + config_classes.eventRect).data([0]).enter().append("rect"); // append event <rect> // bind event to <rect> element // bind draggable selection $$.updateEventRect(eventRectUpdate), isMultipleX ? $$.generateEventRectsForMultipleXs(eventRectUpdate) : $$.generateEventRectsForSingleX(eventRectUpdate), eventRectUpdate.call($$.getDraggableSelection()), $el.eventRect = eventRectUpdate, $$.state.inputType !== "touch" || $el.svg.on("touchstart.eventRect") || $$.hasArcType() || $$.bindTouchOnEventRect(isMultipleX); } if (!isMultipleX) { // Set data and update eventReceiver.data var xAxisTickValues = $$.getMaxDataCountTarget(); // update data's index value to be alinged with the x Axis $$.updateDataIndexByX(xAxisTickValues), $$.updateXs(xAxisTickValues), $$.updatePointClass && $$.updatePointClass(!0), state.eventReceiver.data = xAxisTickValues; } $$.updateEventRectData(); }, bindTouchOnEventRect: function bindTouchOnEventRect(isMultipleX) { var startPx, $$ = this, config = $$.config, state = $$.state, _$$$$el = $$.$el, eventRect = _$$$$el.eventRect, svg = _$$$$el.svg, selectRect = function (context) { if (isMultipleX) $$.selectRectForMultipleXs(context);else { var index = $$.getDataIndexFromEvent(state.event); $$.callOverOutForTouch(index), index === -1 ? $$.unselectRect() : $$.selectRectForSingle(context, eventRect, index); } }, unselectRect = function () { $$.unselectRect(), $$.callOverOutForTouch(); }, preventDefault = config.interaction_inputType_touch.preventDefault, isPrevented = isboolean(preventDefault) && preventDefault || !1, preventThreshold = !isNaN(preventDefault) && preventDefault || null, preventEvent = function (event) { var eventType = event.type, touch = event.changedTouches[0], currentXY = touch["client" + (config.axis_rotated ? "Y" : "X")]; eventType === "touchstart" ? isPrevented ? event.preventDefault() : preventThreshold !== null && (startPx = currentXY) : eventType === "touchmove" && (isPrevented || startPx === !0 || preventThreshold !== null && Math.abs(startPx - currentXY) >= preventThreshold) && (startPx = !0, event.preventDefault()); }; // bind touch events eventRect.on("touchstart", function (event) { state.event = event, $$.updateEventRect(); }).on("touchstart.eventRect touchmove.eventRect", function (event) { if (state.event = event, !eventRect.empty() && eventRect.classed(config_classes.eventRect)) { // if touch points are > 1, means doing zooming interaction. In this case do not execute tooltip codes. if (state.dragging || state.flowing || $$.hasArcType() || event.touches.length > 1) return; preventEvent(event), selectRect(eventRect.node()); } else unselectRect(); }, !0).on("touchend.eventRect", function (event) { state.event = event, !eventRect.empty() && eventRect.classed(config_classes.eventRect) && ($$.hasArcType() || !$$.toggleShape || state.cancelClick) && state.cancelClick && (state.cancelClick = !1); }, !0), svg.on("touchstart", function (event) { state.event = event; var target = event.target; target && target !== eventRect.node() && unselectRect(); }); }, /** * Update event rect size * @param {d3Selection} eventRect Event <rect> element * @param {boolean} force Force to update * @private */ updateEventRect: function updateEventRect(eventRect, force) { force === void 0 && (force = !1); var $$ = this, state = $$.state, $el = $$.$el, _state = state, eventReceiver = _state.eventReceiver, width = _state.width, height = _state.height, rendered = _state.rendered, resizing = _state.resizing, rectElement = eventRect || $el.eventRect; (!rendered || resizing || force) && (rectElement.attr("x", 0).attr("y", 0).attr("width", width).attr("height", height), !rendered && rectElement.attr("class", config_classes.eventRect)), function updateClientRect() { eventReceiver && (eventReceiver.rect = rectElement.node().getBoundingClientRect()); }(); }, /** * Updates the location and size of the eventRect. * @private */ updateEventRectData: function updateEventRectData() { var x, y, w, h, $$ = this, config = $$.config, scale = $$.scale, state = $$.state, xScale = scale.zoom || scale.x, isRotated = config.axis_rotated; if ($$.isMultipleX()) // TODO: rotated not supported yet x = 0, y = 0, w = state.width, h = state.height;else { var rectW, rectX; if ($$.axis.isCategorized()) rectW = $$.getEventRectWidth(), rectX = function (d) { return xScale(d.x) - rectW / 2; };else { var getPrevNextX = function (_ref) { var index = _ref.index; return { prev: $$.getPrevX(index), next: $$.getNextX(index) }; }; rectW = function (d) { var x = getPrevNextX(d); // if there this is a single data point make the eventRect full width (or height) return x.prev === null && x.next === null ? isRotated ? state.height : state.width : (x.prev === null && (x.prev = xScale.domain()[0]), x.next === null && (x.next = xScale.domain()[1]), Math.max(0, (xScale(x.next) - xScale(x.prev)) / 2)); }, rectX = function (d) { var x = getPrevNextX(d), thisX = d.x; // if there this is a single data point position the eventRect at 0 return x.prev === null && x.next === null ? 0 : (x.prev === null && (x.prev = xScale.domain()[0]), (xScale(thisX) + xScale(x.prev)) / 2); }; } x = isRotated ? 0 : rectX, y = isRotated ? rectX : 0, w = isRotated ? state.width : rectW, h = isRotated ? rectW : state.height; } var eventReceiver = state.eventReceiver, call = function (fn, v) { return isFunction(fn) ? fn(v) : fn; }; // reset for possible remains coords data before the data loading eventReceiver.coords.splice(eventReceiver.data.length), eventReceiver.data.forEach(function (d, i) { eventReceiver.coords[i] = { x: call(x, d), y: call(y, d), w: call(w, d), h: call(h, d) }; }); }, selectRectForMultipleXs: function selectRectForMultipleXs(context) { var $$ = this, config = $$.config, state = $$.state, targetsToShow = $$.filterTargetsToShow($$.data.targets); // do nothing when dragging if (!(state.dragging || $$.hasArcType(targetsToShow))) { var mouse = getPointer(state.event, context), closest = $$.findClosestFromTargets(targetsToShow, mouse); if (state.mouseover && (!closest || closest.id !== state.mouseover.id) && (config.data_onout.call($$.api, state.mouseover), state.mouseover = undefined), !closest) return void $$.unselectRect(); var sameXData = $$.isBubbleType(closest) || $$.isScatterType(closest) || !config.tooltip_grouped ? [closest] : $$.filterByX(targetsToShow, closest.x), selectedData = sameXData.map(function (d) { return $$.addName(d); }); // show tooltip when cursor is close to some point $$.showTooltip(selectedData, context), $$.setExpand(closest.index, closest.id, !0), $$.showGridFocus(selectedData), ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) && ($$.$el.svg.select("." + config_classes.eventRect).style("cursor", "pointer"), !state.mouseover && (config.data_onover.call($$.api, closest), state.mouseover = closest)); } }, /** * Unselect EventRect. * @private */ unselectRect: function unselectRect() { var $$ = this, config = $$.config, _$$$$el2 = $$.$el, circle = _$$$$el2.circle, tooltip = _$$$$el2.tooltip; $$.$el.svg.select("." + config_classes.eventRect).style("cursor", null), $$.hideGridFocus(), tooltip && ($$.hideTooltip(), $$._handleLinkedCharts(!1)), circle && !config.point_focus_only && $$.unexpandCircles(), $$.expandBarTypeShapes(!1); }, /** * Create eventRect for each data on the x-axis. * Register touch and drag events. * @param {object} eventRectEnter d3.select(CLASS.eventRects) object. * @returns {object} d3.select(CLASS.eventRects) object. * @private */ generateEventRectsForSingleX: function generateEventRectsForSingleX(eventRectEnter) { var $$ = this, config = $$.config, state = $$.state, eventReceiver = state.eventReceiver, rect = eventRectEnter.style("cursor", config.data_selection_enabled && config.data_selection_grouped ? "pointer" : null).on("click", function (event) { state.event = event; var _eventReceiver = eventReceiver, currentIdx = _eventReceiver.currentIdx, data = _eventReceiver.data, d = data[currentIdx === -1 ? $$.getDataIndexFromEvent(event) : currentIdx]; $$.clickHandlerForSingleX.bind(this)(d, $$); }); if (state.inputType === "mouse") { var getData = function (event) { var index = event ? $$.getDataIndexFromEvent(event) : eventReceiver.currentIdx; return index > -1 ? eventReceiver.data[index] : null; }; rect.on("mouseover", function (event) { state.event = event, $$.updateEventRect(); }).on("mousemove", function (event) { var d = getData(event); // do nothing while dragging/flowing if (state.event = event, !(state.dragging || state.flowing || $$.hasArcType() || !d || config.tooltip_grouped && d && d.index === eventReceiver.currentIdx)) { var index = d.index; $$.isStepType(d) && config.line_step_type === "step-after" && getPointer(event, this)[0] < $$.scale.x($$.getXValue(d.id, index)) && (index -= 1), index !== eventReceiver.currentIdx && ($$.setOverOut(!1, eventReceiver.currentIdx), eventReceiver.currentIdx = index), index === -1 ? $$.unselectRect() : $$.selectRectForSingle(this, rect, index), $$.setOverOut(index !== -1, index); } }).on("mouseout", function (event) { state.event = event; // chart is destroyed !config || $$.hasArcType() || eventReceiver.currentIdx === -1 || ( // reset the event current index $$.unselectRect(), $$.setOverOut(!1, eventReceiver.currentIdx), eventReceiver.currentIdx = -1); }); } return rect; }, clickHandlerForSingleX: function clickHandlerForSingleX(d, ctx) { var $$ = ctx, config = $$.config, state = $$.state, main = $$.$el.main; if (!d || $$.hasArcType() || state.cancelClick) return void (state.cancelClick && (state.cancelClick = !1)); var index = d.index; main.selectAll("." + config_classes.shape + "-" + index).each(function (d2) { (config.data_selection_grouped || $$.isWithinShape(this, d2)) && ($$.toggleShape && $$.toggleShape(this, d2, index), config.data_onclick.bind($$.api)(d2, this)); }); }, /** * Create an eventRect, * Register touch and drag events. * @param {object} eventRectEnter d3.select(CLASS.eventRects) object. * @private */ generateEventRectsForMultipleXs: function generateEventRectsForMultipleXs(eventRectEnter) { var $$ = this, state = $$.state; eventRectEnter.on("click", function (event) { state.event = event, $$.clickHandlerForMultipleXS.bind(this)($$); }), state.inputType === "mouse" && eventRectEnter.on("mouseover mousemove", function (event) { state.event = event, $$.selectRectForMultipleXs(this); }).on("mouseout", function (event) { state.event = event; // chart is destroyed !$$.config || $$.hasArcType() || $$.unselectRect(); }); }, clickHandlerForMultipleXS: function clickHandlerForMultipleXS(ctx) { var $$ = ctx, config = $$.config, state = $$.state, targetsToShow = $$.filterTargetsToShow($$.data.targets); if (!$$.hasArcType(targetsToShow)) { var mouse = getPointer(state.event, this), closest = $$.findClosestFromTargets(targetsToShow, mouse); !closest || ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) && $$.$el.main.selectAll("." + config_classes.shapes + $$.getTargetSelectorSuffix(closest.id)).selectAll("." + config_classes.shape + "-" + closest.index).each(function () { (config.data_selection_grouped || $$.isWithinShape(this, closest)) && ($$.toggleShape && $$.toggleShape(this, closest, closest.index), config.data_onclick.bind($$.api)(closest, this)); }); } // select if selection enabled } }); // EXTERNAL MODULE: external {"commonjs":"d3-ease","commonjs2":"d3-ease","amd":"d3-ease","root":"d3"} var external_commonjs_d3_ease_commonjs2_d3_ease_amd_d3_ease_root_d3_ = __webpack_require__(11); ;// CONCATENATED MODULE: ./src/ChartInternal/interactions/flow.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var interactions_flow = ({ /** * Generate flow * @param {object} args option object * @returns {Function} * @private */ generateFlow: function generateFlow(args) { var $$ = this, data = $$.data, state = $$.state, $el = $$.$el; return function () { var flowLength = args.flow.length; // set flag state.flowing = !0, data.targets.forEach(function (d) { d.values.splice(0, flowLength); }), $$.updateXGrid && $$.updateXGrid(!0); // target elements var elements = {}; ["axis.x", "grid.x", "gridLines.x", "region.list", "text", "bar", "line", "area", "circle"].forEach(function (v) { var name = v.split("."), node = $el[name[0]]; node && name.length > 1 && (node = node[name[1]]), node && node.size() && (elements[v] = node); }), $$.hideGridFocus(), $$.setFlowList(elements, args); }; }, /** * Set flow list * @param {object} elements Target elements * @param {object} args option object * @private */ setFlowList: function setFlowList(elements, args) { var n, $$ = this, flow = args.flow, targets = args.targets, _flow = flow, _flow$duration = _flow.duration, duration = _flow$duration === void 0 ? args.duration : _flow$duration, flowIndex = _flow.index, flowLength = _flow.length, orgDataCount = _flow.orgDataCount, transform = $$.getFlowTransform(targets, orgDataCount, flowIndex, flowLength), wait = generateWait(); wait.add(Object.keys(elements).map(function (v) { return n = elements[v].transition().ease(external_commonjs_d3_ease_commonjs2_d3_ease_amd_d3_ease_root_d3_.easeLinear).duration(duration), n = v === "axis.x" ? n.call(function (g) { $$.axis.x.setTransition(g).create(g); }) : v === "region.list" ? n.filter($$.isRegionOnX).attr("transform", transform) : n.attr("transform", transform), n; })), n.call(wait, function () { $$.cleanUpFlow(elements, args); }); }, /** * Clean up flow * @param {object} elements Target elements * @param {object} args option object * @private */ cleanUpFlow: function cleanUpFlow(elements, args) { var $$ = this, config = $$.config, state = $$.state, svg = $$.$el.svg, isRotated = config.axis_rotated, flow = args.flow, shape = args.shape, xv = args.xv, _shape$pos = shape.pos, cx = _shape$pos.cx, cy = _shape$pos.cy, xForText = _shape$pos.xForText, yForText = _shape$pos.yForText, _flow2 = flow, _flow2$done = _flow2.done, done = _flow2$done === void 0 ? function () {} : _flow2$done, flowLength = _flow2.length; // draw again for removing flowed elements and reverting attr // callback for end of flow flowLength && (["circle", "text", "shape", "eventRect"].forEach(function (v) { var target = []; for (var i = 0; i < flowLength; i++) target.push("." + config_classes[v] + "-" + i); svg.selectAll("." + config_classes[v + "s"]) // circles, shapes, texts, eventRects .selectAll(target).remove(); }), svg.select("." + config_classes.xgrid).remove()), Object.keys(elements).forEach(function (v) { var n = elements[v]; if (v !== "axis.x" && n.attr("transform", null), v === "grid.x") n.attr(state.xgridAttr);else if (v === "gridLines.x") n.attr("x1", isRotated ? 0 : xv).attr("x2", isRotated ? state.width : xv);else if (v === "gridLines.x") n.select("line").attr("x1", isRotated ? 0 : xv).attr("x2", isRotated ? state.width : xv), n.select("text").attr("x", isRotated ? state.width : 0).attr("y", xv);else if (/^(area|bar|line)$/.test(v)) n.attr("d", shape.type[v]);else if (v === "text") n.attr("x", xForText).attr("y", yForText).style("fill-opacity", $$.opacityForText.bind($$));else if (v !== "circle") v === "region.list" && n.select("rect").filter($$.isRegionOnX).attr("x", $$.regionX.bind($$)).attr("width", $$.regionWidth.bind($$));else if ($$.isCirclePoint()) n.attr("cx", cx).attr("cy", cy);else { var xFunc = function (d) { return cx(d) - config.point_r; }, yFunc = function (d) { return cy(d) - config.point_r; }; n.attr("x", xFunc).attr("y", yFunc).attr("cx", cx) // when pattern is used, it possibly contain 'circle' also. .attr("cy", cy); } }), config.interaction_enabled && $$.redrawEventRect(), done.call($$.api), state.flowing = !1; }, /** * Get flow transform value * @param {object} targets target * @param {number} orgDataCount original data count * @param {number} flowIndex flow index * @param {number} flowLength flow length * @returns {string} * @private */ getFlowTransform: function getFlowTransform(targets, orgDataCount, flowIndex, flowLength) { var translateX, $$ = this, data = $$.data, x = $$.scale.x, dataValues = data.targets[0].values, flowStart = $$.getValueOnIndex(dataValues, flowIndex), flowEnd = $$.getValueOnIndex(dataValues, flowIndex + flowLength), orgDomain = x.domain(), domain = $$.updateXDomain(targets, !0, !0); orgDataCount ? orgDataCount === 1 || (flowStart && flowStart.x) === (flowEnd && flowEnd.x) ? translateX = x(orgDomain[0]) - x(domain[0]) : translateX = $$.axis.isTimeSeries() ? x(orgDomain[0]) - x(domain[0]) : x(flowStart.x) - x(flowEnd.x) : dataValues.length === 1 ? $$.axis.isTimeSeries() ? (flowStart = $$.getValueOnIndex(dataValues, 0), flowEnd = $$.getValueOnIndex(dataValues, dataValues.length - 1), translateX = x(flowStart.x) - x(flowEnd.x)) : translateX = diffDomain(domain) / 2 : translateX = x(orgDomain[0]) - x(domain[0]); var scaleX = diffDomain(orgDomain) / diffDomain(domain); return "translate(" + translateX + ",0) scale(" + scaleX + ",1)"; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/clip.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var clip = ({ initClip: function initClip() { var $$ = this, clip = $$.state.clip; // MEMO: clipId needs to be unique because it conflicts when multiple charts exist // Define 'clip-path' attribute values clip.id = $$.state.datetimeId + "-clip", clip.idXAxis = clip.id + "-xaxis", clip.idYAxis = clip.id + "-yaxis", clip.idGrid = clip.id + "-grid", clip.path = $$.getClipPath(clip.id), clip.pathXAxis = $$.getClipPath(clip.idXAxis), clip.pathYAxis = $$.getClipPath(clip.idYAxis), clip.pathGrid = $$.getClipPath(clip.idGrid); }, getClipPath: function getClipPath(id) { var $$ = this, config = $$.config; if (!config.clipPath && /-clip$/.test(id) || !config.axis_x_clipPath && /-clip-xaxis$/.test(id) || !config.axis_y_clipPath && /-clip-yaxis$/.test(id)) return null; var isIE9 = !!win.navigator && win.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0; return "url(" + (isIE9 ? "" : browser_doc.URL.split("#")[0]) + "#" + id + ")"; }, appendClip: function appendClip(parent, id) { id && parent.append("clipPath").attr("id", id).append("rect"); }, /** * Set x Axis clipPath dimension * @param {d3Selecton} node clipPath <rect> selection * @private */ setXAxisClipPath: function setXAxisClipPath(node) { var $$ = this, config = $$.config, _$$$state = $$.state, margin = _$$$state.margin, width = _$$$state.width, height = _$$$state.height, isRotated = config.axis_rotated, left = Math.max(30, margin.left) - (isRotated ? 0 : 20), x = isRotated ? -(1 + left) : -(left - 1), y = -Math.max(15, margin.top), w = isRotated ? margin.left + 20 : width + 10 + left, h = (isRotated ? margin.top + height + 10 : margin.bottom) + 20; node.attr("x", x).attr("y", y).attr("width", w).attr("height", h); }, /** * Set y Axis clipPath dimension * @param {d3Selecton} node clipPath <rect> selection * @private */ setYAxisClipPath: function setYAxisClipPath(node) { var $$ = this, config = $$.config, _$$$state2 = $$.state, margin = _$$$state2.margin, width = _$$$state2.width, height = _$$$state2.height, isRotated = config.axis_rotated, left = Math.max(30, margin.left) - (isRotated ? 20 : 0), isInner = config.axis_y_inner, x = isInner ? -1 : isRotated ? -(1 + left) : -(left - 1), y = -(isRotated ? 20 : margin.top), w = (isRotated ? width + 15 + left : margin.left + 20) + (isInner ? 20 : 0), h = (isRotated ? margin.bottom : margin.top + height) + 10; node.attr("x", x).attr("y", y).attr("width", w).attr("height", h); }, updateXAxisTickClip: function updateXAxisTickClip() { var $$ = this, config = $$.config, _$$$state3 = $$.state, clip = _$$$state3.clip, xAxisHeight = _$$$state3.xAxisHeight, defs = $$.$el.defs, newXAxisHeight = $$.getHorizontalAxisHeight("x"); if (defs && !clip.idXAxisTickTexts) { var clipId = clip.id + "-xaxisticktexts"; $$.appendClip(defs, clipId), clip.pathXAxisTickTexts = $$.getClipPath(clip.idXAxisTickTexts), clip.idXAxisTickTexts = clipId; } !config.axis_x_tick_multiline && $$.getAxisTickRotate("x") && newXAxisHeight !== xAxisHeight && ($$.setXAxisTickClipWidth(), $$.setXAxisTickTextClipPathWidth()), $$.state.xAxisHeight = newXAxisHeight; }, setXAxisTickClipWidth: function setXAxisTickClipWidth() { var $$ = this, config = $$.config, maxTickWidths = $$.state.current.maxTickWidths, xAxisTickRotate = $$.getAxisTickRotate("x"); if (!config.axis_x_tick_multiline && xAxisTickRotate) { var sinRotation = Math.sin(Math.PI / 180 * Math.abs(xAxisTickRotate)); maxTickWidths.x.clipPath = ($$.getHorizontalAxisHeight("x") - 20) / sinRotation; } else maxTickWidths.x.clipPath = null; }, setXAxisTickTextClipPathWidth: function setXAxisTickTextClipPathWidth() { var $$ = this, _$$$state4 = $$.state, clip = _$$$state4.clip, current = _$$$state4.current, svg = $$.$el.svg; svg && svg.select("#" + clip.idXAxisTickTexts + " rect").attr("width", current.maxTickWidths.x.clipPath).attr("height", 30); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/grid.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // Grid position and text anchor helpers var getGridTextAnchor = function (d) { return isValue(d.position) || "end"; }, getGridTextDx = function (d) { return d.position === "start" ? 4 : d.position === "middle" ? 0 : -4; }; /** * Get grid text x value getter function * @param {boolean} isX Is x Axis * @param {number} width Width value * @param {number} height Height value * @returns {Function} * @private */ function getGridTextX(isX, width, height) { return function (d) { var x = isX ? 0 : width; return d.position === "start" ? x = isX ? -height : 0 : d.position === "middle" && (x = (isX ? -height : width) / 2), x; }; } /** * Update coordinate attributes value * @param {d3.selection} el Target node * @param {string} type Type * @private */ function smoothLines(el, type) { type === "grid" && el.each(function () { var g = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this); ["x1", "x2", "y1", "y2"].forEach(function (v) { return g.attr(v, Math.ceil(+g.attr(v))); }); }); } /* harmony default export */ var grid = ({ hasGrid: function hasGrid() { var config = this.config; return ["x", "y"].some(function (v) { return config["grid_" + v + "_show"] || config["grid_" + v + "_lines"].length; }); }, initGrid: function initGrid() { var $$ = this; $$.hasGrid() && $$.initGridLines(), $$.initFocusGrid(); }, initGridLines: function initGridLines() { var $$ = this, config = $$.config, clip = $$.state.clip, $el = $$.$el; (config.grid_x_lines.length || config.grid_y_lines.length) && ($el.gridLines.main = $el.main.insert("g", "." + config_classes.chart + (config.grid_lines_front ? " + *" : "")).attr("clip-path", clip.pathGrid).attr("class", config_classes.grid + " " + config_classes.gridLines), $el.gridLines.main.append("g").attr("class", config_classes.xgridLines), $el.gridLines.main.append("g").attr("class", config_classes.ygridLines), $el.gridLines.x = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.selectAll)([])); }, updateXGrid: function updateXGrid(withoutUpdate) { var $$ = this, config = $$.config, scale = $$.scale, state = $$.state, _$$$$el = $$.$el, main = _$$$$el.main, grid = _$$$$el.grid, isRotated = config.axis_rotated, xgridData = $$.generateGridData(config.grid_x_type, scale.x), tickOffset = $$.axis.isCategorized() ? $$.axis.x.tickOffset() : 0, pos = function (d) { return (scale.zoom || scale.x)(d) + tickOffset * (isRotated ? -1 : 1); }; state.xgridAttr = isRotated ? { "x1": 0, "x2": state.width, "y1": pos, "y2": pos } : { "x1": pos, "x2": pos, "y1": 0, "y2": state.height }, grid.x = main.select("." + config_classes.xgrids).selectAll("." + config_classes.xgrid).data(xgridData), grid.x.exit().remove(), grid.x = grid.x.enter().append("line").attr("class", config_classes.xgrid).merge(grid.x), withoutUpdate || grid.x.each(function () { var grid = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this); Object.keys(state.xgridAttr).forEach(function (id) { grid.attr(id, state.xgridAttr[id]).style("opacity", function () { return grid.attr(isRotated ? "y1" : "x1") === (isRotated ? state.height : 0) ? "0" : "1"; }); }); }); }, updateYGrid: function updateYGrid() { var $$ = this, config = $$.config, state = $$.state, _$$$$el2 = $$.$el, grid = _$$$$el2.grid, main = _$$$$el2.main, isRotated = config.axis_rotated, gridValues = $$.axis.y.tickValues() || $$.scale.y.ticks(config.grid_y_ticks), pos = function (d) { return Math.ceil($$.scale.y(d)); }; grid.y = main.select("." + config_classes.ygrids).selectAll("." + config_classes.ygrid).data(gridValues), grid.y.exit().remove(), grid.y = grid.y.enter().append("line").attr("class", config_classes.ygrid).merge(grid.y), grid.y.attr("x1", isRotated ? pos : 0).attr("x2", isRotated ? pos : state.width).attr("y1", isRotated ? 0 : pos).attr("y2", isRotated ? state.height : pos), smoothLines(grid.y, "grid"); }, updateGrid: function updateGrid(duration) { var $$ = this, _$$$$el3 = $$.$el, grid = _$$$$el3.grid, gridLines = _$$$$el3.gridLines; // hide if arc type gridLines.main || $$.initGridLines(), grid.main.style("visibility", $$.hasArcType() ? "hidden" : "visible"), $$.hideGridFocus(), $$.updateXGridLines(duration), $$.updateYGridLines(duration); }, /** * Update X Grid lines * @param {number} duration Dration value * @private */ updateXGridLines: function updateXGridLines(duration) { var $$ = this, config = $$.config, _$$$$el4 = $$.$el, gridLines = _$$$$el4.gridLines, main = _$$$$el4.main, isRotated = config.axis_rotated; config.grid_x_show && $$.updateXGrid(); var xLines = main.select("." + config_classes.xgridLines).selectAll("." + config_classes.xgridLine).data(config.grid_x_lines); // exit xLines.exit().transition().duration(duration).style("opacity", "0").remove(); // enter var xgridLine = xLines.enter().append("g"); xgridLine.append("line").style("opacity", "0"), xgridLine.append("text").attr("transform", isRotated ? "" : "rotate(-90)").attr("dy", -5).style("opacity", "0"), xLines = xgridLine.merge(xLines), xLines.attr("class", function (d) { return (config_classes.xgridLine + " " + (d.class || "")).trim(); }).select("text").attr("text-anchor", getGridTextAnchor).attr("dx", getGridTextDx).transition().duration(duration).text(function (d) { return d.text; }).transition().style("opacity", "1"), gridLines.x = xLines; }, /** * Update Y Grid lines * @param {number} duration Duration value * @private */ updateYGridLines: function updateYGridLines(duration) { var $$ = this, config = $$.config, _$$$state = $$.state, width = _$$$state.width, height = _$$$state.height, $el = $$.$el, isRotated = config.axis_rotated; config.grid_y_show && $$.updateYGrid(); var ygridLines = $el.main.select("." + config_classes.ygridLines).selectAll("." + config_classes.ygridLine).data(config.grid_y_lines); // exit ygridLines.exit().transition().duration(duration).style("opacity", "0").remove(); // enter var ygridLine = ygridLines.enter().append("g"); ygridLine.append("line").style("opacity", "0"), ygridLine.append("text").attr("transform", isRotated ? "rotate(-90)" : "").style("opacity", "0"), ygridLines = ygridLine.merge(ygridLines); // update var yv = $$.yv.bind($$); ygridLines.attr("class", function (d) { return (config_classes.ygridLine + " " + (d.class || "")).trim(); }).select("line").transition().duration(duration).attr("x1", isRotated ? yv : 0).attr("x2", isRotated ? yv : width).attr("y1", isRotated ? 0 : yv).attr("y2", isRotated ? height : yv).transition().style("opacity", "1"), ygridLines.select("text").attr("text-anchor", getGridTextAnchor).attr("dx", getGridTextDx).transition().duration(duration).attr("dy", -5).attr("x", getGridTextX(isRotated, width, height)).attr("y", yv).text(function (d) { return d.text; }).transition().style("opacity", "1"), $el.gridLines.y = ygridLines; }, redrawGrid: function redrawGrid(withTransition) { var $$ = this, isRotated = $$.config.axis_rotated, _$$$state2 = $$.state, width = _$$$state2.width, height = _$$$state2.height, gridLines = $$.$el.gridLines, xv = $$.xv.bind($$), lines = gridLines.x.select("line"), texts = gridLines.x.select("text"); return lines = (withTransition ? lines.transition() : lines).attr("x1", isRotated ? 0 : xv).attr("x2", isRotated ? width : xv).attr("y1", isRotated ? xv : 0).attr("y2", isRotated ? xv : height), texts = (withTransition ? texts.transition() : texts).attr("x", getGridTextX(!isRotated, width, height)).attr("y", xv).text(function (d) { return d.text; }), [lines.style("opacity", "1"), texts.style("opacity", "1")]; }, initFocusGrid: function initFocusGrid() { var $$ = this, config = $$.config, clip = $$.state.clip, $el = $$.$el, isFront = config.grid_front, className = "." + config_classes[isFront && $el.gridLines.main ? "gridLines" : "chart"] + (isFront ? " + *" : ""), grid = $el.main.insert("g", className).attr("clip-path", clip.pathGrid).attr("class", config_classes.grid); $el.grid.main = grid, config.grid_x_show && grid.append("g").attr("class", config_classes.xgrids), config.grid_y_show && grid.append("g").attr("class", config_classes.ygrids), config.interaction_enabled && config.grid_focus_show && (grid.append("g").attr("class", config_classes.xgridFocus).append("line").attr("class", config_classes.xgridFocus), config.grid_focus_y && !config.tooltip_grouped && grid.append("g").attr("class", config_classes.ygridFocus).append("line").attr("class", config_classes.ygridFocus)); }, /** * Show grid focus line * @param {Array} data Selected data * @private */ showGridFocus: function showGridFocus(data) { var $$ = this, config = $$.config, _$$$state3 = $$.state, width = _$$$state3.width, height = _$$$state3.height, isRotated = config.axis_rotated, focusEl = $$.$el.main.selectAll("line." + config_classes.xgridFocus + ", line." + config_classes.ygridFocus), dataToShow = (data || [focusEl.datum()]).filter(function (d) { return d && isValue($$.getBaseValue(d)); }); // Hide when bubble/scatter/stanford plot exists if (!(!config.tooltip_show || dataToShow.length === 0 || $$.hasType("bubble") || $$.hasArcType())) { var isEdge = config.grid_focus_edge && !config.tooltip_grouped, xx = $$.xx.bind($$); focusEl.style("visibility", "visible").data(dataToShow.concat(dataToShow)).each(function (d) { var xy, el = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), pos = { x: xx(d), y: $$.getYScaleById(d.id)(d.value) }; if (el.classed(config_classes.xgridFocus)) xy = isRotated ? [null, // x1 pos.x, // y1 isEdge ? pos.y : width, // x2 pos.x // y2 ] : [pos.x, isEdge ? pos.y : null, pos.x, height];else { var isY2 = $$.axis.getId(d.id) === "y2"; xy = isRotated ? [pos.y, // x1 isEdge && !isY2 ? pos.x : null, // y1 pos.y, // x2 isEdge && isY2 ? pos.x : height // y2 ] : [isEdge && isY2 ? pos.x : null, pos.y, isEdge && !isY2 ? pos.x : width, pos.y]; } ["x1", "y1", "x2", "y2"].forEach(function (v, i) { return el.attr(v, xy[i]); }); }), smoothLines(focusEl, "grid"), $$.showCircleFocus && $$.showCircleFocus(data); } }, hideGridFocus: function hideGridFocus() { var $$ = this, _$$$state4 = $$.state, inputType = _$$$state4.inputType, resizing = _$$$state4.resizing, main = $$.$el.main; inputType !== "mouse" && resizing || (main.selectAll("line." + config_classes.xgridFocus + ", line." + config_classes.ygridFocus).style("visibility", "hidden"), $$.hideCircleFocus && $$.hideCircleFocus()); }, updateGridFocus: function updateGridFocus() { var $$ = this, _$$$state5 = $$.state, inputType = _$$$state5.inputType, width = _$$$state5.width, height = _$$$state5.height, resizing = _$$$state5.resizing, grid = $$.$el.grid, xgridFocus = grid.main.select("line." + config_classes.xgridFocus); if (inputType === "touch") xgridFocus.empty() ? resizing && $$.showCircleFocus() : $$.showGridFocus();else { var _isRotated = $$.config.axis_rotated; xgridFocus.attr("x1", _isRotated ? 0 : -10).attr("x2", _isRotated ? width : -10).attr("y1", _isRotated ? -10 : 0).attr("y2", _isRotated ? -10 : height); } // need to return 'true' as of being pushed to the redraw list // ref: getRedrawList() return !0; }, generateGridData: function generateGridData(type, scale) { var $$ = this, tickNum = $$.$el.main.select("." + config_classes.axisX).selectAll(".tick").size(), gridData = []; if (type === "year") { var xDomain = $$.getXDomain(), firstYear = xDomain[0].getFullYear(), lastYear = xDomain[1].getFullYear(); for (var i = firstYear; i <= lastYear; i++) gridData.push(new Date(i + "-01-01 00:00:00")); } else gridData = scale.ticks(10), gridData.length > tickNum && (gridData = gridData.filter(function (d) { return (d + "").indexOf(".") < 0; })); return gridData; }, getGridFilterToRemove: function getGridFilterToRemove(params) { return params ? function (line) { var found = !1; return (isArray(params) ? params.concat() : [params]).forEach(function (param) { ("value" in param && line.value === param.value || "class" in param && line.class === param.class) && (found = !0); }), found; } : function () { return !0; }; }, removeGridLines: function removeGridLines(params, forX) { var $$ = this, config = $$.config, toRemove = $$.getGridFilterToRemove(params), classLines = forX ? config_classes.xgridLines : config_classes.ygridLines, classLine = forX ? config_classes.xgridLine : config_classes.ygridLine; $$.$el.main.select("." + classLines).selectAll("." + classLine).filter(toRemove).transition().duration(config.transition_duration).style("opacity", "0").remove(); var gridLines = "grid_" + (forX ? "x" : "y") + "_lines"; config[gridLines] = config[gridLines].filter(function toShow(line) { return !toRemove(line); }); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/region.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // selection /* harmony default export */ var region = ({ initRegion: function initRegion() { var $$ = this, $el = $$.$el; $el.region.main = $el.main.append("g").attr("clip-path", $$.state.clip.path).attr("class", config_classes.regions); }, updateRegion: function updateRegion(duration) { var $$ = this, config = $$.config, $el = $$.$el; $el.region.main || $$.initRegion(), $el.region.main.style("visibility", $$.hasArcType() ? "hidden" : "visible"); // select <g> element var list = $el.main.select("." + config_classes.regions).selectAll("." + config_classes.region).data(config.regions); list.exit().transition().duration(duration).style("opacity", "0").remove(), list = list.enter().append("g").merge(list).attr("class", $$.classRegion.bind($$)), list.append("rect").style("fill-opacity", "0"), $el.region.list = list; }, redrawRegion: function redrawRegion(withTransition) { var $$ = this, regions = $$.$el.region.list.select("rect"); return regions = (withTransition ? regions.transition() : regions).attr("x", $$.regionX.bind($$)).attr("y", $$.regionY.bind($$)).attr("width", $$.regionWidth.bind($$)).attr("height", $$.regionHeight.bind($$)), [(withTransition ? regions.transition() : regions).style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : "0.1"; }).on("end", function () { (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this.parentNode).selectAll("rect:not([x])").remove(); })]; }, getRegionXY: function getRegionXY(type, d) { var currScale, $$ = this, config = $$.config, scale = $$.scale, isRotated = config.axis_rotated, isX = type === "x", key = "start", pos = 0; return d.axis === "y" || d.axis === "y2" ? (!isX && (key = "end"), (isX ? isRotated : !isRotated) && key in d && (currScale = scale[d.axis], pos = currScale(d[key]))) : (isX ? !isRotated : isRotated) && key in d && (currScale = scale.zoom || scale.x, pos = currScale($$.axis.isTimeSeries() ? parseDate.call($$, d[key]) : d[key])), pos; }, regionX: function regionX(d) { return this.getRegionXY("x", d); }, regionY: function regionY(d) { return this.getRegionXY("y", d); }, getRegionSize: function getRegionSize(type, d) { var currScale, $$ = this, config = $$.config, scale = $$.scale, state = $$.state, isRotated = config.axis_rotated, isWidth = type === "width", start = $$[isWidth ? "regionX" : "regionY"](d), key = "end", end = state[type]; return d.axis === "y" || d.axis === "y2" ? (!isWidth && (key = "start"), (isWidth ? isRotated : !isRotated) && key in d && (currScale = scale[d.axis], end = currScale(d[key]))) : (isWidth ? !isRotated : isRotated) && key in d && (currScale = scale.zoom || scale.x, end = currScale($$.axis.isTimeSeries() ? parseDate.call($$, d[key]) : d[key])), end < start ? 0 : end - start; }, regionWidth: function regionWidth(d) { return this.getRegionSize("width", d); }, regionHeight: function regionHeight(d) { return this.getRegionSize("height", d); }, isRegionOnX: function isRegionOnX(d) { return !d.axis || d.axis === "x"; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/size.axis.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var size_axis = ({ /** * Get Axis size according its position * @param {string} id Axis id value - x, y or y2 * @returns {number} size Axis size value * @private */ getAxisSize: function getAxisSize(id) { var $$ = this, isRotated = $$.config.axis_rotated; return isRotated && id === "x" || !isRotated && /y2?/.test(id) ? $$.getAxisWidthByAxisId(id, !0) : $$.getHorizontalAxisHeight(id); }, getAxisWidthByAxisId: function getAxisWidthByAxisId(id, withoutRecompute) { var $$ = this; if ($$.axis) { var position = $$.axis && $$.axis.getLabelPositionById(id); return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40); } return 40; }, getHorizontalAxisHeight: function getHorizontalAxisHeight(id) { var $$ = this, config = $$.config, state = $$.state, _state = state, current = _state.current, rotatedPadding = _state.rotatedPadding, isLegendRight = _state.isLegendRight, isLegendInset = _state.isLegendInset, isRotated = config.axis_rotated, h = 30; if (id === "x" && !config.axis_x_show) return 8; if (id === "x" && config.axis_x_height) return config.axis_x_height; if (id === "y" && !config.axis_y_show) return !config.legend_show || isLegendRight || isLegendInset ? 1 : 10; if (id === "y2" && !config.axis_y2_show) return rotatedPadding.top; var rotate = $$.getAxisTickRotate(id); // Calculate x/y axis height when tick rotated return (id === "x" && !isRotated || /y2?/.test(id) && isRotated) && rotate && (h = 30 + $$.axis.getMaxTickWidth(id) * Math.cos(Math.PI * (90 - Math.abs(rotate)) / 180), !config.axis_x_tick_multiline && current.height && h > current.height / 2 && (h = current.height / 2)), h + ($$.axis.getLabelPositionById(id).isInner ? 0 : 10) + (id !== "y2" || isRotated ? 0 : -10); }, getEventRectWidth: function getEventRectWidth() { return Math.max(0, this.axis.x.tickInterval()); }, /** * Get axis tick test rotate value * @param {string} id Axis id * @returns {number} rotate value * @private */ getAxisTickRotate: function getAxisTickRotate(id) { var $$ = this, axis = $$.axis, config = $$.config, state = $$.state, $el = $$.$el, rotate = config["axis_" + id + "_tick_rotate"]; if (id === "x") { var allowedXAxisTypes = axis.isCategorized() || axis.isTimeSeries(); if (config.axis_x_tick_fit && allowedXAxisTypes) { var xTickCount = config.axis_x_tick_count, currentXTicksLength = state.current.maxTickWidths.x.ticks.length, tickCount = 0; xTickCount ? tickCount = xTickCount > currentXTicksLength ? currentXTicksLength : xTickCount : currentXTicksLength && (tickCount = currentXTicksLength), tickCount !== state.axis.x.tickCount && (state.axis.x.padding = $$.axis.getXAxisPadding(tickCount)), state.axis.x.tickCount = tickCount; } $el.svg && config.axis_x_tick_fit && !config.axis_x_tick_multiline && !config.axis_x_tick_culling && config.axis_x_tick_autorotate && allowedXAxisTypes && (rotate = $$.needToRotateXAxisTickTexts() ? config.axis_x_tick_rotate : 0); } return rotate; }, /** * Check weather axis tick text needs to be rotated * @returns {boolean} * @private */ needToRotateXAxisTickTexts: function needToRotateXAxisTickTexts() { var $$ = this, _$$$state = $$.state, axis = _$$$state.axis, current = _$$$state.current, xAxisLength = current.width - $$.getCurrentPaddingLeft(!1) - $$.getCurrentPaddingRight(), tickCountWithPadding = axis.x.tickCount + axis.x.padding.left + axis.x.padding.right, maxTickWidth = $$.axis.getMaxTickWidth("x"), tickLength = tickCountWithPadding ? xAxisLength / tickCountWithPadding : 0; return maxTickWidth > tickLength; } }); ;// CONCATENATED MODULE: ./src/config/Options/data/axis.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Axis based chart data config options */ /* harmony default export */ var data_axis = ({ /** * Specify the keys of the x values for each data.<br><br> * This option can be used if we want to show the data that has different x values. * @name dataβ€€xs * @memberof Options * @type {object} * @default {} * @example * data: { * xs: { * data1: "x1", * data2: "x2" * } * } */ data_xs: {}, /** * Set a format specifier to parse string specifed as x. * @name dataβ€€xFormat * @memberof Options * @type {string} * @default %Y-%m-%d * @example * data: { * x: "x", * columns: [ * ["x", "01012019", "02012019", "03012019"], * ["data1", 30, 200, 100] * ], * // Format specifier to parse as datetime for given 'x' string value * xFormat: "%m%d%Y" * }, * axis: { * x: { * type: "timeseries" * } * } * @see [D3's time specifier](https://github.com/d3/d3-time-format#locale_format) */ data_xFormat: "%Y-%m-%d", /** * Set localtime format to parse x axis. * @name dataβ€€xLocaltime * @memberof Options * @type {boolean} * @default true * @example * data: { * xLocaltime: false * } */ data_xLocaltime: !0, /** * Sort on x axis. * @name dataβ€€xSort * @memberof Options * @type {boolean} * @default true * @example * data: { * xSort: false * } */ data_xSort: !0, /** * Set y axis the data related to. y and y2 can be used. * - **NOTE:** If all data is related to one of the axes, the domain of axis without related data will be replaced by the domain from the axis with related data * @name dataβ€€axes * @memberof Options * @type {object} * @default {} * @example * data: { * axes: { * data1: "y", * data2: "y2" * } * } */ data_axes: {}, /** * Define regions for each data.<br> * The values must be an array for each data and it should include an object that has `start`, `end` and `style`. * - The object type should be as: * - start {number}: Start data point number. If not set, the start will be the first data point. * - [end] {number}: End data point number. If not set, the end will be the last data point. * - [style.dasharray="2 2"] {object}: The first number specifies a distance for the filled area, and the second a distance for the unfilled area. * - **NOTE:** Currently this option supports only line chart and dashed style. If this option specified, the line will be dashed only in the regions. * @name dataβ€€regions * @memberof Options * @type {object} * @default {} * @example * data: { * regions: { * data1: [{ * start: 1, * end: 2, * style: { * dasharray: "5 2" * } * }, { * start: 3 * }], * ... * } * } */ data_regions: {}, /** * Set the stacking to be normalized * - **NOTE:** * - For stacking, '[data.groups](#.data%25E2%2580%25A4groups)' option should be set * - y Axis will be set in percentage value (0 ~ 100%) * - Must have postive values * @name dataβ€€stackβ€€normalize * @memberof Options * @type {boolean} * @default false * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.DataStackNormalized) * @example * data: { * stack: { * normalize: true * } * } */ data_stack_normalize: !1 }); ;// CONCATENATED MODULE: ./src/config/Options/axis/x.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * x Axis config options */ /* harmony default export */ var axis_x = ({ /** * Set clip-path attribute for x axis element * @name axisβ€€xβ€€clipPath * @memberof Options * @type {boolean} * @default true * @see [Demo]() * @example * // don't set 'clip-path' attribute * clipPath: false */ axis_x_clipPath: !0, /** * Show or hide x axis. * @name axisβ€€xβ€€show * @memberof Options * @type {boolean} * @default true * @example * axis: { * x: { * show: false * } * } */ axis_x_show: !0, /** * Set type of x axis.<br><br> * **Available Values:** * - category * - indexed * - log * - timeseries * * **NOTE:**<br> * - **log** type: * - the x values specified by [`data.x`](#.data%25E2%2580%25A4x)(or by any equivalent option), must be exclusively-positive. * - x axis min value should be >= 0. * * @name axisβ€€xβ€€type * @memberof Options * @type {string} * @default indexed * @see [Demo: indexed](https://naver.github.io/billboard.js/demo/#Chart.AreaChart) * @see [Demo: timeseries](https://naver.github.io/billboard.js/demo/#Chart.TimeseriesChart) * @see [Demo: category](https://naver.github.io/billboard.js/demo/#Data.CategoryData) * @see [Demo: log](https://naver.github.io/billboard.js/demo/#Axis.LogScales) * @example * axis: { * x: { * type: "timeseries" * } * } */ axis_x_type: "indexed", /** * Set how to treat the timezone of x values.<br> * If true, treat x value as localtime. If false, convert to UTC internally. * @name axisβ€€xβ€€localtime * @memberof Options * @type {boolean} * @default true * @example * axis: { * x: { * localtime: false * } * } */ axis_x_localtime: !0, /** * Set category names on category axis. * This must be an array that includes category names in string. If category names are included in the date by data.x option, this is not required. * @name axisβ€€xβ€€categories * @memberof Options * @type {Array} * @default [] * @example * axis: { * x: { * categories: ["Category 1", "Category 2", ...] * } * } */ axis_x_categories: [], /** * centerize ticks on category axis. * @name axisβ€€xβ€€tickβ€€centered * @memberof Options * @type {boolean} * @default false * @example * axis: { * x: { * tick: { * centered: true * } * } * } */ axis_x_tick_centered: !1, /** * A function to format tick value. Format string is also available for timeseries data. * @name axisβ€€xβ€€tickβ€€format * @memberof Options * @type {Function|string} * @default undefined * @see [D3's time specifier](https://github.com/d3/d3-time-format#locale_format) * @example * axis: { * x: { * tick: { * // for timeseries, a 'datetime' object is given as parameter * format: function(x) { * return x.getFullYear(); * } * * // for category, index(Number) and categoryName(String) are given as parameter * format: function(index, categoryName) { * return categoryName.substr(0, 10); * }, * * // for timeseries format specifier * format: "%Y-%m-%d %H:%M:%S" * } * } * } */ axis_x_tick_format: undefined, /** * Setting for culling ticks.<br><br> * If true is set, the ticks will be culled, then only limitted tick text will be shown. This option does not hide the tick lines. If false is set, all of ticks will be shown.<br><br> * We can change the number of ticks to be shown by axis.x.tick.culling.max. * @name axisβ€€xβ€€tickβ€€culling * @memberof Options * @type {boolean} * @default * - true for indexed axis and timeseries axis * - false for category axis * @example * axis: { * x: { * tick: { * culling: false * } * } * } */ axis_x_tick_culling: {}, /** * The number of tick texts will be adjusted to less than this value. * @name axisβ€€xβ€€tickβ€€cullingβ€€max * @memberof Options * @type {number} * @default 10 * @example * axis: { * x: { * tick: { * culling: { * max: 5 * } * } * } * } */ axis_x_tick_culling_max: 10, /** * The number of x axis ticks to show.<br><br> * This option hides tick lines together with tick text. If this option is used on timeseries axis, the ticks position will be determined precisely and not nicely positioned (e.g. it will have rough second value). * @name axisβ€€xβ€€tickβ€€count * @memberof Options * @type {number} * @default undefined * @example * axis: { * x: { * tick: { * count: 5 * } * } * } */ axis_x_tick_count: undefined, /** * Show or hide x axis tick line. * @name axisβ€€xβ€€tickβ€€show * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.HideTickLineText) * @example * axis: { * x: { * tick: { * show: false * } * } * } */ axis_x_tick_show: !0, /** * Show or hide x axis tick text. * @name axisβ€€xβ€€tickβ€€textβ€€show * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.HideTickLineText) * @example * axis: { * x: { * tick: { * text: { * show: false * } * } * } * } */ axis_x_tick_text_show: !0, /** * Set the x Axis tick text's position relatively its original position * @name axisβ€€xβ€€tickβ€€textβ€€position * @memberof Options * @type {object} * @default {x: 0, y:0} * @example * axis: { * x: { * tick: { * text: { * position: { * x: 10, * y: 10 * } * } * } * } * } */ axis_x_tick_text_position: { x: 0, y: 0 }, /** * Fit x axis ticks. * - **true**: ticks will be positioned nicely to have same intervals. * - **false**: ticks will be positioned according to x value of the data points. * @name axisβ€€xβ€€tickβ€€fit * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.XAxisTickFitting) * @see [Demo: for timeseries zoom](https://naver.github.io/billboard.js/demo/#Axis.XAxisTickTimeseries) * @example * axis: { * x: { * tick: { * fit: false * } * } * } */ axis_x_tick_fit: !0, /** * Set the x values of ticks manually.<br><br> * If this option is provided, the position of the ticks will be determined based on those values.<br> * This option works with `timeseries` data and the x values will be parsed accoding to the type of the value and data.xFormat option. * @name axisβ€€xβ€€tickβ€€values * @memberof Options * @type {Array|Function} * @default null * @example * axis: { * x: { * tick: { * values: [1, 2, 4, 8, 16, 32, ...], * * // an Array value should be returned * values: function() { * return [ ... ]; * } * } * } * } */ axis_x_tick_values: null, /** * Rotate x axis tick text if there is not enough space for 'category' and 'timeseries' type axis. * - **NOTE:** The conditions where `autorotate` is enabled are: * - axis.x.type='category' or 'timeseries * - axis.x.tick.multiline=false * - axis.x.tick.culling=false * - axis.x.tick.fit=true * - **NOTE:** axis.x.tick.clippath=false is necessary for calculating the overflow padding between the end of x axis and the width of the SVG * @name axisβ€€xβ€€tickβ€€autorotate * @memberof Options * @type {boolean} * @default false * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.XAxisTickAutorotate) * @example * axis: { * x: { * tick: { * rotate: 15, * autorotate: true, * multiline: false, * culling: false, * fit: true * }, * clipPath: false * } * } */ axis_x_tick_autorotate: !1, /** * Rotate x axis tick text. * - If you set negative value, it will rotate to opposite direction. * - Applied when [`axis.rotated`](#.axis%25E2%2580%25A4rotated) option is `false`. * - As long as `axis_x_tick_fit` is set to `true` it will calculate an overflow for the y2 axis and add this value to the right padding. * @name axisβ€€xβ€€tickβ€€rotate * @memberof Options * @type {number} * @default 0 * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.RotateXAxisTickText) * @example * axis: { * x: { * tick: { * rotate: 60 * } * } * } */ axis_x_tick_rotate: 0, /** * Show x axis outer tick. * @name axisβ€€xβ€€tickβ€€outer * @memberof Options * @type {boolean} * @default true * @example * axis: { * x: { * tick: { * outer: false * } * } * } */ axis_x_tick_outer: !0, /** * Set tick text to be multiline * - **NOTE:** * > When x tick text contains `\n`, it's used as line break and 'axis.x.tick.width' option is ignored. * @name axisβ€€xβ€€tickβ€€multiline * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.XAxisTickMultiline) * @example * axis: { * x: { * tick: { * multiline: false * } * } * } * @example * // example of line break with '\n' * // In this case, 'axis.x.tick.width' is ignored * data: { * x: "x", * columns: [ * ["x", "long\ntext", "Another\nLong\nText"], * ... * ], * } */ axis_x_tick_multiline: !0, /** * Set tick width * - **NOTE:** * > When x tick text contains `\n`, this option is ignored. * @name axisβ€€xβ€€tickβ€€width * @memberof Options * @type {number} * @default null * @example * axis: { * x: { * tick: { * width: 50 * } * } * } */ axis_x_tick_width: null, /** * Set to display system tooltip(via 'title' attribute) for tick text * - **NOTE:** Only available for category axis type (`axis.x.type='category'`) * @name axisβ€€xβ€€tickβ€€tooltip * @memberof Options * @type {boolean} * @default false * @example * axis: { * x: { * tick: { * tooltip: true * } * } * } */ axis_x_tick_tooltip: !1, /** * Set max value of x axis range. * @name axisβ€€xβ€€max * @memberof Options * @property {number} max Set the max value * @property {boolean} [max.fit=false] When specified `max.value` is greater than the bound data value, setting `true` will make x axis max to be fitted to the bound data max value. * - **NOTE:** If the bound data max value is greater than the `max.value`, the x axis max will be limited as the given `max.value`. * @property {number} [max.value] Set the max value * @example * axis: { * x: { * max: 100, * * max: { * // 'fit=true' will make x axis max to be limited as the bound data value max when 'max.value' is greater. * // - when bound data max is '10' and max.value: '100' ==> x axis max will be '10' * // - when bound data max is '1000' and max.value: '100' ==> x axis max will be '100' * fit: true, * value: 100 * } * } * } */ axis_x_max: undefined, /** * Set min value of x axis range. * @name axisβ€€xβ€€min * @memberof Options * @property {number} min Set the min value * @property {boolean} [min.fit=false] When specified `min.value` is lower than the bound data value, setting `true` will make x axis min to be fitted to the bound data min value. * - **NOTE:** If the bound data min value is lower than the `min.value`, the x axis min will be limited as the given `min.value`. * @property {number} [min.value] Set the min value * @example * axis: { * x: { * min: -100, * * min: { * // 'fit=true' will make x axis min to be limited as the bound data value min when 'min.value' is lower. * // - when bound data min is '-10' and min.value: '-100' ==> x axis min will be '-10' * // - when bound data min is '-1000' and min.value: '-100' ==> x axis min will be '-100' * fit: true, * value: -100 * } * } * } */ axis_x_min: undefined, /** * Set padding for x axis.<br><br> * If this option is set, the range of x axis will increase/decrease according to the values. * If no padding is needed in the rage of x axis, 0 should be set. * - **NOTE:** * The padding values aren't based on pixels. It differs according axis types<br> * - **category:** The unit of tick value * ex. the given value `1`, is same as the width of 1 tick width * - **timeseries:** Numeric time value * ex. the given value `1000*60*60*24`, which is numeric time equivalent of a day, is same as the width of 1 tick width * @name axisβ€€xβ€€padding * @memberof Options * @type {object|number} * @default {} * @example * axis: { * x: { * padding: { * // when axis type is 'category' * left: 1, // set left padding width of equivalent value of a tick's width * right: 0.5 // set right padding width as half of equivalent value of tick's width * * // when axis type is 'timeseries' * left: 1000*60*60*24, // set left padding width of equivalent value of a day tick's width * right: 1000*60*60*12 // set right padding width as half of equivalent value of a day tick's width * }, * * // or set both values at once. * padding: 10 * } * } */ axis_x_padding: {}, /** * Set height of x axis.<br><br> * The height of x axis can be set manually by this option. If you need more space for x axis, please use this option for that. The unit is pixel. * @name axisβ€€xβ€€height * @memberof Options * @type {number} * @default undefined * @example * axis: { * x: { * height: 20 * } * } */ axis_x_height: undefined, /** * Set default extent for subchart and zoom. This can be an array or function that returns an array. * @name axisβ€€xβ€€extent * @memberof Options * @type {Array|Function} * @default undefined * @example * axis: { * x: { * // extent range as a pixel value * extent: [0, 200], * * // when axis is 'timeseries', parsable datetime string * extent: ["2019-03-01", "2019-03-05"], * * // return extent value * extent: function(domain, scale) { * var extent = domain.map(function(v) { * return scale(v); * }); * * // it should return a format of array * // ex) [0, 584] * return extent; * } * } * } */ axis_x_extent: undefined, /** * Set label on x axis.<br><br> * You can set x axis label and change its position by this option. * `string` and `object` can be passed and we can change the poisiton by passing object that has position key.<br> * Available position differs according to the axis direction (vertical or horizontal). * If string set, the position will be the default. * * - **If it's horizontal axis:** * - inner-right [default] * - inner-center * - inner-left * - outer-right * - outer-center * - outer-left * - **If it's vertical axis:** * - inner-top [default] * - inner-middle * - inner-bottom * - outer-top * - outer-middle * - outer-bottom * @name axisβ€€xβ€€label * @memberof Options * @type {string|object} * @default undefined * @example * axis: { * x: { * label: "Your X Axis" * } * } * * axis: { * x: { * label: { * text: "Your X Axis", * position: "outer-center" * } * } * } */ axis_x_label: {}, /** * Set additional axes for x Axis. * - **NOTE:** Axis' scale is based on x Axis value if domain option isn't set. * * Each axis object should consist with following options: * * | Name | Type | Default | Description | * | --- | --- | --- | --- | * | domain | Array | - | Set the domain value | * | tick.outer | boolean | true | Show outer tick | * | tick.format | Function | - | Set formatter for tick text | * | tick.count | Number | - | Set the number of y axis ticks | * | tick.values | Array | - | Set tick values manually | * @name axisβ€€xβ€€axes * @memberof Options * @type {Array} * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.MultiAxes) * @see [Demo: Domain](https://naver.github.io/billboard.js/demo/#Axis.MultiAxesDomain) * @example * x: { * axes: [ * { * // if set, will not be correlated with the main x Axis domain value * domain: [0, 1000], * tick: { * outer: false, * format: function(x) { * return x + "%"; * }, * count: 2, * values: [10, 20, 30] * } * }, * ... * ] * } */ axis_x_axes: [] }); ;// CONCATENATED MODULE: ./src/config/Options/axis/y.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * y Axis config options */ /* harmony default export */ var y = ({ /** * Set clip-path attribute for y axis element * - **NOTE**: `clip-path` attribute for y Axis is set only when `axis.y.inner` option is true. * @name axisβ€€yβ€€clipPath * @memberof Options * @type {boolean} * @default true * @example * // don't set 'clip-path' attribute * clipPath: false */ axis_y_clipPath: !0, /** * Show or hide y axis. * @name axisβ€€yβ€€show * @memberof Options * @type {boolean} * @default true * @example * axis: { * y: { * show: false * } * } */ axis_y_show: !0, /** * Set type of y axis.<br><br> * **Available Values:** * - indexed * - log * - timeseries * * **NOTE:**<br> * - **log** type: * - the bound data values must be exclusively-positive. * - y axis min value should be >= 0. * - [`data.groups`](#.data%25E2%2580%25A4groups)(stacked data) option aren't supported. * * @name axisβ€€yβ€€type * @memberof Options * @type {string} * @default "indexed" * @see [Demo: log](https://naver.github.io/billboard.js/demo/#Axis.LogScales) * @example * axis: { * y: { * type: "log" * } * } */ axis_y_type: "indexed", /** * Set max value of y axis. * - **NOTE:** Padding will be added based on this value, so if you don't need the padding, please set axis.y.padding to disable it (e.g. axis.y.padding = 0). * @name axisβ€€yβ€€max * @memberof Options * @type {number} * @default undefined * @example * axis: { * y: { * max: 1000 * } * } */ axis_y_max: undefined, /** * Set min value of y axis. * - **NOTE:** * Padding will be added based on this value, so if you don't need the padding, please set axis.y.padding to disable it (e.g. axis.y.padding = 0). * @name axisβ€€yβ€€min * @memberof Options * @type {number} * @default undefined * @example * axis: { * y: { * min: 1000 * } * } */ axis_y_min: undefined, /** * Change the direction of y axis.<br><br> * If true set, the direction will be from the top to the bottom. * @name axisβ€€yβ€€inverted * @memberof Options * @type {boolean} * @default false * @example * axis: { * y: { * inverted: true * } * } */ axis_y_inverted: !1, /** * Set center value of y axis. * @name axisβ€€yβ€€center * @memberof Options * @type {number} * @default undefined * @example * axis: { * y: { * center: 0 * } * } */ axis_y_center: undefined, /** * Show y axis inside of the chart. * @name axisβ€€yβ€€inner * @memberof Options * @type {boolean} * @default false * @example * axis: { * y: { * inner: true * } * } */ axis_y_inner: !1, /** * Set label on y axis.<br><br> * You can set y axis label and change its position by this option. This option works in the same way as [axis.x.label](#.axis%25E2%2580%25A4x%25E2%2580%25A4label). * @name axisβ€€yβ€€label * @memberof Options * @type {string|object} * @default {} * @see [axis.x.label](#.axis%25E2%2580%25A4x%25E2%2580%25A4label) for position string value. * @example * axis: { * y: { * label: "Your Y Axis" * } * } * * axis: { * y: { * label: { * text: "Your Y Axis", * position: "outer-middle" * } * } * } */ axis_y_label: {}, /** * Set formatter for y axis tick text.<br><br> * This option accepts d3.format object as well as a function you define. * @name axisβ€€yβ€€tickβ€€format * @memberof Options * @type {Function} * @default undefined * @example * axis: { * y: { * tick: { * format: function(x) { * return x.getFullYear(); * } * } * } * } */ axis_y_tick_format: undefined, /** * Setting for culling ticks.<br><br> * If true is set, the ticks will be culled, then only limitted tick text will be shown. This option does not hide the tick lines. If false is set, all of ticks will be shown.<br><br> * We can change the number of ticks to be shown by axis.y.tick.culling.max. * @name axisβ€€yβ€€tickβ€€culling * @memberof Options * @type {boolean} * @default false * @example * axis: { * y: { * tick: { * culling: false * } * } * } */ axis_y_tick_culling: !1, /** * The number of tick texts will be adjusted to less than this value. * @name axisβ€€yβ€€tickβ€€cullingβ€€max * @memberof Options * @type {number} * @default 5 * @example * axis: { * y: { * tick: { * culling: { * max: 5 * } * } * } * } */ axis_y_tick_culling_max: 5, /** * Show y axis outer tick. * @name axisβ€€yβ€€tickβ€€outer * @memberof Options * @type {boolean} * @default true * @example * axis: { * y: { * tick: { * outer: false * } * } * } */ axis_y_tick_outer: !0, /** * Set y axis tick values manually. * @name axisβ€€yβ€€tickβ€€values * @memberof Options * @type {Array|Function} * @default null * @example * axis: { * y: { * tick: { * values: [100, 1000, 10000], * * // an Array value should be returned * values: function() { * return [ ... ]; * } * } * } * } */ axis_y_tick_values: null, /** * Rotate y axis tick text. * - If you set negative value, it will rotate to opposite direction. * - Applied when [`axis.rotated`](#.axis%25E2%2580%25A4rotated) option is `true`. * @name axisβ€€yβ€€tickβ€€rotate * @memberof Options * @type {number} * @default 0 * @example * axis: { * y: { * tick: { * rotate: 60 * } * } * } */ axis_y_tick_rotate: 0, /** * Set the number of y axis ticks.<br><br> * - **NOTE:** The position of the ticks will be calculated precisely, so the values on the ticks will not be rounded nicely. In the case, axis.y.tick.format or axis.y.tick.values will be helpful. * @name axisβ€€yβ€€tickβ€€count * @memberof Options * @type {number} * @default undefined * @example * axis: { * y: { * tick: { * count: 5 * } * } * } */ axis_y_tick_count: undefined, /** * Show or hide y axis tick line. * @name axisβ€€yβ€€tickβ€€show * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.HideTickLineText) * @example * axis: { * y: { * tick: { * show: false * } * } * } */ axis_y_tick_show: !0, /** * Set axis tick step(interval) size. * - **NOTE:** Will be ignored if `axis.y.tick.count` or `axis.y.tick.values` options are set. * @name axisβ€€yβ€€tickβ€€stepSize * @memberof Options * @type {number} * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.StepSizeForYAxis) * @example * axis: { * y: { * tick: { * // tick value will step as indicated interval value. * // ex) 'stepSize=15' ==> [0, 15, 30, 45, 60] * stepSize: 15 * } * } * } */ axis_y_tick_stepSize: null, /** * Show or hide y axis tick text. * @name axisβ€€yβ€€tickβ€€textβ€€show * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.HideTickLineText) * @example * axis: { * y: { * tick: { * text: { * show: false * } * } * } * } */ axis_y_tick_text_show: !0, /** * Set the y Axis tick text's position relatively its original position * @name axisβ€€yβ€€tickβ€€textβ€€position * @memberof Options * @type {object} * @default {x: 0, y:0} * @example * axis: { * y: { * tick: { * text: { * position: { * x: 10, * y: 10 * } * } * } * } * } */ axis_y_tick_text_position: { x: 0, y: 0 }, /** * Set the number of y axis ticks.<br><br> * - **NOTE:** The position of the ticks will be calculated precisely, so the values on the ticks will not be rounded nicely. In the case, axis.y.tick.format or axis.y.tick.values will be helpful. * @name axisβ€€yβ€€tickβ€€time * @memberof Options * @private * @type {object} * @property {object} time time object * @property {Function} [time.value] D3's time interval function (https://github.com/d3/d3-time#intervals) * @example * axis: { * y: { * tick: { * time: { * // ticks at 15-minute intervals * // https://github.com/d3/d3-scale/blob/master/README.md#time_ticks * value: d3.timeMinute.every(15) * } * } * } * } */ // @TODO: not fully implemented yet axis_y_tick_time_value: undefined, /** * Set padding for y axis.<br><br> * You can set padding for y axis to create more space on the edge of the axis. * This option accepts object and it can include top and bottom. top, bottom will be treated as pixels. * * - **NOTE:** * - Given values are translated relative to the y Axis domain value for padding * - For area and bar type charts, [area.zerobased](#.area) or [bar.zerobased](#.bar) options should be set to 'false` to get padded bottom. * @name axisβ€€yβ€€padding * @memberof Options * @type {object|number} * @default {} * @example * axis: { * y: { * padding: { * top: 0, * bottom: 0 * }, * * // or set both values at once. * padding: 10 * } * } */ axis_y_padding: {}, /** * Set default range of y axis.<br><br> * This option set the default value for y axis when there is no data on init. * @name axisβ€€yβ€€default * @memberof Options * @type {Array} * @default undefined * @example * axis: { * y: { * default: [0, 1000] * } * } */ axis_y_default: undefined, /** * Set additional axes for y Axis. * - **NOTE:** Axis' scale is based on y Axis value if domain option isn't set. * * Each axis object should consist with following options: * * | Name | Type | Default | Description | * | --- | --- | --- | --- | * | domain | Array | - | Set the domain value | * | tick.outer | boolean | true | Show outer tick | * | tick.format | Function | - | Set formatter for tick text | * | tick.count | Number | - | Set the number of y axis ticks | * | tick.values | Array | - | Set tick values manually | * @name axisβ€€yβ€€axes * @memberof Options * @type {Array} * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.MultiAxes) * @see [Demo: Domain](https://naver.github.io/billboard.js/demo/#Axis.MultiAxesDomain) * @example * y: { * axes: [ * { * // if set, will not be correlated with the main y Axis domain value * domain: [0, 1000], * tick: { * outer: false, * format: function(x) { * return x + "%"; * }, * count: 2, * values: [10, 20, 30] * } * }, * ... * ] * } */ axis_y_axes: [] }); ;// CONCATENATED MODULE: ./src/config/Options/axis/y2.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * y2 Axis config options */ /* harmony default export */ var y2 = ({ /** * Show or hide y2 axis. * - **NOTE**: * - When set to `false` will not generate y2 axis node. In this case, all 'y2' axis related functionality won't work properly. * - If need to use 'y2' related options while y2 isn't visible, set the value `true` and control visibility by css display property. * @name axisβ€€y2β€€show * @memberof Options * @type {boolean} * @default false * @example * axis: { * y2: { * show: true * } * } */ axis_y2_show: !1, /** * Set type of y2 axis.<br><br> * **Available Values:** * - indexed * - log * - timeseries * * **NOTE:**<br> * - **log** type: * - the bound data values must be exclusively-positive. * - y2 axis min value should be >= 0. * - [`data.groups`](#.data%25E2%2580%25A4groups)(stacked data) option aren't supported. * * @name axisβ€€y2β€€type * @memberof Options * @type {string} * @default "indexed" * @see [Demo: log](https://naver.github.io/billboard.js/demo/#Axis.LogScales) * @example * axis: { * y2: { * type: "indexed" * } * } */ axis_y2_type: "indexed", /** * Set max value of y2 axis. * @name axisβ€€y2β€€max * @memberof Options * @type {number} * @default undefined * @example * axis: { * y2: { * max: 1000 * } * } */ axis_y2_max: undefined, /** * Set min value of y2 axis. * @name axisβ€€y2β€€min * @memberof Options * @type {number} * @default undefined * @example * axis: { * y2: { * min: -1000 * } * } */ axis_y2_min: undefined, /** * Change the direction of y2 axis.<br><br> * If true set, the direction will be from the top to the bottom. * @name axisβ€€y2β€€inverted * @memberof Options * @type {boolean} * @default false * @example * axis: { * y2: { * inverted: true * } * } */ axis_y2_inverted: !1, /** * Set center value of y2 axis. * @name axisβ€€y2β€€center * @memberof Options * @type {number} * @default undefined * @example * axis: { * y2: { * center: 0 * } * } */ axis_y2_center: undefined, /** * Show y2 axis inside of the chart. * @name axisβ€€y2β€€inner * @memberof Options * @type {boolean} * @default false * @example * axis: { * y2: { * inner: true * } * } */ axis_y2_inner: !1, /** * Set label on y2 axis.<br><br> * You can set y2 axis label and change its position by this option. This option works in the same way as [axis.x.label](#.axis%25E2%2580%25A4x%25E2%2580%25A4label). * @name axisβ€€y2β€€label * @memberof Options * @type {string|object} * @default {} * @see [axis.x.label](#.axis%25E2%2580%25A4x%25E2%2580%25A4label) for position string value. * @example * axis: { * y2: { * label: "Your Y2 Axis" * } * } * * axis: { * y2: { * label: { * text: "Your Y2 Axis", * position: "outer-middle" * } * } * } */ axis_y2_label: {}, /** * Set formatter for y2 axis tick text.<br><br> * This option works in the same way as axis.y.format. * @name axisβ€€y2β€€tickβ€€format * @memberof Options * @type {Function} * @default undefined * @example * axis: { * y2: { * tick: { * format: d3.format("$,") * //or format: function(d) { return "$" + d; } * } * } * } */ axis_y2_tick_format: undefined, /** * Setting for culling ticks.<br><br> * If true is set, the ticks will be culled, then only limitted tick text will be shown. This option does not hide the tick lines. If false is set, all of ticks will be shown.<br><br> * We can change the number of ticks to be shown by axis.y.tick.culling.max. * @name axisβ€€y2β€€tickβ€€culling * @memberof Options * @type {boolean} * @default false * @example * axis: { * y2: { * tick: { * culling: false * } * } * } */ axis_y2_tick_culling: !1, /** * The number of tick texts will be adjusted to less than this value. * @name axisβ€€y2β€€tickβ€€cullingβ€€max * @memberof Options * @type {number} * @default 5 * @example * axis: { * y2: { * tick: { * culling: { * max: 5 * } * } * } * } */ axis_y2_tick_culling_max: 5, /** * Show or hide y2 axis outer tick. * @name axisβ€€y2β€€tickβ€€outer * @memberof Options * @type {boolean} * @default true * @example * axis: { * y2: { * tick: { * outer: false * } * } * } */ axis_y2_tick_outer: !0, /** * Set y2 axis tick values manually. * @name axisβ€€y2β€€tickβ€€values * @memberof Options * @type {Array|Function} * @default null * @example * axis: { * y2: { * tick: { * values: [100, 1000, 10000], * * // an Array value should be returned * values: function() { * return [ ... ]; * } * } * } * } */ axis_y2_tick_values: null, /** * Rotate y2 axis tick text. * - If you set negative value, it will rotate to opposite direction. * - Applied when [`axis.rotated`](#.axis%25E2%2580%25A4rotated) option is `true`. * @name axisβ€€y2β€€tickβ€€rotate * @memberof Options * @type {number} * @default 0 * @example * axis: { * y2: { * tick: { * rotate: 60 * } * } * } */ axis_y2_tick_rotate: 0, /** * Set the number of y2 axis ticks. * - **NOTE:** This works in the same way as axis.y.tick.count. * @name axisβ€€y2β€€tickβ€€count * @memberof Options * @type {number} * @default undefined * @example * axis: { * y2: { * tick: { * count: 5 * } * } * } */ axis_y2_tick_count: undefined, /** * Show or hide y2 axis tick line. * @name axisβ€€y2β€€tickβ€€show * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.HideTickLineText) * @example * axis: { * y2: { * tick: { * show: false * } * } * } */ axis_y2_tick_show: !0, /** * Set axis tick step(interval) size. * - **NOTE:** Will be ignored if `axis.y2.tick.count` or `axis.y2.tick.values` options are set. * @name axisβ€€y2β€€tickβ€€stepSize * @memberof Options * @type {number} * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.StepSizeForYAxis) * @example * axis: { * y2: { * tick: { * // tick value will step as indicated interval value. * // ex) 'stepSize=15' ==> [0, 15, 30, 45, 60] * stepSize: 15 * } * } * } */ axis_y2_tick_stepSize: null, /** * Show or hide y2 axis tick text. * @name axisβ€€y2β€€tickβ€€textβ€€show * @memberof Options * @type {boolean} * @default true * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.HideTickLineText) * @example * axis: { * y2: { * tick: { * text: { * show: false * } * } * } * } */ axis_y2_tick_text_show: !0, /** * Set the y2 Axis tick text's position relatively its original position * @name axisβ€€y2β€€tickβ€€textβ€€position * @memberof Options * @type {object} * @default {x: 0, y:0} * @example * axis: { * y2: { * tick: { * text: { * position: { * x: 10, * y: 10 * } * } * } * } * } */ axis_y2_tick_text_position: { x: 0, y: 0 }, /** * Set padding for y2 axis.<br><br> * You can set padding for y2 axis to create more space on the edge of the axis. * This option accepts object and it can include top and bottom. top, bottom will be treated as pixels. * * - **NOTE:** * - Given values are translated relative to the y2 Axis domain value for padding * - For area and bar type charts, [area.zerobased](#.area) or [bar.zerobased](#.bar) options should be set to 'false` to get padded bottom. * @name axisβ€€y2β€€padding * @memberof Options * @type {object|number} * @default {} * @example * axis: { * y2: { * padding: { * top: 100, * bottom: 100 * } * * // or set both values at once. * padding: 10 * } */ axis_y2_padding: {}, /** * Set default range of y2 axis.<br><br> * This option set the default value for y2 axis when there is no data on init. * @name axisβ€€y2β€€default * @memberof Options * @type {Array} * @default undefined * @example * axis: { * y2: { * default: [0, 1000] * } * } */ axis_y2_default: undefined, /** * Set additional axes for y2 Axis. * - **NOTE:** Axis' scale is based on y2 Axis value if domain option isn't set. * * Each axis object should consist with following options: * * | Name | Type | Default | Description | * | --- | --- | --- | --- | * | domain | Array | - | Set the domain value | * | tick.outer | boolean | true | Show outer tick | * | tick.format | Function | - | Set formatter for tick text | * | tick.count | Number | - | Set the number of y axis ticks | * | tick.values | Array | - | Set tick values manually | * @name axisβ€€y2β€€axes * @memberof Options * @type {Array} * @see [Demo](https://naver.github.io/billboard.js/demo/#Axis.MultiAxes) * @see [Demo: Domain](https://naver.github.io/billboard.js/demo/#Axis.MultiAxesDomain) * @example * y2: { * axes: [ * { * // if set, will not be correlated with the main y2 Axis domain value * domain: [0, 1000], * tick: { * outer: false, * format: function(x) { * return x + "%"; * }, * count: 2, * values: [10, 20, 30] * } * }, * ... * ] * } */ axis_y2_axes: [] }); ;// CONCATENATED MODULE: ./src/config/Options/axis/axis.ts function axis_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function axis_objectSpread(target) { for (var source, i = 1; i < arguments.length; i++) source = arguments[i] == null ? {} : arguments[i], i % 2 ? axis_ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : axis_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); return target; } /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * y Axis config options */ /* harmony default export */ var axis_axis = (axis_objectSpread(axis_objectSpread(axis_objectSpread({ /** * Switch x and y axis position. * @name axisβ€€rotated * @memberof Options * @type {boolean} * @default false * @example * axis: { * rotated: true * } */ axis_rotated: !1 }, axis_x), y), y2)); ;// CONCATENATED MODULE: ./src/config/Options/common/grid.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * grid config options */ /* harmony default export */ var common_grid = ({ /** * Set related options * @name grid * @memberof Options * @type {object} * @property {boolean} [front=false] Set 'grid & focus lines' to be positioned over grid lines and chart elements. * @property {object} x Grid x object * @property {boolean} [x.show=false] Show grids along x axis. * @property {Array} [x.lines=[]] Show additional grid lines along x axis.<br> * This option accepts array including object that has value, text, position and class. text, position and class are optional. For position, start, middle and end (default) are available. * If x axis is category axis, value can be category name. If x axis is timeseries axis, value can be date string, Date object and unixtime integer. * @property {object} y Grid y object * @property {boolean} [y.show=false] Show grids along x axis. * @property {Array} [y.lines=[]] Show additional grid lines along y axis.<br> * This option accepts array including object that has value, text, position and class. * @property {number} [y.ticks=10] Number of y grids to be shown. * @property {object} focus Grid focus object * @property {boolean} [focus.edge=false] Show edged focus grid line.<br>**NOTE:** Available when [`tooltip.grouped=false`](#.tooltip) option is set. * @property {boolean} [focus.show=true] Show grid line when focus. * @property {boolean} [focus.y=false] Show y coordinate focus grid line.<br>**NOTE:** Available when [`tooltip.grouped=false`](#.tooltip) option is set. * @property {object} lines Grid lines object * @property {boolean} [lines.front=true] Set grid lines to be positioned over chart elements. * @default undefined * @see [Demo](https://naver.github.io/billboard.js/demo/#Grid.GridLines) * @see [Demo: X Grid Lines](https://naver.github.io/billboard.js/demo/#Grid.OptionalXGridLines) * @see [Demo: Y Grid Lines](https://naver.github.io/billboard.js/demo/#Grid.OptionalYGridLines) * @example * grid: { * x: { * show: true, * lines: [ * {value: 2, text: "Label on 2"}, * {value: 5, text: "Label on 5", class: "label-5"}, * {value: 6, text: "Label on 6", position: "start"} * ] * }, * y: { * show: true, * lines: [ * {value: 100, text: "Label on 100"}, * {value: 200, text: "Label on 200", class: "label-200"}, * {value: 300, text: "Label on 300", position: 'middle'} * ], * ticks: 5 * }, * front: true, * focus: { * show: false, * * // Below options are available when 'tooltip.grouped=false' option is set * edge: true, * y: true * }, * lines: { * front: false * } * } */ grid_x_show: !1, grid_x_type: "tick", grid_x_lines: [], grid_y_show: !1, grid_y_lines: [], grid_y_ticks: 10, grid_focus_edge: !1, grid_focus_show: !0, grid_focus_y: !1, grid_front: !1, grid_lines_front: !0 }); ;// CONCATENATED MODULE: ./src/config/resolver/axis.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Modules exports for Axis based chart */ // Chart // ChartInternal // Axis based options var api = [api_axis, api_category, grid_x, grid_y, flow, group, api_regions, x]; var internal = [Axis, clip, eventrect, interactions_flow, grid, region, size_axis]; var options = [data_axis, axis_axis, common_grid]; // EXTERNAL MODULE: external {"commonjs":"d3-interpolate","commonjs2":"d3-interpolate","amd":"d3-interpolate","root":"d3"} var external_commonjs_d3_interpolate_commonjs2_d3_interpolate_amd_d3_interpolate_root_d3_ = __webpack_require__(12); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/arc.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var arc = ({ initPie: function initPie() { var $$ = this, config = $$.config, dataType = config.data_type, padding = config.pie_padding, startingAngle = config[dataType + "_startingAngle"] || 0, padAngle = ($$.hasType("pie") && padding ? padding * .01 : config[dataType + "_padAngle"]) || 0; $$.pie = (0,external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.pie)().startAngle(startingAngle).endAngle(startingAngle + 2 * Math.PI).padAngle(padAngle).value(function (d) { return d.values.reduce(function (a, b) { return a + b.value; }, 0); }).sort($$.getSortCompareFn.bind($$)(!0)); }, updateRadius: function updateRadius() { var $$ = this, config = $$.config, state = $$.state, padding = config.pie_padding, w = config.gauge_width || config.donut_width, gaugeArcWidth = $$.filterTargetsToShow($$.data.targets).length * config.gauge_arcs_minWidth; state.radiusExpanded = Math.min(state.arcWidth, state.arcHeight) / 2 * ($$.hasMultiArcGauge() ? .85 : 1), state.radius = state.radiusExpanded * .95, state.innerRadiusRatio = w ? (state.radius - w) / state.radius : .6, state.gaugeArcWidth = w || (gaugeArcWidth <= state.radius - state.innerRadius ? state.radius - state.innerRadius : gaugeArcWidth <= state.radius ? gaugeArcWidth : state.radius); var innerRadius = config.pie_innerRadius || (padding ? padding * (state.innerRadiusRatio + .1) : 0); // NOTE: inner/outerRadius can be an object by user setting, only for 'pie' type state.outerRadius = config.pie_outerRadius, state.innerRadius = $$.hasType("donut") || $$.hasType("gauge") ? state.radius * state.innerRadiusRatio : innerRadius; }, /** * Get pie's inner & outer radius value * @param {object|undefined} d Data object * @returns {object} * @private */ getRadius: function getRadius(d) { var $$ = this, data = d && d.data, _$$$state = $$.state, innerRadius = _$$$state.innerRadius, outerRadius = _$$$state.outerRadius; return !isNumber(innerRadius) && data && (innerRadius = innerRadius[data.id] || 0), isObject(outerRadius) && data && data.id in outerRadius ? outerRadius = outerRadius[data.id] : !isNumber(outerRadius) && (outerRadius = $$.state.radius), { innerRadius: innerRadius, outerRadius: outerRadius }; }, updateArc: function updateArc() { var $$ = this; $$.updateRadius(), $$.svgArc = $$.getSvgArc(), $$.svgArcExpanded = $$.getSvgArcExpanded(); }, getArcLength: function getArcLength() { var $$ = this, config = $$.config, arcLengthInPercent = config.gauge_arcLength * 3.6, len = 2 * (arcLengthInPercent / 360); return arcLengthInPercent < -360 ? len = -2 : arcLengthInPercent > 360 && (len = 2), len * Math.PI; }, getStartAngle: function getStartAngle() { var $$ = this, config = $$.config, isFullCircle = config.gauge_fullCircle, defaultStartAngle = -1 * Math.PI / 2, defaultEndAngle = Math.PI / 2, startAngle = config.gauge_startingAngle; return !isFullCircle && startAngle <= defaultStartAngle ? startAngle = defaultStartAngle : !isFullCircle && startAngle >= defaultEndAngle ? startAngle = defaultEndAngle : (startAngle > Math.PI || startAngle < -1 * Math.PI) && (startAngle = Math.PI), startAngle; }, updateAngle: function updateAngle(dValue) { var $$ = this, config = $$.config, state = $$.state, pie = $$.pie, d = dValue, found = !1; if (!config) return null; var gStart = $$.getStartAngle(), radius = config.gauge_fullCircle ? $$.getArcLength() : gStart * -2; if (d.data && $$.isGaugeType(d.data) && !$$.hasMultiArcGauge()) { // to prevent excluding total data sum during the init(when data.hide option is used), use $$.rendered state value var totalSum = $$.getTotalDataSum(state.rendered), gEnd = radius * (totalSum / (config.gauge_max - config.gauge_min)); pie = pie.startAngle(gStart).endAngle(gEnd + gStart); } if (pie($$.filterTargetsToShow()).forEach(function (t, i) { found || t.data.id !== d.data.id || (found = !0, d = t, d.index = i); }), isNaN(d.startAngle) && (d.startAngle = 0), isNaN(d.endAngle) && (d.endAngle = d.startAngle), d.data && $$.hasMultiArcGauge()) { var gMin = config.gauge_min, gMax = config.gauge_max, gValue = d.value < gMin ? 0 : d.value < gMax ? d.value - gMin : gMax - gMin; d.startAngle = gStart, d.endAngle = gStart + radius / (gMax - gMin) * gValue; } return found ? d : null; }, getSvgArc: function getSvgArc() { var $$ = this, state = $$.state, singleArcWidth = state.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length, hasMultiArcGauge = $$.hasMultiArcGauge(), arc = (0,external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.arc)().innerRadius(function (d) { var _$$$getRadius = $$.getRadius(d), innerRadius = _$$$getRadius.innerRadius; return hasMultiArcGauge ? state.radius - singleArcWidth * (d.index + 1) : isNumber(innerRadius) ? innerRadius : 0; }).outerRadius(function (d) { var _$$$getRadius2 = $$.getRadius(d), outerRadius = _$$$getRadius2.outerRadius; return hasMultiArcGauge ? state.radius - singleArcWidth * d.index : outerRadius; }), newArc = function (d, withoutUpdate) { var path = "M 0 0"; if (d.value || d.data) { var updated = !withoutUpdate && $$.updateAngle(d); withoutUpdate ? path = arc(d) : updated && (path = arc(updated)); } return path; }; return newArc.centroid = arc.centroid, newArc; }, getSvgArcExpanded: function getSvgArcExpanded(rate) { var $$ = this, state = $$.state, newRate = rate || 1, singleArcWidth = state.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length, hasMultiArcGauge = $$.hasMultiArcGauge(), expandWidth = Math.min(state.radiusExpanded * newRate - state.radius, singleArcWidth * .8 - (1 - newRate) * 100), arc = (0,external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.arc)().innerRadius(function (d) { return hasMultiArcGauge ? state.radius - singleArcWidth * (d.index + 1) : $$.getRadius(d).innerRadius; }).outerRadius(function (d) { var radius; if (hasMultiArcGauge) radius = state.radius - singleArcWidth * d.index + expandWidth;else { var _$$$getRadius3 = $$.getRadius(d), outerRadius = _$$$getRadius3.outerRadius, radiusExpanded = state.radiusExpanded; state.radius !== outerRadius && (radiusExpanded -= Math.abs(state.radius - outerRadius)), radius = radiusExpanded * newRate; } return radius; }); return function (d) { var updated = $$.updateAngle(d); return updated ? arc(updated) : "M 0 0"; }; }, getArc: function getArc(d, withoutUpdate, force) { return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0"; }, transformForArcLabel: function transformForArcLabel(d) { var $$ = this, config = $$.config, radiusExpanded = $$.state.radiusExpanded, updated = $$.updateAngle(d), translate = ""; if (updated) if ($$.hasMultiArcGauge()) { var y1 = Math.sin(updated.endAngle - Math.PI / 2), x = Math.cos(updated.endAngle - Math.PI / 2) * (radiusExpanded + 25), y = y1 * (radiusExpanded + 15 - Math.abs(y1 * 10)) + 3; translate = "translate(" + x + "," + y + ")"; } else if (!$$.hasType("gauge") || $$.data.targets.length > 1) { var _$$$getRadius4 = $$.getRadius(d), outerRadius = _$$$getRadius4.outerRadius, c = this.svgArc.centroid(updated), x = isNaN(c[0]) ? 0 : c[0], y = isNaN(c[1]) ? 0 : c[1], h = Math.sqrt(x * x + y * y), ratio = $$.hasType("donut") && config.donut_label_ratio || $$.hasType("pie") && config.pie_label_ratio; ratio = ratio ? isFunction(ratio) ? ratio.bind($$.api)(d, outerRadius, h) : ratio : outerRadius && (h ? (36 / outerRadius > .375 ? 1.175 - 36 / outerRadius : .8) * outerRadius / h : 0), translate = "translate(" + x * ratio + "," + y * ratio + ")"; } return translate; }, convertToArcData: function convertToArcData(d) { return this.addName({ id: d.data ? d.data.id : d.id, value: d.value, ratio: this.getRatio("arc", d), index: d.index }); }, textForArcLabel: function textForArcLabel(selection) { var $$ = this, hasGauge = $$.hasType("gauge"); $$.shouldShowArcLabel() && selection.style("fill", $$.updateTextColor.bind($$)).each(function (d) { var node = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), updated = $$.updateAngle(d), ratio = $$.getRatio("arc", updated), isUnderThreshold = $$.meetsLabelThreshold(ratio, $$.hasType("donut") && "donut" || $$.hasType("gauge") && "gauge" || $$.hasType("pie") && "pie"); if (isUnderThreshold) { var value = (updated || d).value, text = ($$.getArcLabelFormat() || $$.defaultArcValueFormat)(value, ratio, d.data.id).toString(); setTextValue(node, text, [-1, 1], hasGauge); } else node.text(""); }); }, expandArc: function expandArc(targetIds) { var $$ = this, transiting = $$.state.transiting, $el = $$.$el; // MEMO: avoid to cancel transition if (transiting) { var interval = setInterval(function () { transiting || (clearInterval(interval), $el.legend.selectAll("." + config_classes.legendItemFocused).size() > 0 && $$.expandArc(targetIds)); }, 10); return; } var newTargetIds = $$.mapToTargetIds(targetIds); $el.svg.selectAll($$.selectorTargets(newTargetIds, "." + config_classes.chartArc)).each(function (d) { if ($$.shouldExpand(d.data.id)) { var expandDuration = $$.getExpandConfig(d.data.id, "duration"), svgArcExpandedSub = $$.getSvgArcExpanded($$.getExpandConfig(d.data.id, "rate")); (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).selectAll("path").transition().duration(expandDuration).attr("d", $$.svgArcExpanded).transition().duration(expandDuration * 2).attr("d", svgArcExpandedSub); } }); }, unexpandArc: function unexpandArc(targetIds) { var $$ = this, transiting = $$.state.transiting, svg = $$.$el.svg; if (!transiting) { var newTargetIds = $$.mapToTargetIds(targetIds); svg.selectAll($$.selectorTargets(newTargetIds, "." + config_classes.chartArc)).selectAll("path").transition().duration(function (d) { return $$.getExpandConfig(d.data.id, "duration"); }).attr("d", $$.svgArc), svg.selectAll("" + config_classes.arc).style("opacity", "1"); } }, /** * Get expand config value * @param {string} id data ID * @param {string} key config key: 'duration | rate' * @returns {number} * @private */ getExpandConfig: function getExpandConfig(id, key) { var type, $$ = this, config = $$.config; return $$.isDonutType(id) ? type = "donut" : $$.isGaugeType(id) ? type = "gauge" : $$.isPieType(id) && (type = "pie"), type ? config[type + "_expand_" + key] : { duration: 50, rate: .98 }[key]; }, shouldExpand: function shouldExpand(id) { var $$ = this, config = $$.config; return $$.isDonutType(id) && config.donut_expand || $$.isGaugeType(id) && config.gauge_expand || $$.isPieType(id) && config.pie_expand; }, shouldShowArcLabel: function shouldShowArcLabel() { var $$ = this, config = $$.config; return ["pie", "donut", "gauge"].some(function (v) { return $$.hasType(v) && config[v + "_label_show"]; }); }, getArcLabelFormat: function getArcLabelFormat() { var $$ = this, config = $$.config, format = config.pie_label_format; return $$.hasType("gauge") ? format = config.gauge_label_format : $$.hasType("donut") && (format = config.donut_label_format), isFunction(format) ? format.bind($$.api) : format; }, getArcTitle: function getArcTitle() { var $$ = this, type = $$.hasType("donut") && "donut" || $$.hasType("gauge") && "gauge"; return type ? $$.config[type + "_title"] : ""; }, updateTargetsForArc: function updateTargetsForArc(targets) { var $$ = this, $el = $$.$el, hasGauge = $$.hasType("gauge"), classChartArc = $$.getChartClass("Arc"), classArcs = $$.getClass("arcs", !0), classFocus = $$.classFocus.bind($$), chartArcs = $el.main.select("." + config_classes.chartArcs), mainPieUpdate = chartArcs.selectAll("." + config_classes.chartArc).data($$.pie(targets)).attr("class", function (d) { return classChartArc(d) + classFocus(d.data); }), mainPieEnter = mainPieUpdate.enter().append("g").attr("class", classChartArc); mainPieEnter.append("g").attr("class", classArcs).merge(mainPieUpdate), mainPieEnter.append("text").attr("dy", hasGauge && !$$.hasMultiTargets() ? "-.1em" : ".35em").style("opacity", "0").style("text-anchor", "middle").style("pointer-events", "none"), $el.text = chartArcs.selectAll("." + config_classes.target + " text"); }, initArc: function initArc() { var $$ = this, $el = $$.$el; $el.arcs = $el.main.select("." + config_classes.chart).append("g").attr("class", config_classes.chartArcs).attr("transform", $$.getTranslate("arc")), $$.setArcTitle(); }, /** * Set arc title text * @private */ setArcTitle: function setArcTitle() { var $$ = this, title = $$.getArcTitle(), hasGauge = $$.hasType("gauge"); if (title) { var text = $$.$el.arcs.append("text").attr("class", config_classes[hasGauge ? "chartArcsGaugeTitle" : "chartArcsTitle"]).style("text-anchor", "middle"); hasGauge && text.attr("dy", "-0.3em").style("font-size", "27px"), setTextValue(text, title, hasGauge ? undefined : [-.6, 1.35], !0); } }, redrawArc: function redrawArc(duration, durationForExit, withTransform) { var $$ = this, config = $$.config, state = $$.state, main = $$.$el.main, hasInteraction = config.interaction_enabled, isSelectable = hasInteraction && config.data_selection_isselectable, mainArc = main.selectAll("." + config_classes.arcs).selectAll("." + config_classes.arc).data($$.arcData.bind($$)); // bind arc events mainArc.exit().transition().duration(durationForExit).style("opacity", "0").remove(), mainArc = mainArc.enter().append("path").attr("class", $$.getClass("arc", !0)).style("fill", function (d) { return $$.color(d.data); }).style("cursor", function (d) { return isSelectable && isSelectable.bind($$.api)(d) ? "pointer" : null; }).style("opacity", "0").each(function (d) { $$.isGaugeType(d.data) && (d.startAngle = config.gauge_startingAngle, d.endAngle = config.gauge_startingAngle), this._current = d; }).merge(mainArc), $$.hasType("gauge") && ($$.updateGaugeMax(), $$.hasMultiArcGauge() && $$.redrawMultiArcGauge()), mainArc.attr("transform", function (d) { return !$$.isGaugeType(d.data) && withTransform ? "scale(0)" : ""; }).style("opacity", function (d) { return d === this._current ? "0" : "1"; }).each(function () { state.transiting = !0; }).transition().duration(duration).attrTween("d", function (d) { var updated = $$.updateAngle(d); if (!updated) return function () { return "M 0 0"; }; isNaN(this._current.startAngle) && (this._current.startAngle = 0), isNaN(this._current.endAngle) && (this._current.endAngle = this._current.startAngle); var interpolate = (0,external_commonjs_d3_interpolate_commonjs2_d3_interpolate_amd_d3_interpolate_root_d3_.interpolate)(this._current, updated); return this._current = interpolate(0), function (t) { var interpolated = interpolate(t); // data.id will be updated by interporator return interpolated.data = d.data, $$.getArc(interpolated, !0); }; }).attr("transform", withTransform ? "scale(1)" : "").style("fill", function (d) { var color; return $$.levelColor ? (color = $$.levelColor(d.data.values[0].value), config.data_colors[d.data.id] = color) : color = $$.color(d.data), color; }) // Where gauge reading color would receive customization. .style("opacity", "1").call(endall, function () { if ($$.levelColor) { var path = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), d = path.datum(); $$.updateLegendItemColor(d.data.id, path.style("fill")); } state.transiting = !1, callFn(config.onrendered, $$.api); }), hasInteraction && $$.bindArcEvent(mainArc), $$.hasType("gauge") && $$.redrawBackgroundArcs(), $$.redrawArcText(duration); }, redrawBackgroundArcs: function redrawBackgroundArcs() { var $$ = this, config = $$.config, state = $$.state, hasMultiArcGauge = $$.hasMultiArcGauge(), isFullCircle = config.gauge_fullCircle, startAngle = $$.getStartAngle(), endAngle = isFullCircle ? startAngle + $$.getArcLength() : startAngle * -1, backgroundArc = $$.$el.arcs.select((hasMultiArcGauge ? "g" : "") + "." + config_classes.chartArcsBackground); if (hasMultiArcGauge) { var index = 0; backgroundArc = backgroundArc.selectAll("path." + config_classes.chartArcsBackground).data($$.data.targets), backgroundArc.enter().append("path").attr("class", function (d, i) { return config_classes.chartArcsBackground + " " + config_classes.chartArcsBackground + "-" + i; }).merge(backgroundArc).style("fill", config.gauge_background || null).attr("d", function (_ref2) { var id = _ref2.id; if (state.hiddenTargetIds.indexOf(id) >= 0) return "M 0 0"; var d = { data: [{ value: config.gauge_max }], startAngle: startAngle, endAngle: endAngle, index: index++ }; return $$.getArc(d, !0, !0); }), backgroundArc.exit().remove(); } else backgroundArc.attr("d", function () { var d = { data: [{ value: config.gauge_max }], startAngle: startAngle, endAngle: endAngle }; return $$.getArc(d, !0, !0); }); }, bindArcEvent: function bindArcEvent(arc) { // eslint-disable-next-line function selectArc(_this, arcData, id) { $$.expandArc(id), $$.api.focus(id), $$.toggleFocusLegend(id, !0), $$.showTooltip([arcData], _this); } // eslint-disable-next-line function unselectArc(arcData) { var id = arcData && arcData.id || undefined; $$.unexpandArc(id), $$.api.revert(), $$.revertLegend(), $$.hideTooltip(); } var $$ = this, config = $$.config, state = $$.state, isTouch = state.inputType === "touch", isMouse = state.inputType === "mouse"; // touch events if (arc.on("click", function (event, d, i) { var arcData, updated = $$.updateAngle(d); updated && (arcData = $$.convertToArcData(updated), $$.toggleShape && $$.toggleShape(this, arcData, i), config.data_onclick.bind($$.api)(arcData, this)); }), isMouse && arc.on("mouseover", function (event, d) { if (!state.transiting) // skip while transiting { state.event = event; var updated = $$.updateAngle(d), arcData = updated ? $$.convertToArcData(updated) : null, id = arcData && arcData.id || undefined; selectArc(this, arcData, id), $$.setOverOut(!0, arcData); } }).on("mouseout", function (event, d) { if (!state.transiting) // skip while transiting { state.event = event; var updated = $$.updateAngle(d), arcData = updated ? $$.convertToArcData(updated) : null; unselectArc(), $$.setOverOut(!1, arcData); } }).on("mousemove", function (event, d) { var updated = $$.updateAngle(d), arcData = updated ? $$.convertToArcData(updated) : null; state.event = event, $$.showTooltip([arcData], this); }), isTouch && $$.hasArcType() && !$$.radars) { var getEventArc = function (event) { var touch = event.changedTouches[0], eventArc = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(browser_doc.elementFromPoint(touch.clientX, touch.clientY)); return eventArc; }; $$.$el.svg.on("touchstart touchmove", function (event) { if (!state.transiting) // skip while transiting { var eventArc = getEventArc(event), datum = eventArc.datum(), updated = datum && datum.data && datum.data.id ? $$.updateAngle(datum) : null, arcData = updated ? $$.convertToArcData(updated) : null, id = arcData && arcData.id || undefined; $$.callOverOutForTouch(arcData), isUndefined(id) ? unselectArc() : selectArc(this, arcData, id); } }); } }, redrawArcText: function redrawArcText(duration) { var text, $$ = this, config = $$.config, state = $$.state, _$$$$el = $$.$el, main = _$$$$el.main, arcs = _$$$$el.arcs, hasGauge = $$.hasType("gauge"), hasMultiArcGauge = $$.hasMultiArcGauge(); if (hasGauge && $$.data.targets.length === 1 && config.gauge_title || (text = main.selectAll("." + config_classes.chartArc).select("text").style("opacity", "0").attr("class", function (d) { return $$.isGaugeType(d.data) ? config_classes.gaugeValue : null; }).call($$.textForArcLabel.bind($$)).attr("transform", $$.transformForArcLabel.bind($$)).style("font-size", function (d) { return $$.isGaugeType(d.data) && $$.data.targets.length === 1 && !hasMultiArcGauge ? Math.round(state.radius / 5) + "px" : null; }).transition().duration(duration).style("opacity", function (d) { return $$.isTargetToShow(d.data.id) && $$.isArcType(d.data) ? "1" : "0"; }), hasMultiArcGauge && text.attr("dy", "-.1em")), main.select("." + config_classes.chartArcsTitle).style("opacity", $$.hasType("donut") || hasGauge ? "1" : "0"), hasGauge) { var isFullCircle = config.gauge_fullCircle; isFullCircle && text && text.attr("dy", "" + (hasMultiArcGauge ? 0 : Math.round(state.radius / 14))), config.gauge_label_show && (arcs.select("." + config_classes.chartArcsGaugeUnit).attr("dy", (isFullCircle ? 1.5 : .75) + "em").text(config.gauge_units), arcs.select("." + config_classes.chartArcsGaugeMin).attr("dx", -1 * (state.innerRadius + (state.radius - state.innerRadius) / (isFullCircle ? 1 : 2)) + "px").attr("dy", "1.2em").text($$.textForGaugeMinMax(config.gauge_min, !1)), !isFullCircle && arcs.select("." + config_classes.chartArcsGaugeMax).attr("dx", state.innerRadius + (state.radius - state.innerRadius) / 2 + "px").attr("dy", "1.2em").text($$.textForGaugeMinMax(config.gauge_max, !0))); } } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/area.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var shape_area = ({ initArea: function initArea(mainLine) { var $$ = this, config = $$.config; mainLine.insert("g", "." + config_classes[config.area_front ? "circles" : "lines"]).attr("class", $$.getClass("areas", !0)); }, updateAreaGradient: function updateAreaGradient() { var $$ = this, config = $$.config, datetimeId = $$.state.datetimeId, defs = $$.$el.defs; $$.data.targets.forEach(function (d) { var id = datetimeId + "-areaGradient" + $$.getTargetSelectorSuffix(d.id); if ($$.isAreaType(d) && defs.select("#" + id).empty()) { var color = $$.color(d), _config$area_linearGr = config.area_linearGradient, _config$area_linearGr2 = _config$area_linearGr.x, x = _config$area_linearGr2 === void 0 ? [0, 0] : _config$area_linearGr2, _config$area_linearGr3 = _config$area_linearGr.y, y = _config$area_linearGr3 === void 0 ? [0, 1] : _config$area_linearGr3, _config$area_linearGr4 = _config$area_linearGr.stops, stops = _config$area_linearGr4 === void 0 ? [[0, color, 1], [1, color, 0]] : _config$area_linearGr4, linearGradient = defs.append("linearGradient").attr("id", "" + id).attr("x1", x[0]).attr("x2", x[1]).attr("y1", y[0]).attr("y2", y[1]); stops.forEach(function (v) { var stopColor = isFunction(v[1]) ? v[1].bind($$.api)(d.id) : v[1]; linearGradient.append("stop").attr("offset", v[0]).attr("stop-color", stopColor || color).attr("stop-opacity", v[2]); }); } }); }, updateAreaColor: function updateAreaColor(d) { var $$ = this; return $$.config.area_linearGradient ? "url(#" + $$.state.datetimeId + "-areaGradient" + $$.getTargetSelectorSuffix(d.id) + ")" : $$.color(d); }, /** * Generate/Update elements * @param {number} durationForExit Transition duration for exit elements * @param {boolean} isSub Subchart draw * @private */ updateArea: function updateArea(durationForExit, isSub) { isSub === void 0 && (isSub = !1); var $$ = this, config = $$.config, state = $$.state, $el = $$.$el, $root = isSub ? $el.subchart : $el; config.area_linearGradient && $$.updateAreaGradient(); var area = $root.main.selectAll("." + config_classes.areas).selectAll("." + config_classes.area).data($$.lineData.bind($$)); area.exit().transition().duration(durationForExit).style("opacity", "0").remove(), $root.area = area.enter().append("path").attr("class", $$.getClass("area", !0)).style("fill", $$.updateAreaColor.bind($$)).style("opacity", function () { return state.orgAreaOpacity = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).style("opacity"), "0"; }).merge(area), area.style("opacity", state.orgAreaOpacity); }, /** * Redraw function * @param {Function} drawFn Retuned functino from .generateDrawCandlestick() * @param {boolean} withTransition With or without transition * @param {boolean} isSub Subchart draw * @returns {Array} */ redrawArea: function redrawArea(drawFn, withTransition, isSub) { isSub === void 0 && (isSub = !1); var $$ = this, _ref = isSub ? this.$el.subchart : this.$el, area = _ref.area, orgAreaOpacity = $$.state.orgAreaOpacity; return [(withTransition ? area.transition(getRandom()) : area).attr("d", drawFn).style("fill", $$.updateAreaColor.bind($$)).style("opacity", function (d) { return ($$.isAreaRangeType(d) ? orgAreaOpacity / 1.75 : orgAreaOpacity) + ""; })]; }, /** * Generate area path data * @param {object} areaIndices Indices * @param {boolean} isSub Weather is sub axis * @returns {Function} * @private */ generateDrawArea: function generateDrawArea(areaIndices, isSub) { var $$ = this, config = $$.config, lineConnectNull = config.line_connectNull, isRotated = config.axis_rotated, getPoints = $$.generateGetAreaPoints(areaIndices, isSub), yScale = $$.getYScaleById.bind($$), xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); }, value0 = function (d, i) { return $$.isGrouped(d.id) ? getPoints(d, i)[0][1] : yScale(d.id, isSub)($$.isAreaRangeType(d) ? $$.getRangedData(d, "high") : $$.getShapeYMin(d.id)); }, value1 = function (d, i) { return $$.isGrouped(d.id) ? getPoints(d, i)[1][1] : yScale(d.id, isSub)($$.isAreaRangeType(d) ? $$.getRangedData(d, "low") : d.value); }; return function (d) { var path, values = lineConnectNull ? $$.filterRemoveNull(d.values) : d.values, x0 = 0, y0 = 0; if ($$.isAreaType(d)) { var area = (0,external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.area)(); area = isRotated ? area.y(xValue).x0(value0).x1(value1) : area.x(xValue) // @ts-ignore .y0(config.area_above ? 0 : value0).y1(value1), lineConnectNull || (area = area.defined(function (d) { return $$.getBaseValue(d) !== null; })), $$.isStepType(d) && (values = $$.convertValuesToStep(values)), path = area.curve($$.getCurve(d))(values); } else values[0] && (x0 = $$.scale.x(values[0].x), y0 = $$.getYScaleById(d.id)(values[0].value)), path = isRotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0; return path || "M 0 0"; }; }, generateGetAreaPoints: function generateGetAreaPoints(areaIndices, isSub) { // partial duplication of generateGetBarPoints var $$ = this, config = $$.config, x = $$.getShapeX(0, areaIndices, isSub), y = $$.getShapeY(!!isSub), areaOffset = $$.getShapeOffset($$.isAreaType, areaIndices, isSub), yScale = $$.getYScaleById.bind($$); return function (d, i) { var y0 = yScale.call($$, d.id, isSub)($$.getShapeYMin(d.id)), offset = areaOffset(d, i) || y0, posX = x(d), posY = y(d); // 1 point that marks the area position return config.axis_rotated && (d.value > 0 && posY < y0 || d.value < 0 && y0 < posY) && (posY = y0), [[posX, offset], [posX, posY - (y0 - offset)], [posX, posY - (y0 - offset)], // needed for compatibility [posX, offset] // needed for compatibility ]; }; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/bar.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var bar = ({ initBar: function initBar() { var $el = this.$el; $el.bar = $el.main.select("." + config_classes.chart) // should positioned at the beginning of the shape node to not overlap others .insert("g", ":first-child").attr("class", config_classes.chartBars); }, updateTargetsForBar: function updateTargetsForBar(targets) { var $$ = this, config = $$.config, $el = $$.$el, classChartBar = $$.getChartClass("Bar"), classBars = $$.getClass("bars", !0), classFocus = $$.classFocus.bind($$), isSelectable = config.interaction_enabled && config.data_selection_isselectable; $el.bar || $$.initBar(); var mainBarUpdate = $$.$el.main.select("." + config_classes.chartBars).selectAll("." + config_classes.chartBar).data(targets).attr("class", function (d) { return classChartBar(d) + classFocus(d); }), mainBarEnter = mainBarUpdate.enter().append("g").attr("class", classChartBar).style("opacity", "0").style("pointer-events", "none"); // Bars for each data mainBarEnter.append("g").attr("class", classBars).style("cursor", function (d) { return isSelectable && isSelectable.bind($$.api)(d) ? "pointer" : null; }); }, /** * Generate/Update elements * @param {number} durationForExit Transition duration for exit elements * @param {boolean} isSub Subchart draw * @private */ updateBar: function updateBar(durationForExit, isSub) { isSub === void 0 && (isSub = !1); var $$ = this, $root = isSub ? $$.$el.subchart : $$.$el, classBar = $$.getClass("bar", !0), initialOpacity = $$.initialOpacity.bind($$), bar = $root.main.selectAll("." + config_classes.bars).selectAll("." + config_classes.bar).data($$.labelishData.bind($$)); bar.exit().transition().duration(durationForExit).style("opacity", "0").remove(), $root.bar = bar.enter().append("path").attr("class", classBar).style("fill", $$.color).merge(bar).style("opacity", initialOpacity); }, /** * Redraw function * @param {Function} drawFn Retuned functino from .generateDrawCandlestick() * @param {boolean} withTransition With or without transition * @param {boolean} isSub Subchart draw * @returns {Array} */ redrawBar: function redrawBar(drawFn, withTransition, isSub) { isSub === void 0 && (isSub = !1); var _ref = isSub ? this.$el.subchart : this.$el, bar = _ref.bar; return [(withTransition ? bar.transition(getRandom()) : bar).attr("d", drawFn).style("fill", this.color).style("opacity", "1")]; }, generateDrawBar: function generateDrawBar(barIndices, isSub) { var $$ = this, config = $$.config, getPoints = $$.generateGetBarPoints(barIndices, isSub), isRotated = config.axis_rotated, isGrouped = config.data_groups.length, barRadius = config.bar_radius, barRadiusRatio = config.bar_radius_ratio, getRadius = isNumber(barRadius) && barRadius > 0 ? function () { return barRadius; } : isNumber(barRadiusRatio) ? function (w) { return w * barRadiusRatio; } : null; return function (d, i) { // 4 points that make a bar var points = getPoints(d, i), indexX = +isRotated, indexY = +!indexX, isNegative = d.value < 0, pathRadius = ["", ""], radius = 0; // switch points if axis is rotated, not applicable for sub chart if (getRadius && !isGrouped) { var index = isRotated ? indexY : indexX, barW = points[2][index] - points[0][index]; radius = getRadius(barW); var arc = "a" + radius + "," + radius + " " + (isNegative ? "1 0 0" : "0 0 1") + " "; pathRadius[+!isRotated] = "" + arc + radius + "," + radius, pathRadius[+isRotated] = "" + arc + [-radius, radius][isRotated ? "sort" : "reverse"](), isNegative && pathRadius.reverse(); } // path string data shouldn't be containing new line chars // https://github.com/naver/billboard.js/issues/530 var path = isRotated ? "H" + (points[1][indexX] - radius) + " " + pathRadius[0] + "V" + (points[2][indexY] - radius) + " " + pathRadius[1] + "H" + points[3][indexX] : "V" + (points[1][indexY] + (isNegative ? -radius : radius)) + " " + pathRadius[0] + "H" + (points[2][indexX] - radius) + " " + pathRadius[1] + "V" + points[3][indexY]; return "M" + points[0][indexX] + "," + points[0][indexY] + path + "z"; }; }, generateGetBarPoints: function generateGetBarPoints(barIndices, isSub) { var $$ = this, config = $$.config, axis = isSub ? $$.axis.subX : $$.axis.x, barTargetsNum = $$.getIndicesMax(barIndices) + 1, barW = $$.getBarW("bar", axis, barTargetsNum), barX = $$.getShapeX(barW, barIndices, !!isSub), barY = $$.getShapeY(!!isSub), barOffset = $$.getShapeOffset($$.isBarType, barIndices, !!isSub), yScale = $$.getYScaleById.bind($$); return function (d, i) { var y0 = yScale.call($$, d.id, isSub)($$.getShapeYMin(d.id)), offset = barOffset(d, i) || y0, width = isNumber(barW) ? barW : barW[d.id] || barW._$width, posX = barX(d), posY = barY(d); config.axis_rotated && (d.value > 0 && posY < y0 || d.value < 0 && y0 < posY) && (posY = y0), posY -= y0 - offset; var startPosX = posX + width; // 4 points that make a bar return [[posX, offset], [posX, posY], [startPosX, posY], [startPosX, offset]]; }; }, isWithinBar: function isWithinBar(that) { var mouse = getPointer(this.state.event, that), list = getRectSegList(that), _list = list, seg0 = _list[0], seg1 = _list[1], x = Math.min(seg0.x, seg1.x), y = Math.min(seg0.y, seg1.y), offset = this.config.bar_sensitivity, _that$getBBox = that.getBBox(), width = _that$getBBox.width, height = _that$getBBox.height, isWithin = x - offset < mouse[0] && mouse[0] < x + width + offset && y - offset < mouse[1] && mouse[1] < y + height + offset; return isWithin; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/candlestick.ts function candlestick_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function candlestick_objectSpread(target) { for (var source, i = 1; i < arguments.length; i++) source = arguments[i] == null ? {} : arguments[i], i % 2 ? candlestick_ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : candlestick_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); return target; } /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var candlestick = ({ initCandlestick: function initCandlestick() { var $el = this.$el; $el.candlestick = $el.main.select("." + config_classes.chart) // should positioned at the beginning of the shape node to not overlap others .append("g").attr("class", config_classes.chartCandlesticks); }, /** * Update targets by its data * called from: ChartInternal.updateTargets() * @param {Array} targets Filtered target by type * @private */ updateTargetsForCandlestick: function updateTargetsForCandlestick(targets) { var $$ = this, $el = $$.$el, classChart = $$.getChartClass("Candlestick"), classFocus = $$.classFocus.bind($$); $el.candlestick || $$.initCandlestick(); var mainUpdate = $$.$el.main.select("." + config_classes.chartCandlesticks).selectAll("." + config_classes.chartCandlestick).data(targets).attr("class", function (d) { return classChart(d) + classFocus(d); }); mainUpdate.enter().append("g").attr("class", classChart).style("pointer-events", "none"); }, /** * Generate/Update elements * @param {number} durationForExit Transition duration for exit elements * @param {boolean} isSub Subchart draw * @private */ updateCandlestick: function updateCandlestick(durationForExit, isSub) { isSub === void 0 && (isSub = !1); var $$ = this, $el = $$.$el, $root = isSub ? $el.subchart : $el, classSetter = $$.getClass("candlestick", !0), initialOpacity = $$.initialOpacity.bind($$), candlestick = $root.main.selectAll("." + config_classes.chartCandlestick).selectAll("." + config_classes.candlestick).data($$.labelishData.bind($$)); candlestick.exit().transition().duration(durationForExit).style("opacity", "0").remove(); var candlestickEnter = candlestick.enter().filter(function (d) { return d.value; }).append("g").attr("class", classSetter); candlestickEnter.append("line"), candlestickEnter.append("path"), $root.candlestick || ($root.candlestick = {}), $root.candlestick = candlestick.merge(candlestickEnter).style("opacity", initialOpacity); }, /** * Get draw function * @param {object} indices Indice data * @param {boolean} isSub Subchart draw * @returns {Function} * @private */ generateDrawCandlestick: function generateDrawCandlestick(indices, isSub) { var $$ = this, config = $$.config, getPoints = $$.generateGetCandlestickPoints(indices, isSub), isRotated = config.axis_rotated, downColor = config.candlestick_color_down; return function (d, i, g) { var _value, points = getPoints(d, i), value = $$.getCandlestickData(d), isUp = (_value = value) == null ? void 0 : _value._isUp, indexX = +isRotated; g.classed && g.classed(config_classes[isUp ? "valueUp" : "valueDown"], !0); var path = isRotated ? "H" + points[1][1] + " V" + points[1][0] + " H" + points[0][1] : "V" + points[1][1] + " H" + points[1][0] + " V" + points[0][1]; g.select("path").attr("d", "M" + points[0][indexX] + "," + points[0][+!indexX] + path + "z").style("fill", function (d) { var color = isUp ? $$.color(d) : isObject(downColor) ? downColor[d.id] : downColor; return color || $$.color(d); }); // set line position var line = g.select("line"), pos = isRotated ? { x1: points[2][1], x2: points[2][2], y1: points[2][0], y2: points[2][0] } : { x1: points[2][0], x2: points[2][0], y1: points[2][1], y2: points[2][2] }; for (var x in pos) line.attr(x, pos[x]); }; }, /** * Generate shape drawing points * @param {object} indices Indice data * @param {boolean} isSub Subchart draw * @returns {Function} */ generateGetCandlestickPoints: function generateGetCandlestickPoints(indices, isSub) { isSub === void 0 && (isSub = !1); var $$ = this, config = $$.config, axis = isSub ? $$.axis.subX : $$.axis.x, targetsNum = $$.getIndicesMax(indices) + 1, barW = $$.getBarW("candlestick", axis, targetsNum), x = $$.getShapeX(barW, indices, !!isSub), y = $$.getShapeY(!!isSub), shapeOffset = $$.getShapeOffset($$.isBarType, indices, !!isSub), yScale = $$.getYScaleById.bind($$); return function (d, i) { var points, y0 = yScale.call($$, d.id, isSub)($$.getShapeYMin(d.id)), offset = shapeOffset(d, i) || y0, width = isNumber(barW) ? barW : barW[d.id] || barW._$width, value = $$.getCandlestickData(d); if (value) { var posX = { start: x(d), end: 0 }; posX.end = posX.start + width; var posY = { start: y(value.open), end: y(value.close) }, posLine = { x: posX.start + width / 2, high: y(value.high), low: y(value.low) }; config.axis_rotated && (d.value > 0 && posY.start < y0 || d.value < 0 && y0 < posY.start) && (posY.start = y0), posY.start -= y0 - offset, points = [[posX.start, posY.start], [posX.end, posY.end], [posLine.x, posLine.low, posLine.high]]; } else points = [[0, 0], [0, 0], [0, 0, 0]]; return points; }; }, /** * Redraw function * @param {Function} drawFn Retuned functino from .generateDrawCandlestick() * @param {boolean} withTransition With or without transition * @param {boolean} isSub Subchart draw * @returns {Array} */ redrawCandlestick: function redrawCandlestick(drawFn, withTransition, isSub) { isSub === void 0 && (isSub = !1); var _ref = isSub ? this.$el.subchart : this.$el, candlestick = _ref.candlestick, rand = getRandom(!0); return [candlestick.each(function (d, i) { var g = withTransition ? (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).transition(rand) : (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this); drawFn(d, i, g); }).style("opacity", "1")]; }, /** * Get candlestick data as object * @param {object} param Data object * @param {Array|object} param.value Data value * @returns {object|null} Converted data object * @private */ getCandlestickData: function getCandlestickData(_ref2) { var d, value = _ref2.value; if (isArray(value)) { var open = value[0], high = value[1], low = value[2], close = value[3], _value$ = value[4], volume = _value$ !== void 0 && _value$; d = { open: open, high: high, low: low, close: close }, volume !== !1 && (d.volume = volume); } else isObject(value) && (d = candlestick_objectSpread({}, value)); return d && (d._isUp = d.close >= d.open), d || null; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/gauge.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var gauge = ({ initGauge: function initGauge() { var $$ = this, config = $$.config, arcs = $$.$el.arcs, appendText = function (className) { arcs.append("text").attr("class", className).style("text-anchor", "middle").style("pointer-events", "none"); }; if ($$.hasType("gauge")) { var hasMulti = $$.hasMultiArcGauge(); arcs.append(hasMulti ? "g" : "path").attr("class", config_classes.chartArcsBackground).style("fill", !hasMulti && config.gauge_background || null), config.gauge_units && appendText(config_classes.chartArcsGaugeUnit), config.gauge_label_show && (appendText(config_classes.chartArcsGaugeMin), !config.gauge_fullCircle && appendText(config_classes.chartArcsGaugeMax)); } }, updateGaugeMax: function updateGaugeMax() { var $$ = this, config = $$.config, state = $$.state, hasMultiGauge = $$.hasMultiArcGauge(), max = hasMultiGauge ? $$.getMinMaxData().max[0].value : $$.getTotalDataSum(state.rendered); max > config.gauge_max && (config.gauge_max = max); }, redrawMultiArcGauge: function redrawMultiArcGauge() { var $$ = this, config = $$.config, state = $$.state, $el = $$.$el, hiddenTargetIds = $$.state.hiddenTargetIds, arcLabelLines = $el.main.selectAll("." + config_classes.arcs).selectAll("." + config_classes.arcLabelLine).data($$.arcData.bind($$)), mainArcLabelLine = arcLabelLines.enter().append("rect").attr("class", function (d) { return config_classes.arcLabelLine + " " + config_classes.target + " " + config_classes.target + "-" + d.data.id; }).merge(arcLabelLines); mainArcLabelLine.style("fill", function (d) { return $$.levelColor ? $$.levelColor(d.data.values[0].value) : $$.color(d.data); }).style("display", config.gauge_label_show ? "" : "none").each(function (d) { var lineLength = 0, lineThickness = 2, x = 0, y = 0, transform = ""; if (hiddenTargetIds.indexOf(d.data.id) < 0) { var updated = $$.updateAngle(d), innerLineLength = state.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length * (updated.index + 1), lineAngle = updated.endAngle - Math.PI / 2, arcInnerRadius = state.radius - innerLineLength, linePositioningAngle = lineAngle - (arcInnerRadius === 0 ? 0 : 1 / arcInnerRadius); lineLength = state.radiusExpanded - state.radius + innerLineLength, x = Math.cos(linePositioningAngle) * arcInnerRadius, y = Math.sin(linePositioningAngle) * arcInnerRadius, transform = "rotate(" + lineAngle * 180 / Math.PI + ", " + x + ", " + y + ")"; } (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).attr("x", x).attr("y", y).attr("width", lineLength).attr("height", lineThickness).attr("transform", transform).style("stroke-dasharray", "0, " + (lineLength + lineThickness) + ", 0"); }); }, textForGaugeMinMax: function textForGaugeMinMax(value, isMax) { var $$ = this, config = $$.config, format = config.gauge_label_extents; return isFunction(format) ? format.bind($$.api)(value, isMax) : value; }, getGaugeLabelHeight: function getGaugeLabelHeight() { var config = this.config; return this.config.gauge_label_show && !config.gauge_fullCircle ? 20 : 0; }, getPaddingBottomForGauge: function getPaddingBottomForGauge() { var $$ = this; return $$.getGaugeLabelHeight() * ($$.config.gauge_label_show ? 2 : 2.5); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/bubble.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var bubble = ({ /** * Initializer * @private */ initBubble: function initBubble() { var $$ = this, config = $$.config; $$.hasType("bubble") && (config.point_show = !0, config.point_type = "circle", config.point_sensitivity = 25); }, /** * Get user agent's computed value * @returns {number} * @private */ getBaseLength: function getBaseLength() { var $$ = this, _$$$state = $$.state, width = _$$$state.width, height = _$$$state.height, cacheKey = KEY.bubbleBaseLength, baseLength = $$.cache.get(cacheKey); return baseLength || $$.cache.add(cacheKey, baseLength = getMinMax("min", [width, height])), baseLength; }, /** * Get the radius value for bubble circle * @param {object} d Data object * @returns {number} * @private */ getBubbleR: function getBubbleR(d) { var $$ = this, maxR = $$.config.bubble_maxR; isFunction(maxR) ? maxR = maxR.bind($$.api)(d) : !isNumber(maxR) && (maxR = $$.getBaseLength() / ($$.getMaxDataCount() * 2) + 12); var max = getMinMax("max", $$.getMinMaxData().max.map(function (d) { return $$.isBubbleZType(d) ? $$.getBubbleZData(d.value, "y") : isObject(d.value) ? d.value.mid : d.value; })), maxArea = maxR * maxR * Math.PI, area = ($$.isBubbleZType(d) ? $$.getBubbleZData(d.value, "z") : d.value) * (maxArea / max); return Math.sqrt(area / Math.PI); }, /** * Get bubble dimension data * @param {object|Array} d data value * @param {string} type - y or z * @returns {number} * @private */ getBubbleZData: function getBubbleZData(d, type) { return isObject(d) ? d[type] : d[type === "y" ? 0 : 1]; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/line.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var line = ({ initLine: function initLine() { var $el = this.$el; $el.line = $el.main.select("." + config_classes.chart).append("g").attr("class", config_classes.chartLines); }, updateTargetsForLine: function updateTargetsForLine(t) { var $$ = this, _$$$$el = $$.$el, area = _$$$$el.area, line = _$$$$el.line, main = _$$$$el.main, classChartLine = $$.getChartClass("Line"), classLines = $$.getClass("lines", !0), classFocus = $$.classFocus.bind($$); line || $$.initLine(); var targets = t.filter(function (d) { return !($$.isScatterType(d) || $$.isBubbleType(d)); }), mainLineUpdate = main.select("." + config_classes.chartLines).selectAll("." + config_classes.chartLine).data(targets).attr("class", function (d) { return classChartLine(d) + classFocus(d); }), mainLineEnter = mainLineUpdate.enter().append("g").attr("class", classChartLine).style("opacity", "0").style("pointer-events", "none"); // Lines for each data mainLineEnter.append("g").attr("class", classLines), $$.hasTypeOf("Area") && $$.initArea(!area && mainLineEnter.empty() ? mainLineUpdate : mainLineEnter), $$.updateTargetForCircle(targets, mainLineEnter); }, /** * Generate/Update elements * @param {number} durationForExit Transition duration for exit elements * @param {boolean} isSub Subchart draw * @private */ updateLine: function updateLine(durationForExit, isSub) { isSub === void 0 && (isSub = !1); var $$ = this, extraLineClasses = $$.format.extraLineClasses, $el = $$.$el, $root = isSub ? $el.subchart : $el, line = $root.main.selectAll("." + config_classes.lines).selectAll("." + config_classes.line).data($$.lineData.bind($$)); line.exit().transition().duration(durationForExit).style("opacity", "0").remove(), $root.line = line.enter().append("path").attr("class", function (d) { return $$.getClass("line", !0)(d) + " " + (extraLineClasses(d) || ""); }).style("stroke", $$.color).merge(line).style("opacity", $$.initialOpacity.bind($$)).style("shape-rendering", function (d) { return $$.isStepType(d) ? "crispEdges" : ""; }).attr("transform", null); }, /** * Redraw function * @param {Function} drawFn Retuned functino from .generateDrawCandlestick() * @param {boolean} withTransition With or without transition * @param {boolean} isSub Subchart draw * @returns {Array} */ redrawLine: function redrawLine(drawFn, withTransition, isSub) { isSub === void 0 && (isSub = !1); var _ref = isSub ? this.$el.subchart : this.$el, line = _ref.line; return [(withTransition ? line.transition(getRandom()) : line).attr("d", drawFn).style("stroke", this.color).style("opacity", "1")]; }, /** * Get the curve interpolate * @param {Array} d Data object * @returns {Function} * @private */ getCurve: function getCurve(d) { var $$ = this, isRotatedStepType = $$.config.axis_rotated && $$.isStepType(d); // when is step & rotated, should be computed in different way // https://github.com/naver/billboard.js/issues/471 return isRotatedStepType ? function (context) { var step = $$.getInterpolate(d)(context); // keep the original method return step.orgPoint = step.point, step.pointRotated = function (x, y) { this._point === 1 && (this._point = 2); var y1 = this._y * (1 - this._t) + y * this._t; this._context.lineTo(this._x, y1), this._context.lineTo(x, y1), this._x = x, this._y = y; }, step.point = function (x, y) { this._point === 0 ? this.orgPoint(x, y) : this.pointRotated(x, y); }, step; } : $$.getInterpolate(d); }, generateDrawLine: function generateDrawLine(lineIndices, isSub) { var $$ = this, config = $$.config, scale = $$.scale, lineConnectNull = config.line_connectNull, isRotated = config.axis_rotated, getPoints = $$.generateGetLinePoints(lineIndices, isSub), yScale = $$.getYScaleById.bind($$), xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); }, yValue = function (d, i) { return $$.isGrouped(d.id) ? getPoints(d, i)[0][1] : yScale(d.id, isSub)($$.getBaseValue(d)); }, line = (0,external_commonjs_d3_shape_commonjs2_d3_shape_amd_d3_shape_root_d3_.line)(); line = isRotated ? line.x(yValue).y(xValue) : line.x(xValue).y(yValue), lineConnectNull || (line = line.defined(function (d) { return $$.getBaseValue(d) !== null; })); var x = isSub ? scale.subX : scale.x; return function (d) { var path, y = yScale(d.id, isSub), values = lineConnectNull ? $$.filterRemoveNull(d.values) : d.values, x0 = 0, y0 = 0; if ($$.isLineType(d)) { var regions = config.data_regions[d.id]; regions ? path = $$.lineWithRegions(values, x, y, regions) : ($$.isStepType(d) && (values = $$.convertValuesToStep(values)), path = line.curve($$.getCurve(d))(values)); } else values[0] && (x0 = x(values[0].x), y0 = y(values[0].value)), path = isRotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0; return path || "M 0 0"; }; }, lineWithRegions: function lineWithRegions(d, x, y, _regions) { var xp, yp, diff, diffx2, $$ = this, config = $$.config, isRotated = config.axis_rotated, isTimeSeries = $$.axis.isTimeSeries(), xOffset = $$.axis.isCategorized() ? .5 : 0, regions = [], dasharray = "2 2", isWithinRegions = function (withinX, withinRegions) { for (var reg, i = 0; reg = withinRegions[i]; i++) if (reg.start < withinX && withinX <= reg.end) return reg.style; return !1; }; // Check start/end of regions if (isDefined(_regions)) { var getValue = function (v, def) { return isUndefined(v) ? def : isTimeSeries ? parseDate.call($$, v) : v; }; for (var reg, i = 0; reg = _regions[i]; i++) { var start = getValue(reg.start, d[0].x), end = getValue(reg.end, d[d.length - 1].x), style = reg.style || { dasharray: dasharray }; regions[i] = { start: start, end: end, style: style }; } } // Set scales var xValue = isRotated ? function (dt) { return y(dt.value); } : function (dt) { return x(dt.x); }, yValue = isRotated ? function (dt) { return x(dt.x); } : function (dt) { return y(dt.value); }, generateM = function (points) { return "M" + points[0][0] + "," + points[0][1] + "L" + points[1][0] + "," + points[1][1]; }, sWithRegion = isTimeSeries ? function (d0, d1, k, timeseriesDiff) { var x0 = d0.x.getTime(), xDiff = d1.x - d0.x, xv0 = new Date(x0 + xDiff * k), xv1 = new Date(x0 + xDiff * (k + timeseriesDiff)), points = isRotated ? [[y(yp(k)), x(xv0)], [y(yp(k + diff)), x(xv1)]] : [[x(xv0), y(yp(k))], [x(xv1), y(yp(k + diff))]]; return generateM(points); } : function (d0, d1, k, otherDiff) { var points = isRotated ? [[y(yp(k), !0), x(xp(k))], [y(yp(k + otherDiff), !0), x(xp(k + otherDiff))]] : [[x(xp(k), !0), y(yp(k))], [x(xp(k + otherDiff), !0), y(yp(k + otherDiff))]]; return generateM(points); }, axisType = { x: $$.axis.getAxisType("x"), y: $$.axis.getAxisType("y") }, path = ""; for (var data, _i = 0; data = d[_i]; _i++) { var prevData = d[_i - 1], hasPrevData = prevData && isValue(prevData.value), style = isWithinRegions(data.x, regions); // https://github.com/naver/billboard.js/issues/1172 if (isValue(data.value)) // Draw as normal if (isUndefined(regions) || !style || !hasPrevData) path += "" + (_i && hasPrevData ? "L" : "M") + xValue(data) + "," + yValue(data);else if (hasPrevData) { try { style = style.dasharray.split(" "); } catch (e) { style = dasharray.split(" "); } // Draw with region // TODO: Fix for horizotal charts xp = getScale(axisType.x, prevData.x + xOffset, data.x + xOffset), yp = getScale(axisType.y, prevData.value, data.value); var dx = x(data.x) - x(prevData.x), dy = y(data.value) - y(prevData.value), dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); diff = style[0] / dd, diffx2 = diff * style[1]; for (var _j = diff; _j <= 1; _j += diffx2) path += sWithRegion(prevData, data, _j, diff), _j + diffx2 >= 1 && (path += sWithRegion(prevData, data, 1, 0)); } } return path; }, isWithinStep: function isWithinStep(that, y) { return Math.abs(y - getPointer(this.state.event, that)[1]) < 30; }, shouldDrawPointsForLine: function shouldDrawPointsForLine(d) { var linePoint = this.config.line_point; return linePoint === !0 || isArray(linePoint) && linePoint.indexOf(d.id) !== -1; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/point.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ var getTransitionName = function () { return getRandom(); }; /* harmony default export */ var point = ({ hasValidPointType: function hasValidPointType(type) { return /^(circle|rect(angle)?|polygon|ellipse|use)$/i.test(type || this.config.point_type); }, hasValidPointDrawMethods: function hasValidPointDrawMethods(type) { var pointType = type || this.config.point_type; return isObjectType(pointType) && isFunction(pointType.create) && isFunction(pointType.update); }, initialOpacityForCircle: function initialOpacityForCircle(d) { var config = this.config, withoutFadeIn = this.state.withoutFadeIn, opacity = config.point_opacity; return isUndefined(opacity) && (opacity = this.getBaseValue(d) !== null && withoutFadeIn[d.id] ? this.opacityForCircle(d) : "0"), opacity; }, opacityForCircle: function opacityForCircle(d) { var config = this.config, opacity = config.point_opacity; return isUndefined(opacity) && (opacity = config.point_show && !config.point_focus_only ? "1" : "0", opacity = isValue(this.getBaseValue(d)) ? this.isBubbleType(d) || this.isScatterType(d) ? "0.5" : opacity : "0"), opacity; }, initCircle: function initCircle() { var $$ = this, main = $$.$el.main; $$.point = $$.generatePoint(), ($$.hasType("bubble") || $$.hasType("scatter")) && main.select("." + config_classes.chartCircles).empty() && main.select("." + config_classes.chart).append("g").attr("class", config_classes.chartCircles); }, updateTargetForCircle: function updateTargetForCircle(targetsValue, enterNodeValue) { var _this = this, $$ = this, config = $$.config, data = $$.data, $el = $$.$el, selectionEnabled = config.interaction_enabled && config.data_selection_enabled, isSelectable = selectionEnabled && config.data_selection_isselectable, classCircles = $$.getClass("circles", !0); if (config.point_show) { $el.circle || $$.initCircle(); var targets = targetsValue, enterNode = enterNodeValue; // only for scatter & bubble type should generate seprate <g> node if (!targets) { targets = data.targets.filter(function (d) { return _this.isScatterType(d) || _this.isBubbleType(d); }); var mainCircle = $el.main.select("." + config_classes.chartCircles).style("pointer-events", "none").selectAll("." + config_classes.circles).data(targets).attr("class", classCircles); mainCircle.exit().remove(), enterNode = mainCircle.enter(); } // Circles for each data point on lines selectionEnabled && enterNode.append("g").attr("class", function (d) { return $$.generateClass(config_classes.selectedCircles, d.id); }), enterNode.append("g").attr("class", classCircles).style("cursor", function (d) { return isSelectable && isSelectable(d) ? "pointer" : null; }), selectionEnabled && targets.forEach(function (t) { $el.main.selectAll("." + config_classes.selectedCircles + $$.getTargetSelectorSuffix(t.id)).selectAll("" + config_classes.selectedCircle).each(function (d) { d.value = t.values[d.index].value; }); }); } }, updateCircle: function updateCircle(isSub) { isSub === void 0 && (isSub = !1); var $$ = this, config = $$.config, state = $$.state, $el = $$.$el, focusOnly = config.point_focus_only, $root = isSub ? $el.subchart : $el; if (config.point_show && !state.toggling) { var circles = $root.main.selectAll("." + config_classes.circles).selectAll("." + config_classes.circle).data(function (d) { return $$.isLineType(d) && $$.shouldDrawPointsForLine(d) || $$.isBubbleType(d) || $$.isRadarType(d) || $$.isScatterType(d) ? focusOnly ? [d.values[0]] : d.values : []; }); circles.exit().remove(), circles.enter().filter(Boolean).append($$.point("create", this, $$.pointR.bind($$), $$.color)), $root.circle = $root.main.selectAll("." + config_classes.circles + " ." + config_classes.circle).style("stroke", $$.color).style("opacity", $$.initialOpacityForCircle.bind($$)); } }, redrawCircle: function redrawCircle(cx, cy, withTransition, flow, isSub) { isSub === void 0 && (isSub = !1); var $$ = this, rendered = $$.state.rendered, $el = $$.$el, $root = isSub ? $el.subchart : $el, selectedCircles = $root.main.selectAll("." + config_classes.selectedCircle); if (!$$.config.point_show) return []; var fn = $$.point("update", $$, cx, cy, $$.color, withTransition, flow, selectedCircles), posAttr = $$.isCirclePoint() ? "c" : "", t = getRandom(), opacityStyleFn = $$.opacityForCircle.bind($$), mainCircles = []; return $root.circle.each(function (d) { var result = fn.bind(this)(d); result = (withTransition || !rendered ? result.transition(t) : result).style("opacity", opacityStyleFn), mainCircles.push(result); }), [mainCircles, (withTransition ? selectedCircles.transition() : selectedCircles).attr(posAttr + "x", cx).attr(posAttr + "y", cy)]; }, /** * Show focused data point circle * @param {object} d Selected data * @private */ showCircleFocus: function showCircleFocus(d) { var $$ = this, config = $$.config, _$$$state = $$.state, hasRadar = _$$$state.hasRadar, resizing = _$$$state.resizing, toggling = _$$$state.toggling, transiting = _$$$state.transiting, $el = $$.$el, circle = $el.circle; if (transiting === !1 && config.point_focus_only && circle) { var cx = (hasRadar ? $$.radarCircleX : $$.circleX).bind($$), cy = (hasRadar ? $$.radarCircleY : $$.circleY).bind($$), withTransition = toggling || isUndefined(d), fn = $$.point("update", $$, cx, cy, $$.color, !resizing && withTransition); d && (circle = circle.filter(function (t) { var data = d.filter(function (v) { return v.id === t.id; }); return !!data.length && (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).datum(data[0]); })), circle.attr("class", this.updatePointClass.bind(this)).style("opacity", "1").each(function (d) { var id = d.id, index = d.index, value = d.value, visibility = "hidden"; isValue(value) && (fn.bind(this)(d), $$.expandCircles(index, id), visibility = ""), this.style.visibility = visibility; }); } }, /** * Hide focused data point circle * @private */ hideCircleFocus: function hideCircleFocus() { var $$ = this, config = $$.config, circle = $$.$el.circle; config.point_focus_only && circle && ($$.unexpandCircles(), circle.style("visibility", "hidden")); }, circleX: function circleX(d) { return this.xx(d); }, updateCircleY: function updateCircleY(isSub) { isSub === void 0 && (isSub = !1); var $$ = this, getPoints = $$.generateGetLinePoints($$.getShapeIndices($$.isLineType), isSub); return function (d, i) { var id = d.id; return $$.isGrouped(id) ? getPoints(d, i)[0][1] : $$.getYScaleById(id, isSub)($$.getBaseValue(d)); }; }, getCircles: function getCircles(i, id) { var $$ = this, suffix = isValue(i) ? "-" + i : ""; return (id ? $$.$el.main.selectAll("." + config_classes.circles + $$.getTargetSelectorSuffix(id)) : $$.$el.main).selectAll("." + config_classes.circle + suffix); }, expandCircles: function expandCircles(i, id, reset) { var $$ = this, r = $$.pointExpandedR.bind($$); reset && $$.unexpandCircles(); var circles = $$.getCircles(i, id).classed(config_classes.EXPANDED, !0), scale = r(circles) / $$.config.point_r, ratio = 1 - scale; $$.isCirclePoint() ? circles.attr("r", r) : circles.each(function () { var point = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this); if (this.tagName === "circle") point.attr("r", r);else { var _this$getBBox = this.getBBox(), width = _this$getBBox.width, height = _this$getBBox.height, x = ratio * (+point.attr("x") + width / 2), y = ratio * (+point.attr("y") + height / 2); point.attr("transform", "translate(" + x + " " + y + ") scale(" + scale + ")"); } }); }, unexpandCircles: function unexpandCircles(i) { var $$ = this, r = $$.pointR.bind($$), circles = $$.getCircles(i).filter(function () { return (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).classed(config_classes.EXPANDED); }).classed(config_classes.EXPANDED, !1); circles.attr("r", r), $$.isCirclePoint() || circles.attr("transform", "scale(" + r(circles) / $$.config.point_r + ")"); }, pointR: function (d) { var $$ = this, config = $$.config, pointR = config.point_r, r = pointR; return $$.isBubbleType(d) ? r = $$.getBubbleR(d) : isFunction(pointR) && (r = pointR.bind($$.api)(d)), r; }, pointExpandedR: function pointExpandedR(d) { var $$ = this, config = $$.config, scale = $$.isBubbleType(d) ? 1.15 : 1.75; return config.point_focus_expand_enabled ? config.point_focus_expand_r || $$.pointR(d) * scale : $$.pointR(d); }, pointSelectR: function pointSelectR(d) { var $$ = this, selectR = $$.config.point_select_r; return isFunction(selectR) ? selectR(d) : selectR || $$.pointR(d) * 4; }, isWithinCircle: function isWithinCircle(node, r) { var mouse = getPointer(this.state.event, node), element = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(node), prefix = this.isCirclePoint(node) ? "c" : "", cx = +element.attr(prefix + "x"), cy = +element.attr(prefix + "y"); // if node don't have cx/y or x/y attribute value if (!(cx || cy) && node.nodeType === 1) { var _getBoundingRect = getBoundingRect(node), x = _getBoundingRect.x, y = _getBoundingRect.y; cx = x, cy = y; } return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < (r || this.config.point_sensitivity); }, insertPointInfoDefs: function insertPointInfoDefs(point, id) { var $$ = this, copyAttr = function (from, target) { for (var name, attribs = from.attributes, i = 0; name = attribs[i]; i++) name = name.name, target.setAttribute(name, from.getAttribute(name)); }, doc = new DOMParser().parseFromString(point, "image/svg+xml"), node = doc.documentElement, clone = browser_doc.createElementNS(external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.namespaces.svg, node.nodeName.toLowerCase()); if (clone.id = id, clone.style.fill = "inherit", clone.style.stroke = "inherit", copyAttr(node, clone), node.childNodes && node.childNodes.length) { var parent = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(clone); "innerHTML" in clone ? parent.html(node.innerHTML) : toArray(node.childNodes).forEach(function (v) { copyAttr(v, parent.append(v.tagName).node()); }); } $$.$el.defs.node().appendChild(clone); }, pointFromDefs: function pointFromDefs(id) { return this.$el.defs.select("#" + id); }, updatePointClass: function updatePointClass(d) { var $$ = this, circle = $$.$el.circle, pointClass = !1; return (isObject(d) || circle) && (pointClass = d === !0 ? circle.each(function (d) { var className = $$.getClass("circle", !0)(d); this.getAttribute("class").indexOf(config_classes.EXPANDED) > -1 && (className += " " + config_classes.EXPANDED), this.setAttribute("class", className); }) : $$.getClass("circle", !0)(d)), pointClass; }, generateGetLinePoints: function generateGetLinePoints(lineIndices, isSub) { // partial duplication of generateGetBarPoints var $$ = this, config = $$.config, x = $$.getShapeX(0, lineIndices, isSub), y = $$.getShapeY(isSub), lineOffset = $$.getShapeOffset($$.isLineType, lineIndices, isSub), yScale = $$.getYScaleById.bind($$); return function (d, i) { var y0 = yScale.call($$, d.id, isSub)($$.getShapeYMin(d.id)), offset = lineOffset(d, i) || y0, posX = x(d), posY = y(d); config.axis_rotated && (d.value > 0 && posY < y0 || d.value < 0 && y0 < posY) && (posY = y0); // 1 point that marks the line position var point = [posX, posY - (y0 - offset)]; return [point, point, // from here and below, needed for compatibility point, point]; }; }, generatePoint: function generatePoint() { var $$ = this, config = $$.config, datetimeId = $$.state.datetimeId, ids = [], pattern = notEmpty(config.point_pattern) ? config.point_pattern : [config.point_type]; return function (method, context) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) args[_key - 2] = arguments[_key]; return function (d) { var id = $$.getTargetSelectorSuffix(d.id || d.data && d.data.id || d), element = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this); ids.indexOf(id) < 0 && ids.push(id); var point = pattern[ids.indexOf(id) % pattern.length]; if ($$.hasValidPointType(point)) point = $$[point];else if (!$$.hasValidPointDrawMethods(point)) { var pointId = datetimeId + "-point" + id, pointFromDefs = $$.pointFromDefs(pointId); if (pointFromDefs.size() < 1 && $$.insertPointInfoDefs(point, pointId), method === "create") return $$.custom.create.bind(context).apply(void 0, [element, pointId].concat(args)); if (method === "update") return $$.custom.update.bind(context).apply(void 0, [element].concat(args)); } return point[method].bind(context).apply(void 0, [element].concat(args)); }; }; }, custom: { create: function create(element, id, sizeFn, fillStyleFn) { return element.append("use").attr("xlink:href", "#" + id).attr("class", this.updatePointClass.bind(this)).style("fill", fillStyleFn).node(); }, update: function update(element, xPosFn, yPosFn, fillStyleFn, withTransition, flow, selectedCircles) { var _element$node$getBBox = element.node().getBBox(), width = _element$node$getBBox.width, height = _element$node$getBBox.height, xPosFn2 = function (d) { return xPosFn(d) - width / 2; }, mainCircles = element; if (withTransition) { var transitionName = getTransitionName(); flow && mainCircles.attr("x", xPosFn2), mainCircles = mainCircles.transition(transitionName), selectedCircles && selectedCircles.transition(getTransitionName()); } return mainCircles.attr("x", xPosFn2).attr("y", function yPosFn2(d) { return yPosFn(d) - height / 2; }).style("fill", fillStyleFn); } }, // 'circle' data point circle: { create: function create(element, sizeFn, fillStyleFn) { return element.append("circle").attr("class", this.updatePointClass.bind(this)).attr("r", sizeFn).style("fill", fillStyleFn).node(); }, update: function update(element, xPosFn, yPosFn, fillStyleFn, withTransition, flow, selectedCircles) { var $$ = this, mainCircles = element; if ($$.hasType("bubble") && mainCircles.attr("r", $$.pointR.bind($$)), withTransition) { var transitionName = getTransitionName(); flow && mainCircles.attr("cx", xPosFn), mainCircles.attr("cx") && (mainCircles = mainCircles.transition(transitionName)), selectedCircles && selectedCircles.transition(getTransitionName()); } return mainCircles.attr("cx", xPosFn).attr("cy", yPosFn).style("fill", fillStyleFn); } }, // 'rectangle' data point rectangle: { create: function create(element, sizeFn, fillStyleFn) { var rectSizeFn = function (d) { return sizeFn(d) * 2; }; return element.append("rect").attr("class", this.updatePointClass.bind(this)).attr("width", rectSizeFn).attr("height", rectSizeFn).style("fill", fillStyleFn).node(); }, update: function update(element, xPosFn, yPosFn, fillStyleFn, withTransition, flow, selectedCircles) { var $$ = this, r = $$.config.point_r, rectXPosFn = function (d) { return xPosFn(d) - r; }, mainCircles = element; if (withTransition) { var transitionName = getTransitionName(); flow && mainCircles.attr("x", rectXPosFn), mainCircles = mainCircles.transition(transitionName), selectedCircles && selectedCircles.transition(getTransitionName()); } return mainCircles.attr("x", rectXPosFn).attr("y", function rectYPosFn(d) { return yPosFn(d) - r; }).style("fill", fillStyleFn); } } }); ;// CONCATENATED MODULE: ./src/ChartInternal/shape/radar.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Get the position value * @param {boolean} isClockwise If the direction is clockwise * @param {string} type Coordinate type 'x' or 'y' * @param {number} edge Number of edge * @param {number} pos The indexed position * @param {number} range Range value * @param {number} ratio Ratio value * @returns {number} * @private */ function getPosition(isClockwise, type, edge, pos, range, ratio) { var index = isClockwise && pos > 0 ? edge - pos : pos, r = 2 * Math.PI, func = type === "x" ? Math.sin : Math.cos; return range * (1 - ratio * func(index * r / edge)); } // cache key var cacheKey = KEY.radarPoints; /* harmony default export */ var radar = ({ initRadar: function initRadar() { var $$ = this, config = $$.config, current = $$.state.current, $el = $$.$el; $$.hasType("radar") && ($el.radar = $el.main.select("." + config_classes.chart).append("g").attr("class", config_classes.chartRadars), $el.radar.levels = $el.radar.append("g").attr("class", config_classes.levels), $el.radar.axes = $el.radar.append("g").attr("class", config_classes.axis), $el.radar.shapes = $el.radar.append("g").attr("class", config_classes.shapes), current.dataMax = config.radar_axis_max || $$.getMinMaxData().max[0].value); }, getRadarSize: function getRadarSize() { var $$ = this, config = $$.config, _$$$state = $$.state, arcWidth = _$$$state.arcWidth, arcHeight = _$$$state.arcHeight, padding = config.axis_x_categories.length < 4 ? -20 : 10, size = (Math.min(arcWidth, arcHeight) - padding) / 2; return [size, size]; }, updateTargetsForRadar: function updateTargetsForRadar(targets) { var $$ = this, config = $$.config; isEmpty(config.axis_x_categories) && (config.axis_x_categories = getRange(0, getMinMax("max", targets.map(function (v) { return v.values.length; })))), $$.generateRadarPoints(); }, getRadarPosition: function getRadarPosition(type, index, range, ratio) { var $$ = this, config = $$.config, _$$$getRadarSize = $$.getRadarSize(), width = _$$$getRadarSize[0], height = _$$$getRadarSize[1], edge = config.axis_x_categories.length, isClockwise = config.radar_direction_clockwise, pos = toArray(type).map(function (v) { return getPosition(isClockwise, v, edge, index, isDefined(range) ? range : type === "x" ? width : height, isNumber(ratio) ? ratio : config.radar_size_ratio); }); return pos.length === 1 ? pos[0] : pos; }, /** * Generate data points * @private */ generateRadarPoints: function generateRadarPoints() { var $$ = this, targets = $$.data.targets, _$$$getRadarSize2 = $$.getRadarSize(), width = _$$$getRadarSize2[0], height = _$$$getRadarSize2[1], points = $$.cache.get(cacheKey) || {}, size = points._size; size && (size.width === width || size.height === height) || (targets.forEach(function (d) { points[d.id] = d.values.map(function (v, i) { return $$.getRadarPosition(["x", "y"], i, undefined, $$.getRatio("radar", v)); }); }), points._size = { width: width, height: height }, $$.cache.add(cacheKey, points)); }, redrawRadar: function redrawRadar(durationForExit) { var $$ = this, _$$$$el = $$.$el, radar = _$$$$el.radar, main = _$$$$el.main, translate = $$.getTranslate("radar"); translate && (radar.attr("transform", translate), main.select("." + config_classes.chartTexts).attr("transform", translate), $$.generateRadarPoints(), $$.updateRadarLevel(), $$.updateRadarAxes(), $$.updateRadarShape(durationForExit)); }, generateGetRadarPoints: function generateGetRadarPoints() { var points = this.cache.get(cacheKey); return function (d, i) { var point = points[d.id][i]; return [point, point, point, point]; }; }, updateRadarLevel: function updateRadarLevel() { var $$ = this, config = $$.config, state = $$.state, radar = $$.$el.radar, _$$$getRadarSize3 = $$.getRadarSize(), width = _$$$getRadarSize3[0], height = _$$$getRadarSize3[1], depth = config.radar_level_depth, edge = config.axis_x_categories.length, showText = config.radar_level_text_show, radarLevels = radar.levels, levelData = getRange(0, depth), radius = config.radar_size_ratio * Math.min(width, height), levelRatio = levelData.map(function (l) { return radius * ((l + 1) / depth); }), levelTextFormat = (config.radar_level_text_format || function () {}).bind($$.api), points = levelData.map(function (v) { var range = levelRatio[v], pos = getRange(0, edge).map(function (i) { return $$.getRadarPosition(["x", "y"], i, range, 1).join(","); }); return pos.join(" "); }), level = radarLevels.selectAll("." + config_classes.level).data(levelData); level.exit().remove(); var levelEnter = level.enter().append("g").attr("class", function (d, i) { return config_classes.level + " " + config_classes.level + "-" + i; }); levelEnter.append("polygon").style("visibility", config.radar_level_show ? null : "hidden"), showText && (radarLevels.select("text").empty() && radarLevels.append("text").attr("dx", "-.5em").attr("dy", "-.7em").style("text-anchor", "end").text(function () { return levelTextFormat(0); }), levelEnter.append("text").attr("dx", "-.5em").style("text-anchor", "end").text(function (d) { return levelTextFormat(state.current.dataMax / levelData.length * (d + 1)); })), levelEnter.merge(level).attr("transform", function (d) { return "translate(" + (width - levelRatio[d]) + ", " + (height - levelRatio[d]) + ")"; }).selectAll("polygon").attr("points", function (d) { return points[d]; }), showText && radarLevels.selectAll("text").attr("x", function (d) { return isUndefined(d) ? width : points[d].split(",")[0]; }).attr("y", function (d) { return isUndefined(d) ? height : 0; }); }, updateRadarAxes: function updateRadarAxes() { var $$ = this, config = $$.config, radar = $$.$el.radar, _$$$getRadarSize4 = $$.getRadarSize(), width = _$$$getRadarSize4[0], height = _$$$getRadarSize4[1], categories = config.axis_x_categories, axis = radar.axes.selectAll("g").data(categories); axis.exit().remove(); var axisEnter = axis.enter().append("g").attr("class", function (d, i) { return config_classes.axis + "-" + i; }); // axis text if (config.radar_axis_line_show && axisEnter.append("line"), config.radar_axis_text_show && axisEnter.append("text"), axis = axisEnter.merge(axis), config.radar_axis_line_show && axis.select("line").attr("x1", width).attr("y1", height).attr("x2", function (d, i) { return $$.getRadarPosition("x", i); }).attr("y2", function (d, i) { return $$.getRadarPosition("y", i); }), config.radar_axis_text_show) { var _config$radar_axis_te = config.radar_axis_text_position, _config$radar_axis_te2 = _config$radar_axis_te.x, x = _config$radar_axis_te2 === void 0 ? 0 : _config$radar_axis_te2, _config$radar_axis_te3 = _config$radar_axis_te.y, y = _config$radar_axis_te3 === void 0 ? 0 : _config$radar_axis_te3; axis.select("text").style("text-anchor", "middle").attr("dy", ".5em").call(function (selection) { selection.each(function (d) { setTextValue((0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), d + "", [-.6, 1.2]); }); }).datum(function (d, i) { return { index: i }; }).attr("transform", function (d) { isUndefined(this.width) && (this.width = this.getBoundingClientRect().width / 2); var posX = $$.getRadarPosition("x", d.index, undefined, 1), posY = Math.round($$.getRadarPosition("y", d.index, undefined, 1)); return posX > width ? posX += this.width + x : Math.round(posX) < width && (posX -= this.width + x), posY > height ? (posY / 2 === height && this.firstChild.tagName === "tspan" && this.firstChild.setAttribute("dy", "0em"), posY += y) : posY < height && (posY -= y), "translate(" + posX + " " + posY + ")"; }); } $$.bindEvent(); }, bindEvent: function bindEvent() { var $$ = this, config = $$.config, state = $$.state, _$$$$el2 = $$.$el, radar = _$$$$el2.radar, svg = _$$$$el2.svg, focusOnly = config.point_focus_only, _state = state, inputType = _state.inputType, transiting = _state.transiting; if (config.interaction_enabled) { var isMouse = inputType === "mouse", getIndex = function (event) { var target = event.target; // in case of multilined axis text /tspan/i.test(target.tagName) && (target = target.parentNode); var d = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(target).datum(); return d && Object.keys(d).length === 1 ? d.index : undefined; }, hide = function (event) { var index = getIndex(event), noIndex = isUndefined(index); (isMouse || noIndex) && ($$.hideTooltip(), focusOnly ? $$.hideCircleFocus() : $$.unexpandCircles(), isMouse ? $$.setOverOut(!1, index) : noIndex && $$.callOverOutForTouch()); }; radar.axes.selectAll("text").on(isMouse ? "mouseover " : "touchstart", function (event) { if (!transiting) // skip while transiting { state.event = event; var index = getIndex(event); $$.selectRectForSingle(svg.node(), null, index), isMouse ? $$.setOverOut(!0, index) : $$.callOverOutForTouch(index); } }).on("mouseout", isMouse ? hide : null), isMouse || svg.on("touchstart", hide); } }, updateRadarShape: function updateRadarShape(durationForExit) { var $$ = this, targets = $$.data.targets.filter(function (d) { return $$.isRadarType(d); }), points = $$.cache.get(cacheKey), areas = $$.$el.radar.shapes.selectAll("polygon").data(targets), areasEnter = areas.enter().append("g").attr("class", $$.getChartClass("Radar")); areas.exit().transition().duration(durationForExit).remove(), areasEnter.append("polygon").merge(areas).style("fill", $$.color).style("stroke", $$.color).attr("points", function (d) { return points[d.id].join(" "); }), $$.updateTargetForCircle(targets, areasEnter); }, /** * Get data point x coordinate * @param {object} d Data object * @returns {number} * @private */ radarCircleX: function radarCircleX(d) { return this.cache.get(cacheKey)[d.id][d.index][0]; }, /** * Get data point y coordinate * @param {object} d Data object * @returns {number} * @private */ radarCircleY: function radarCircleY(d) { return this.cache.get(cacheKey)[d.id][d.index][1]; } }); ;// CONCATENATED MODULE: ./src/config/Options/common/point.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * point config options */ /* harmony default export */ var common_point = ({ /** * Set point options * @name point * @memberof Options * @type {object} * @property {object} point Point object * @property {boolean} [point.show=true] Whether to show each point in line. * @property {number|Function} [point.r=2.5] The radius size of each point. * - **NOTE:** Disabled for 'bubble' type * @property {boolean} [point.focus.expand.enabled=true] Whether to expand each point on focus. * @property {number} [point.focus.expand.r=point.r*1.75] The radius size of each point on focus. * - **NOTE:** For 'bubble' type, the default is `bubbleSize*1.15` * @property {boolean} [point.focus.only=false] Show point only when is focused. * @property {number|null} [point.opacity=undefined] Set point opacity value. * - **NOTE:** * - `null` will make to not set inline 'opacity' css prop. * - when no value(or undefined) is set, it defaults to set opacity value according its chart types. * @property {number} [point.sensitivity=10] The senstivity value for interaction boundary. * @property {number} [point.select.r=point.r*4] The radius size of each point on selected. * @property {string} [point.type="circle"] The type of point to be drawn * - **NOTE:** * - If chart has 'bubble' type, only circle can be used. * - For IE, non circle point expansions are not supported due to lack of transform support. * - **Available Values:** * - circle * - rectangle * @property {Array} [point.pattern=[]] The type of point or svg shape as string, to be drawn for each line * - **NOTE:** * - This is an `experimental` feature and can have some unexpected behaviors. * - If chart has 'bubble' type, only circle can be used. * - For IE, non circle point expansions are not supported due to lack of transform support. * - **Available Values:** * - circle * - rectangle * - svg shape tag interpreted as string<br> * (ex. `<polygon points='2.5 0 0 5 5 5'></polygon>`) * @see [Demo: point type](https://naver.github.io/billboard.js/demo/#Point.RectanglePoints) * @see [Demo: point focus only](https://naver.github.io/billboard.js/demo/#Point.FocusOnly) * @example * point: { * show: false, * r: 5, * * // or customize the radius * r: function(d) { * ... * return r; * }, * * focus: { * expand: { * enabled: true, * r: 1 * }, * only: true * }, * * // do not set inline 'opacity' css prop setting * opacity: null, * * // set every data point's opacity value * opacity: 0.7, * * select: { * r: 3 * }, * * // having lower value, means how closer to be for interaction * sensitivity: 3, * * // valid values are "circle" or "rectangle" * type: "rectangle", * * // or indicate as pattern * pattern: [ * "circle", * "rectangle", * "<polygon points='0 6 4 0 -4 0'></polygon>" * ], * } */ point_show: !0, point_r: 2.5, point_sensitivity: 10, point_focus_expand_enabled: !0, point_focus_expand_r: undefined, point_focus_only: !1, point_opacity: undefined, point_pattern: [], point_select_r: undefined, point_type: "circle" }); ;// CONCATENATED MODULE: ./src/config/Options/shape/area.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * area config options */ /* harmony default export */ var Options_shape_area = ({ /** * Set area options * @name area * @memberof Options * @type {object} * @property {object} area Area object * @property {boolean} [area.above=false] Set background area above the data chart line. * @property {boolean} [area.front=true] Set area node to be positioned over line node. * @property {boolean|object} [area.linearGradient=false] Set the linear gradient on area.<br><br> * Or customize by giving below object value: * - x {Array}: `x1`, `x2` value * - y {Array}: `y1`, `y2` value * - stops {Array}: Each item should be having `[offset, stop-color, stop-opacity]` values. * @property {boolean} [area.zerobased=true] Set if min or max value will be 0 on area chart. * @see [MDN's &lt;linearGradient>](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient), [&lt;stop>](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/stop) * @see [Demo](https://naver.github.io/billboard.js/demo/#Chart.AreaChart) * @see [Demo: above](https://naver.github.io/billboard.js/demo/#AreaChartOptions.Above) * @see [Demo: linearGradient](https://naver.github.io/billboard.js/demo/#AreaChartOptions.LinearGradient) * @example * area: { * above: true, * zerobased: false, * * // <g class='bb-areas'> will be positioned behind the line <g class='bb-lines'> in stacking order * front: false, * * // will generate follwing linearGradient: * // <linearGradient x1="0" x2="0" y1="0" y2="1"> * // <stop offset="0" stop-color="$DATA_COLOR" stop-opacity="1"></stop> * // <stop offset="1" stop-color="$DATA_COLOR" stop-opacity="0"></stop> * // </linearGradient> * linearGradient: true, * * // Or customized gradient * linearGradient: { * x: [0, 0], // x1, x2 attributes * y: [0, 0], // y1, y2 attributes * stops: [ * // offset, stop-color, stop-opacity * [0, "#7cb5ec", 1], * * // setting 'null' for stop-color, will set its original data color * [0.5, null, 0], * * // setting 'function' for stop-color, will pass data id as argument. * // It should return color string or null value * [1, function(id) { return id === "data1" ? "red" : "blue"; }, 0], * ] * } * } */ area_above: !1, area_front: !0, area_linearGradient: !1, area_zerobased: !0 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/bar.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * bar config options */ /* harmony default export */ var shape_bar = ({ /** * Set bar options * @name bar * @memberof Options * @type {object} * @property {object} bar Bar object * @property {number} [bar.label.threshold=0] Set threshold ratio to show/hide labels. * @property {number} [bar.padding=0] The padding pixel value between each bar. * @property {number} [bar.radius] Set the radius of bar edge in pixel. * - **NOTE:** Works only for non-stacked bar * @property {number} [bar.radius.ratio] Set the radius ratio of bar edge in relative the bar's width. * @property {number} [bar.sensitivity=2] The senstivity offset value for interaction boundary. * @property {number} [bar.width] Change the width of bar chart. * @property {number} [bar.width.ratio=0.6] Change the width of bar chart by ratio. * @property {number} [bar.width.max] The maximum width value for ratio. * @property {number} [bar.width.dataname] Change the width of bar for indicated dataset only. * - **NOTE:** * - Works only for non-stacked bar * - Bars are centered accoding its total width value * @property {number} [bar.width.dataname.ratio=0.6] Change the width of bar chart by ratio. * @property {number} [bar.width.dataname.max] The maximum width value for ratio. * @property {boolean} [bar.zerobased=true] Set if min or max value will be 0 on bar chart. * @see [Demo: bar padding](https://naver.github.io/billboard.js/demo/#BarChartOptions.BarPadding) * @see [Demo: bar radius](https://naver.github.io/billboard.js/demo/#BarChartOptions.BarRadius) * @see [Demo: bar width](https://naver.github.io/billboard.js/demo/#BarChartOptions.BarWidth) * @see [Demo: bar width variant](https://naver.github.io/billboard.js/demo/#BarChartOptions.BarWidthVariant) * @example * bar: { * padding: 1, * * // the 'radius' option can be used only for non-stacking bars * radius: 10, * // or * radius: { * ratio: 0.5 * } * * label: { * // 0.1(10%) ratio value means, the minimum ratio to show text label relative to the y Axis domain range value. * // if data value is below than 0.1, text label will be hidden. * threshold: 0.1, * }, * * // will not have offset between each bar elements for interaction * sensitivity: 0, * * width: 10, * * // or * width: { * ratio: 0.2, * max: 20 * }, * * // or specify width per dataset * width: { * data1: 20, * data2: { * ratio: 0.2, * max: 20 * } * }, * * zerobased: false * } */ bar_label_threshold: 0, bar_padding: 0, bar_radius: undefined, bar_radius_ratio: undefined, bar_sensitivity: 2, bar_width: undefined, bar_width_ratio: .6, bar_width_max: undefined, bar_zerobased: !0 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/bubble.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * bubble config options */ /* harmony default export */ var shape_bubble = ({ /** * Set bubble options * @name bubble * @memberof Options * @type {object} * @property {object} bubble bubble object * @property {number|Function} [bubble.maxR=35] Set the max bubble radius value * @property {boolean} [bubble.zerobased=false] Set if min or max value will be 0 on bubble chart. * @example * bubble: { * // ex) If 100 is the highest value among data bound, the representation bubble of 100 will have radius of 50. * // And the lesser will have radius relatively from tha max value. * maxR: 50, * * // or set radius callback * maxR: function(d) { * // ex. of d param - {x: Fri Oct 06 2017 00:00:00 GMT+0900, value: 80, id: "data2", index: 5} * ... * return Math.sqrt(d.value * 2); * }, * zerobased: false * } */ bubble_maxR: 35, bubble_zerobased: !1 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/candlestick.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * candlestick config options */ /* harmony default export */ var shape_candlestick = ({ /** * Set candlestick options * @name candlestick * @memberof Options * @type {object} * @property {object} candlestick Candlestick object * @property {number} [candlestick.width] Change the width. * @property {number} [candlestick.width.ratio=0.6] Change the width by ratio. * @property {number} [candlestick.width.max] The maximum width value for ratio. * @property {number} [candlestick.width.dataname] Change the width for indicated dataset only. * @property {number} [candlestick.width.dataname.ratio=0.6] Change the width of bar chart by ratio. * @property {number} [candlestick.width.dataname.max] The maximum width value for ratio. * @property {object} [candlestick.color] Color setting. * @property {string|object} [candlestick.color.down] Change down(bearish) value color. * @property {string} [candlestick.color.down.dataname] Change down value color for indicated dataset only. * * @see [Demo](https://naver.github.io/billboard.js/demo/##Chart.CandlestickChart) * @example * candlestick: { * width: 10, * * // or * width: { * ratio: 0.2, * max: 20 * }, * * // or specify width per dataset * width: { * data1: 20, * data2: { * ratio: 0.2, * max: 20 * } * }, * color: { * // spcify bearish color * down: "red", * * // or specify color per dataset * down: { * data1: "red", * data2: "blue", * } * } * } */ candlestick_width: undefined, candlestick_width_ratio: .6, candlestick_width_max: undefined, candlestick_color_down: "red" }); ;// CONCATENATED MODULE: ./src/config/Options/shape/line.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * line config options */ /* harmony default export */ var shape_line = ({ /** * Set line options * @name line * @memberof Options * @type {object} * @property {object} line Line object * @property {boolean} [line.connectNull=false] Set if null data point will be connected or not.<br> * If true set, the region of null data will be connected without any data point. If false set, the region of null data will not be connected and get empty. * @property {Array} [line.classes=undefined] If set, used to set a css class on each line. * @property {boolean} [line.step.type=step] Change step type for step chart.<br> * **Available values:** * - step * - step-before * - step-after * @property {boolean|Array} [line.point=true] Set to false to not draw points on linecharts. Or pass an array of line ids to draw points for. * @property {boolean} [line.zerobased=false] Set if min or max value will be 0 on line chart. * @example * line: { * connectNull: true, * classes: [ * "line-class1", * "line-class2" * ], * step: { * type: "step-after" * }, * * // hide all data points ('point.show=false' also has similar effect) * point: false, * * // show data points for only indicated datas * point: [ * "data1", "data3" * ], * * zerobased: false * } */ line_connectNull: !1, line_step_type: "step", line_zerobased: !1, line_classes: undefined, line_point: !0 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/scatter.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * scatter config options */ /* harmony default export */ var scatter = ({ /** * Set scatter options * @name scatter * @memberof Options * @type {object} * @property {object} [scatter] scatter object * @property {boolean} [scatter.zerobased=false] Set if min or max value will be 0 on scatter chart. * @example * scatter: { * connectNull: true, * step: { * type: "step-after" * }, * * // hide all data points ('point.show=false' also has similar effect) * point: false, * * // show data points for only indicated datas * point: [ * "data1", "data3" * ], * * zerobased: false * } */ scatter_zerobased: !1 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/spline.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * x Axis config options */ /* harmony default export */ var spline = ({ /** * Set spline options * - **Available interpolation type values:** * - basis (d3.curveBasis) * - basis-closed (d3.curveBasisClosed) * - basis-open (d3.curveBasisOpen) * - bundle (d3.curveBundle) * - cardinal (d3.curveCardinal) * - cardinal-closed (d3.curveCardinalClosed) * - cardinal-open (d3.curveCardinalOpen) * - catmull-rom (d3.curveCatmullRom) * - catmull-rom-closed (d3.curveCatmullRomClosed) * - catmull-rom-open (d3.curveCatmullRomOpen) * - monotone-x (d3.curveMonotoneX) * - monotone-y (d3.curveMonotoneY) * - natural (d3.curveNatural) * - linear-closed (d3.curveLinearClosed) * - linear (d3.curveLinear) * - step (d3.curveStep) * - step-after (d3.curveStepAfter) * - step-before (d3.curveStepBefore) * @name spline * @memberof Options * @type {object} * @property {object} spline Spline object * @property {object} spline.interpolation Spline interpolation object * @property {string} [spline.interpolation.type="cardinal"] Interpolation type * @see [Interpolation (d3 v4)](http://bl.ocks.org/emmasaunders/c25a147970def2b02d8c7c2719dc7502) * @example * spline: { * interpolation: { * type: "cardinal" * } * } */ spline_interpolation_type: "cardinal" }); ;// CONCATENATED MODULE: ./src/config/Options/shape/donut.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * donut config options */ /* harmony default export */ var donut = ({ /** * Set donut options * @name donut * @memberof Options * @type {object} * @property {object} donut Donut object * @property {boolean} [donut.label.show=true] Show or hide label on each donut piece. * @property {Function} [donut.label.format] Set formatter for the label on each donut piece. * @property {number} [donut.label.threshold=0.05] Set threshold ratio to show/hide labels. * @property {number|Function} [donut.label.ratio=undefined] Set ratio of labels position. * @property {boolean} [donut.expand=true] Enable or disable expanding donut pieces. * @property {number} [donut.expand.rate=0.98] Set expand rate. * @property {number} [donut.expand.duration=50] Set expand transition time in ms. * @property {number} [donut.width] Set width of donut chart. * @property {string} [donut.title=""] Set title of donut chart. Use `\n` character for line break. * @property {number} [donut.padAngle=0] Set padding between data. * @property {number} [donut.startingAngle=0] Set starting angle where data draws. * @example * donut: { * label: { * show: false, * format: function(value, ratio, id) { * return d3.format("$")(value); * * // to multiline, return with '\n' character * // return value +"%\nLine1\n2Line2"; * }, * * // 0.1(10%) ratio value means, the minimum ratio to show text label relative to the total value. * // if data value is below than 0.1, text label will be hidden. * threshold: 0.1, * * // set ratio callback. Should return ratio value * ratio: function(d, radius, h) { * ... * return ratio; * }, * // or set ratio number * ratio: 0.5 * }, * * // disable expand transition for interaction * expand: false, * * expand: { * // set duration of expand transition to 500ms. * duration: 500, * * // set expand area rate * rate: 1 * }, * * width: 10, * padAngle: 0.2, * startingAngle: 1, * title: "Donut Title" * * // title with line break * title: "Title1\nTitle2" * } */ donut_label_show: !0, donut_label_format: undefined, donut_label_threshold: .05, donut_label_ratio: undefined, donut_width: undefined, donut_title: "", donut_expand: {}, donut_expand_rate: .98, donut_expand_duration: 50, donut_padAngle: 0, donut_startingAngle: 0 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/gauge.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * gauge config options */ /* harmony default export */ var shape_gauge = ({ /** * Set gauge options * @name gauge * @memberof Options * @type {object} * @property {object} gauge Gauge object * @property {boolean} [gauge.background=""] Set background color. (The `.bb-chart-arcs-background` element) * @property {boolean} [gauge.fullCircle=false] Show full circle as donut. When set to 'true', the max label will not be showed due to start and end points are same location. * @property {boolean} [gauge.label.show=true] Show or hide label on gauge. * @property {Function} [gauge.label.format] Set formatter for the label on gauge. Label text can be multilined with `\n` character. * @property {Function} [gauge.label.extents] Set customized min/max label text. * @property {number} [gauge.label.threshold=0] Set threshold ratio to show/hide labels. * @property {boolean} [gauge.expand=true] Enable or disable expanding gauge. * @property {number} [gauge.expand.rate=0.98] Set expand rate. * @property {number} [gauge.expand.duration=50] Set the expand transition time in milliseconds. * @property {number} [gauge.min=0] Set min value of the gauge. * @property {number} [gauge.max=100] Set max value of the gauge. * @property {number} [gauge.startingAngle=-1 * Math.PI / 2] Set starting angle where data draws. * * **Limitations:** * - when `gauge.fullCircle=false`: * - -1 * Math.PI / 2 <= startingAngle <= Math.PI / 2 * - `startingAngle <= -1 * Math.PI / 2` defaults to `-1 * Math.PI / 2` * - `startingAngle >= Math.PI / 2` defaults to `Math.PI / 2` * - when `gauge.fullCircle=true`: * - -1 * Math.PI < startingAngle < Math.PI * - `startingAngle < -1 * Math.PI` defaults to `Math.PI` * - `startingAngle > Math.PI` defaults to `Math.PI` * @property {number} [gauge.arcLength=100] Set the length of the arc to be drawn in percent from -100 to 100.<br> * Negative value will draw the arc **counterclockwise**. * * **Limitations:** * - -100 <= arcLength (in percent) <= 100 * - 'arcLength < -100' defaults to -100 * - 'arcLength > 100' defaults to 100 * @property {string} [gauge.title=""] Set title of gauge chart. Use `\n` character for line break. * @property {string} [gauge.units] Set units of the gauge. * @property {number} [gauge.width] Set width of gauge chart. * @property {string} [gauge.type="single"] Set type of gauge to be displayed.<br><br> * **Available Values:** * - single * - multi * @property {string} [gauge.arcs.minWidth=5] Set minimal width of gauge arcs until the innerRadius disappears. * @see [Demo: archLength](https://naver.github.io/billboard.js/demo/#GaugeChartOptions.GaugeArcLength) * @see [Demo: startingAngle](https://naver.github.io/billboard.js/demo/#GaugeChartOptions.GaugeStartingAngle) * @example * gauge: { * background: "#eee", // will set 'fill' css prop for '.bb-chart-arcs-background' classed element. * fullCircle: false, * label: { * show: false, * format: function(value, ratio) { * return value; * * // to multiline, return with '\n' character * // return value +"%\nLine1\n2Line2"; * }, * * extents: function(value, isMax) { * return (isMax ? "Max:" : "Min:") + value; * }, * * // 0.1(10%) ratio value means, the minimum ratio to show text label relative to the total value. * // if data value is below than 0.1, text label will be hidden. * threshold: 0.1, * }, * * // disable expand transition for interaction * expand: false, * * expand: { * // set duration of expand transition to 500ms. * duration: 500, * * // set expand area rate * rate: 1 * }, * * min: -100, * max: 200, * type: "single" // or 'multi' * title: "Title Text", * units: "%", * width: 10, * startingAngle: -1 * Math.PI / 2, * arcLength: 100, * arcs: { * minWidth: 5 * } * } */ gauge_background: "", gauge_fullCircle: !1, gauge_label_show: !0, gauge_label_format: undefined, gauge_label_extents: undefined, gauge_label_threshold: 0, gauge_min: 0, gauge_max: 100, gauge_type: "single", gauge_startingAngle: -1 * Math.PI / 2, gauge_arcLength: 100, gauge_title: "", gauge_units: undefined, gauge_width: undefined, gauge_arcs_minWidth: 5, gauge_expand: {}, gauge_expand_rate: .98, gauge_expand_duration: 50 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/pie.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * x Axis config options */ /* harmony default export */ var pie = ({ /** * Set pie options * @name pie * @memberof Options * @type {object} * @property {object} pie Pie object * @property {boolean} [pie.label.show=true] Show or hide label on each pie piece. * @property {Function} [pie.label.format] Set formatter for the label on each pie piece. * @property {number} [pie.label.threshold=0.05] Set threshold ratio to show/hide labels. * @property {number|Function} [pie.label.ratio=undefined] Set ratio of labels position. * @property {boolean|object} [pie.expand=true] Enable or disable expanding pie pieces. * @property {number} [pie.expand.rate=0.98] Set expand rate. * @property {number} [pie.expand.duration=50] Set expand transition time in ms. * @property {number|object} [pie.innerRadius=0] Sets the inner radius of pie arc. * @property {number|object|undefined} [pie.outerRadius=undefined] Sets the outer radius of pie arc. * @property {number} [pie.padAngle=0] Set padding between data. * @property {number} [pie.padding=0] Sets the gap between pie arcs. * @property {number} [pie.startingAngle=0] Set starting angle where data draws. * @see [Demo: expand.rate](https://naver.github.io/billboard.js/demo/#PieChartOptions.ExpandRate) * @see [Demo: innerRadius](https://naver.github.io/billboard.js/demo/#PieChartOptions.InnerRadius) * @see [Demo: outerRadius](https://naver.github.io/billboard.js/demo/#PieChartOptions.OuterRadius) * @see [Demo: startingAngle](https://naver.github.io/billboard.js/demo/#PieChartOptions.StartingAngle) * @example * pie: { * label: { * show: false, * format: function(value, ratio, id) { * return d3.format("$")(value); * * // to multiline, return with '\n' character * // return value +"%\nLine1\n2Line2"; * }, * * // 0.1(10%) ratio value means, the minimum ratio to show text label relative to the total value. * // if data value is below than 0.1, text label will be hidden. * threshold: 0.1, * * // set ratio callback. Should return ratio value * ratio: function(d, radius, h) { * ... * return ratio; * }, * // or set ratio number * ratio: 0.5 * }, * * // disable expand transition for interaction * expand: false, * * expand: { * // set duration of expand transition to 500ms. * duration: 500, * * // set expand area rate * rate: 1 * }, * * innerRadius: 0, * * // set different innerRadius for each data * innerRadius: { * data1: 10, * data2: 0 * }, * * outerRadius: 100, * * // set different outerRadius for each data * outerRadius: { * data1: 50, * data2: 100 * } * * padAngle: 0.1, * padding: 0, * startingAngle: 1 * } */ pie_label_show: !0, pie_label_format: undefined, pie_label_threshold: .05, pie_label_ratio: undefined, pie_expand: {}, pie_expand_rate: .98, pie_expand_duration: 50, pie_innerRadius: 0, pie_outerRadius: undefined, pie_padAngle: 0, pie_padding: 0, pie_startingAngle: 0 }); ;// CONCATENATED MODULE: ./src/config/Options/shape/radar.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * x Axis config options */ /* harmony default export */ var shape_radar = ({ /** * Set radar options * - **NOTE:** * > When x tick text contains `\n`, it's used as line break. * @name radar * @memberof Options * @type {object} * @property {object} radar Radar object * @property {number} [radar.axis.max=undefined] The max value of axis. If not given, it'll take the max value from the given data. * @property {boolean} [radar.axis.line.show=true] Show or hide axis line. * @property {number} [radar.axis.text.position.x=0] x coordinate position, relative the original. * @property {number} [radar.axis.text.position.y=0] y coordinate position, relative the original. * @property {boolean} [radar.axis.text.show=true] Show or hide axis text. * @property {boolean} [radar.direction.clockwise=false] Set the direction to be drawn. * @property {number} [radar.level.depth=3] Set the level depth. * @property {boolean} [radar.level.show=true] Show or hide level. * @property {Function} [radar.level.text.format] Set format function for the level value.<br>- Default value: `(x) => x % 1 === 0 ? x : x.toFixed(2)` * @property {boolean} [radar.level.text.show=true] Show or hide level text. * @property {number} [radar.size.ratio=0.87] Set size ratio. * @see [Demo](https://naver.github.io/billboard.js/demo/#Chart.RadarChart) * @see [Demo: radar axis](https://naver.github.io/billboard.js/demo/#RadarChartOptions.RadarAxis) * @see [Demo: radar level](https://naver.github.io/billboard.js/demo/#RadarChartOptions.RadarLevel) * @see [Demo: radar size](https://naver.github.io/billboard.js/demo/#RadarChartOptions.RadarSize) * @see [Demo: radar axis multiline](https://naver.github.io/billboard.js/demo/#RadarChartOptions.RadarAxisMultiline) * @example * radar: { * axis: { * max: 50, * line: { * show: false * }, * text: { * position: { * x: 0, * y: 0 * }, * show: false * } * }, * direction: { * clockwise: true * }, * level: { * show: false, * text: { * format: function(x) { * return x + "%"; * }, * show: true * } * }, * size: { * ratio: 0.7 * } * } */ radar_axis_max: undefined, radar_axis_line_show: !0, radar_axis_text_show: !0, radar_axis_text_position: {}, radar_level_depth: 3, radar_level_show: !0, radar_level_text_format: function radar_level_text_format(x) { return x % 1 === 0 ? x : x.toFixed(2); }, radar_level_text_show: !0, radar_size_ratio: .87, radar_direction_clockwise: !1 }); ;// CONCATENATED MODULE: ./src/config/resolver/shape.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // Axis // Shape // Options // Non-Axis based /** * Extend Axis * @param {Array} module Module to be extended * @param {Array} option Option object to be extended * @private */ function extendAxis(module, option) { extend(ChartInternal.prototype, internal.concat(module)), extend(Chart.prototype, api), Options.setOptions(options.concat(option || [])); } /** * Extend Line type modules * @param {object} module Module to be extended * @param {Array} option Option object to be extended * @private */ function extendLine(module, option) { extendAxis([point, line].concat(module || [])), Options.setOptions([common_point, shape_line].concat(option || [])); } /** * Extend Arc type modules * @param {Array} module Module to be extended * @param {Array} option Option object to be extended * @private */ function extendArc(module, option) { extend(ChartInternal.prototype, [arc].concat(module || [])), Options.setOptions(option); } // Area types var _area = function area() { return extendLine(shape_area, [Options_shape_area]), (_area = function area() { return TYPE.AREA; })(); }, areaLineRange = function () { return extendLine(shape_area, [Options_shape_area]), (areaLineRange = function () { return TYPE.AREA_LINE_RANGE; })(); }, areaSpline = function () { return extendLine(shape_area, [Options_shape_area, spline]), (areaSpline = function () { return TYPE.AREA_SPLINE; })(); }, areaSplineRange = function () { return extendLine(shape_area, [Options_shape_area, spline]), (areaSplineRange = function () { return TYPE.AREA_SPLINE_RANGE; })(); }, areaStep = function () { return extendLine(shape_area, [Options_shape_area]), (areaStep = function () { return TYPE.AREA_STEP; })(); }, resolver_shape_line = function () { return extendLine(), (resolver_shape_line = function () { return TYPE.LINE; })(); }, shape_spline = function () { return extendLine(undefined, [spline]), (shape_spline = function () { return TYPE.SPLINE; })(); }, step = function () { return extendLine(), (step = function () { return TYPE.STEP; })(); }, shape_donut = function () { return extendArc(undefined, [donut]), (shape_donut = function () { return TYPE.DONUT; })(); }, resolver_shape_gauge = function () { return extendArc([gauge], [shape_gauge]), (resolver_shape_gauge = function () { return TYPE.GAUGE; })(); }, shape_pie = function () { return extendArc(undefined, [pie]), (shape_pie = function () { return TYPE.PIE; })(); }, resolver_shape_radar = function () { return extendArc([point, radar], [common_point, shape_radar]), (resolver_shape_radar = function () { return TYPE.RADAR; })(); }, resolver_shape_bar = function () { return extendAxis([bar], shape_bar), (resolver_shape_bar = function () { return TYPE.BAR; })(); }, resolver_shape_bubble = function () { return extendAxis([point, bubble], [shape_bubble, common_point]), (resolver_shape_bubble = function () { return TYPE.BUBBLE; })(); }, resolver_shape_candlestick = function () { return extendAxis([candlestick], [shape_candlestick]), (resolver_shape_candlestick = function () { return TYPE.CANDLESTICK; })(); }, shape_scatter = function () { return extendAxis([point], [common_point, scatter]), (shape_scatter = function () { return TYPE.SCATTER; })(); }; ;// CONCATENATED MODULE: ./src/Chart/api/selection.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var selection = ({ /** * Get selected data points.<br><br> * By this API, you can get selected data points information. To use this API, data.selection.enabled needs to be set true. * @function selected * @instance * @memberof Chart * @param {string} [targetId] You can filter the result by giving target id that you want to get. If not given, all of data points will be returned. * @returns {Array} dataPoint Array of the data points.<br>ex.) `[{x: 1, value: 200, id: "data1", index: 1, name: "data1"}, ...]` * @example * // all selected data points will be returned. * chart.selected(); * // --> ex.) [{x: 1, value: 200, id: "data1", index: 1, name: "data1"}, ... ] * * // all selected data points of data1 will be returned. * chart.selected("data1"); */ selected: function selected(targetId) { var $$ = this.internal, dataPoint = []; return $$.$el.main.selectAll("." + (config_classes.shapes + $$.getTargetSelectorSuffix(targetId))).selectAll("." + config_classes.shape).filter(function () { return (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this).classed(config_classes.SELECTED); }).each(function (d) { return dataPoint.push(d); }), dataPoint; }, /** * Set data points to be selected. ([`data.selection.enabled`](Options.html#.data%25E2%2580%25A4selection%25E2%2580%25A4enabled) option should be set true to use this method) * @function select * @instance * @memberof Chart * @param {string|Array} [ids] id value to get selected. * @param {Array} [indices] The index array of data points. If falsy value given, will select all data points. * @param {boolean} [resetOther] Unselect already selected. * @example * // select all data points * chart.select(); * * // select all from 'data2' * chart.select("data2"); * * // select all from 'data1' and 'data2' * chart.select(["data1", "data2"]); * * // select from 'data1', indices 2 and unselect others selected * chart.select("data1", [2], true); * * // select from 'data1', indices 0, 3 and 5 * chart.select("data1", [0, 3, 5]); */ select: function select(ids, indices, resetOther) { var $$ = this.internal, config = $$.config, $el = $$.$el; config.data_selection_enabled && $el.main.selectAll("." + config_classes.shapes).selectAll("." + config_classes.shape).each(function (d, i) { var shape = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), id = d.data ? d.data.id : d.id, toggle = $$.getToggle(this, d).bind($$), isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0, isTargetIndex = !indices || indices.indexOf(i) >= 0, isSelected = shape.classed(config_classes.SELECTED); // line/area selection not supported yet shape.classed(config_classes.line) || shape.classed(config_classes.area) || (isTargetId && isTargetIndex ? config.data_selection_isselectable.bind($$.api)(d) && !isSelected && toggle(!0, shape.classed(config_classes.SELECTED, !0), d, i) : isDefined(resetOther) && resetOther && isSelected && toggle(!1, shape.classed(config_classes.SELECTED, !1), d, i)); }); }, /** * Set data points to be un-selected. * @function unselect * @instance * @memberof Chart * @param {string|Array} [ids] id value to be unselected. * @param {Array} [indices] The index array of data points. If falsy value given, will select all data points. * @example * // unselect all data points * chart.unselect(); * * // unselect all from 'data1' * chart.unselect("data1"); * * // unselect from 'data1', indices 2 * chart.unselect("data1", [2]); */ unselect: function unselect(ids, indices) { var $$ = this.internal, config = $$.config, $el = $$.$el; config.data_selection_enabled && $el.main.selectAll("." + config_classes.shapes).selectAll("." + config_classes.shape).each(function (d, i) { var shape = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), id = d.data ? d.data.id : d.id, toggle = $$.getToggle(this, d).bind($$), isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0, isTargetIndex = !indices || indices.indexOf(i) >= 0, isSelected = shape.classed(config_classes.SELECTED); // line/area selection not supported yet shape.classed(config_classes.line) || shape.classed(config_classes.area) || isTargetId && isTargetIndex && config.data_selection_isselectable.bind($$.api)(d) && isSelected && toggle(!1, shape.classed(config_classes.SELECTED, !1), d, i); }); } }); ;// CONCATENATED MODULE: ./src/Chart/api/subchart.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var subchart = ({ subchart: { /** * Show subchart * - **NOTE:** for ESM imports, needs to import 'subchart' exports and instantiate it by calling `subchart()`. * @function subchartβ€€show * @instance * @memberof Chart * @example * // for ESM imports, needs to import 'subchart' and must be instantiated first to enable subchart's API. * import {subchart} from "billboard.js"; * * const chart = bb.generate({ * ... * subchart: { * // need to be instantiated by calling 'subchart()' * enabled: subchart() * * // in case don't want subchart to be shown at initialization, instantiate with '!subchart()' * enabled: !subchart() * } * }); * * chart.subchart.show(); */ show: function () { var $$ = this.internal, subchart = $$.$el.subchart, config = $$.config, show = config.subchart_show; if (!show) { config.subchart_show = !show, subchart.main || $$.initSubchart(); var $target = subchart.main.selectAll("." + config_classes.target); // need to cover when new data has been loaded $$.data.targets.length !== $target.size() && ($$.updateSizes(), $$.updateTargetsForSubchart($$.data.targets), $target = subchart.main.selectAll("." + config_classes.target)), $target.style("opacity", "1"), subchart.main.style("display", null), this.flush(); } }, /** * Hide generated subchart * - **NOTE:** for ESM imports, needs to import 'subchart' exports and instantiate it by calling `subchart()`. * @function subchartβ€€hide * @instance * @memberof Chart * @example * chart.subchart.hide(); */ hide: function hide() { var $$ = this.internal, subchart = $$.$el.subchart, config = $$.config; config.subchart_show && subchart.main.style("display") !== "none" && (config.subchart_show = !1, subchart.main.style("display", "none"), this.flush()); }, /** * Toggle the visiblity of subchart * - **NOTE:** for ESM imports, needs to import 'subchart' exports and instantiate it by calling `subchart()`. * @function subchartβ€€toggle * @instance * @memberof Chart * @example * // When subchart is hidden, will be shown * // When subchart is shown, will be hidden * chart.subchart.toggle(); */ toggle: function toggle() { var $$ = this.internal, config = $$.config; this.subchart[config.subchart_show ? "hide" : "show"](); } } }); // EXTERNAL MODULE: external {"commonjs":"d3-zoom","commonjs2":"d3-zoom","amd":"d3-zoom","root":"d3"} var external_commonjs_d3_zoom_commonjs2_d3_zoom_amd_d3_zoom_root_d3_ = __webpack_require__(14); ;// CONCATENATED MODULE: ./src/Chart/api/zoom.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Check if the given domain is within zoom range * @param {Array} domain domain value * @param {Array} range zoom range value * @returns {boolean} * @private */ function withinRange(domain, range) { var min = range[0], max = range[1]; return domain.every(function (v, i) { return i === 0 ? v >= min : v <= max; }); } /** * Zoom by giving x domain. * - **NOTE:** * - For `wheel` type zoom, the minimum zoom range will be set as the given domain. To get the initial state, [.unzoom()](#unzoom) should be called. * - To be used [zoom.enabled](Options.html#.zoom) option should be set as `truthy`. * @function zoom * @instance * @memberof Chart * @param {Array} domainValue If domain is given, the chart will be zoomed to the given domain. If no argument is given, the current zoomed domain will be returned. * @returns {Array} domain value in array * @example * // Zoom to specified domain * chart.zoom([10, 20]); * * // Get the current zoomed domain * chart.zoom(); */ var zoom = function (domainValue) { var resultDomain, $$ = this.internal, config = $$.config, scale = $$.scale, domain = domainValue; if (!(config.zoom_enabled && domain)) resultDomain = scale.zoom ? scale.zoom.domain() : scale.x.orgDomain();else if ($$.axis.isTimeSeries() && (domain = domain.map(function (x) { return parseDate.bind($$)(x); })), withinRange(domain, $$.getZoomDomain())) { if ($$.api.tooltip.hide(), config.subchart_show) { var xScale = scale.zoom || scale.x; $$.brush.getSelection().call($$.brush.move, [xScale(domain[0]), xScale(domain[1])]), resultDomain = domain; } else scale.x.domain(domain), scale.zoom = scale.x, $$.axis.x.scale(scale.zoom), resultDomain = scale.zoom.orgDomain(); $$.redraw({ withTransition: !0, withY: config.zoom_rescale, withDimension: !1 }), $$.setZoomResetButton(), callFn(config.zoom_onzoom, $$.api, resultDomain); } return resultDomain; }; extend(zoom, { /** * Enable and disable zooming. * @function zoomβ€€enable * @instance * @memberof Chart * @param {string|boolean} enabled Possible string values are "wheel" or "drag". If enabled is true, "wheel" will be used. If false is given, zooming will be disabled.<br>When set to false, the current zooming status will be reset. * @example * // Enable zooming using the mouse wheel * chart.zoom.enable(true); * // Or * chart.zoom.enable("wheel"); * * // Enable zooming by dragging * chart.zoom.enable("drag"); * * // Disable zooming * chart.zoom.enable(false); */ enable: function enable(enabled) { var $$ = this.internal, config = $$.config; /^(drag|wheel)$/.test(enabled) && (config.zoom_type = enabled), config.zoom_enabled = !!enabled, $$.zoom ? enabled === !1 && $$.bindZoomEvent(!1) : ($$.initZoom(), $$.bindZoomEvent()), $$.updateAndRedraw(); }, /** * Set or get x Axis maximum zoom range value * @function zoomβ€€max * @instance * @memberof Chart * @param {number} [max] maximum value to set for zoom * @returns {number} zoom max value * @example * // Set maximum range value * chart.zoom.max(20); */ max: function max(_max) { var $$ = this.internal, config = $$.config, xDomain = $$.org.xDomain; return (_max === 0 || _max) && (config.zoom_x_max = getMinMax("max", [xDomain[1], _max])), config.zoom_x_max; }, /** * Set or get x Axis minimum zoom range value * @function zoomβ€€min * @instance * @memberof Chart * @param {number} [min] minimum value to set for zoom * @returns {number} zoom min value * @example * // Set minimum range value * chart.zoom.min(-1); */ min: function min(_min) { var $$ = this.internal, config = $$.config, xDomain = $$.org.xDomain; return (_min === 0 || _min) && (config.zoom_x_min = getMinMax("min", [xDomain[0], _min])), config.zoom_x_min; }, /** * Set zoom range * @function zoomβ€€range * @instance * @memberof Chart * @param {object} [range] zoom range * @returns {object} zoom range value * { * min: 0, * max: 100 * } * @example * chart.zoom.range({ * min: 10, * max: 100 * }); */ range: function range(_range) { var zoom = this.zoom; if (isObject(_range)) { var min = _range.min, max = _range.max; isDefined(min) && zoom.min(min), isDefined(max) && zoom.max(max); } return { min: zoom.min(), max: zoom.max() }; } }); /* harmony default export */ var api_zoom = ({ zoom: zoom, /** * Unzoom zoomed area * @function unzoom * @instance * @memberof Chart * @example * chart.unzoom(); */ unzoom: function unzoom() { var $$ = this.internal, config = $$.config; if ($$.scale.zoom) { config.subchart_show ? $$.brush.getSelection().call($$.brush.move, null) : $$.zoom.updateTransformScale(external_commonjs_d3_zoom_commonjs2_d3_zoom_amd_d3_zoom_root_d3_.zoomIdentity), $$.updateZoom(!0), $$.zoom.resetBtn && $$.zoom.resetBtn.style("display", "none"); // reset transform var eventRects = $$.$el.main.select("." + config_classes.eventRects); (0,external_commonjs_d3_zoom_commonjs2_d3_zoom_amd_d3_zoom_root_d3_.zoomTransform)(eventRects.node()) !== external_commonjs_d3_zoom_commonjs2_d3_zoom_amd_d3_zoom_root_d3_.zoomIdentity && $$.zoom.transform(eventRects, external_commonjs_d3_zoom_commonjs2_d3_zoom_amd_d3_zoom_root_d3_.zoomIdentity), $$.redraw({ withTransition: !0, withUpdateXDomain: !0, withUpdateOrgXDomain: !0, withY: config.zoom_rescale }); } } }); // EXTERNAL MODULE: external {"commonjs":"d3-color","commonjs2":"d3-color","amd":"d3-color","root":"d3"} var external_commonjs_d3_color_commonjs2_d3_color_amd_d3_color_root_d3_ = __webpack_require__(13); ;// CONCATENATED MODULE: ./src/ChartInternal/interactions/drag.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Module used for data.selection.draggable option */ /* harmony default export */ var drag = ({ /** * Called when dragging. * Data points can be selected. * @private * @param {object} mouse Object */ drag: function drag(mouse) { var $$ = this, config = $$.config, state = $$.state, main = $$.$el.main, isSelectionGrouped = config.data_selection_grouped, isSelectable = config.interaction_enabled && config.data_selection_isselectable; if (!$$.hasArcType() && config.data_selection_enabled && ( // do nothing if not selectable !config.zoom_enabled || $$.zoom.altDomain) && config.data_selection_multiple // skip when single selection because drag is used for multiple selection ) { var _ref = state.dragStart || [0, 0], sx = _ref[0], sy = _ref[1], mx = mouse[0], my = mouse[1], minX = Math.min(sx, mx), maxX = Math.max(sx, mx), minY = isSelectionGrouped ? state.margin.top : Math.min(sy, my), maxY = isSelectionGrouped ? state.height : Math.max(sy, my); main.select("." + config_classes.dragarea).attr("x", minX).attr("y", minY).attr("width", maxX - minX).attr("height", maxY - minY), main.selectAll("." + config_classes.shapes).selectAll("." + config_classes.shape).filter(function (d) { return isSelectable && isSelectable.bind($$.api)(d); }).each(function (d, i) { var toggle, shape = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this), isSelected = shape.classed(config_classes.SELECTED), isIncluded = shape.classed(config_classes.INCLUDED), isWithin = !1; if (shape.classed(config_classes.circle)) { var x = +shape.attr("cx") * 1, y = +shape.attr("cy") * 1; toggle = $$.togglePoint, isWithin = minX < x && x < maxX && minY < y && y < maxY; } else if (shape.classed(config_classes.bar)) { var _getPathBox = getPathBox(this), _x = _getPathBox.x, y = _getPathBox.y, width = _getPathBox.width, height = _getPathBox.height; toggle = $$.togglePath, isWithin = !(maxX < _x || _x + width < minX) && !(maxY < y || y + height < minY); } else // line/area selection not supported yet return; // @ts-ignore isWithin ^ isIncluded && (shape.classed(config_classes.INCLUDED, !isIncluded), shape.classed(config_classes.SELECTED, !isSelected), toggle.call($$, !isSelected, shape, d, i)); }); } }, /** * Called when the drag starts. * Adds and Shows the drag area. * @private * @param {object} mouse Object */ dragstart: function dragstart(mouse) { var $$ = this, config = $$.config, state = $$.state, main = $$.$el.main; $$.hasArcType() || !config.data_selection_enabled || (state.dragStart = mouse, main.select("." + config_classes.chart).append("rect").attr("class", config_classes.dragarea).style("opacity", "0.1"), $$.setDragStatus(!0)); }, /** * Called when the drag finishes. * Removes the drag area. * @private */ dragend: function dragend() { var $$ = this, config = $$.config, main = $$.$el.main; $$.hasArcType() || !config.data_selection_enabled || (main.select("." + config_classes.dragarea).transition().duration(100).style("opacity", "0").remove(), main.selectAll("." + config_classes.shape).classed(config_classes.INCLUDED, !1), $$.setDragStatus(!1)); } }); ;// CONCATENATED MODULE: ./src/ChartInternal/internals/selection.ts function selection_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function selection_objectSpread(target) { for (var source, i = 1; i < arguments.length; i++) source = arguments[i] == null ? {} : arguments[i], i % 2 ? selection_ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : selection_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); return target; } /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var internals_selection = (selection_objectSpread(selection_objectSpread({}, drag), {}, { /** * Select a point * @param {object} target Target point * @param {object} d Data object * @param {number} i Index number * @private */ selectPoint: function selectPoint(target, d, i) { var $$ = this, config = $$.config, main = $$.$el.main, isRotated = config.axis_rotated, cx = (isRotated ? $$.circleY : $$.circleX).bind($$), cy = (isRotated ? $$.circleX : $$.circleY).bind($$), r = $$.pointSelectR.bind($$); // add selected-circle on low layer g callFn(config.data_onselected, $$.api, d, target.node()), main.select("." + config_classes.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll("." + config_classes.selectedCircle + "-" + i).data([d]).enter().append("circle").attr("class", function () { return $$.generateClass(config_classes.selectedCircle, i); }).attr("cx", cx).attr("cy", cy).attr("stroke", $$.color).attr("r", function (d2) { return $$.pointSelectR(d2) * 1.4; }).transition().duration(100).attr("r", r); }, /** * Unelect a point * @param {object} target Target point * @param {object} d Data object * @param {number} i Index number * @private */ unselectPoint: function unselectPoint(target, d, i) { var $$ = this, config = $$.config, $el = $$.$el; // remove selected-circle from low layer g callFn(config.data_onunselected, $$.api, d, target.node()), $el.main.select("." + config_classes.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll("." + config_classes.selectedCircle + "-" + i).transition().duration(100).attr("r", 0).remove(); }, /** * Toggles the selection of points * @param {boolean} selected whether or not to select. * @param {object} target Target object * @param {object} d Data object * @param {number} i Index number * @private */ togglePoint: function togglePoint(selected, target, d, i) { var method = (selected ? "" : "un") + "selectPoint"; this[method](target, d, i); }, /** * Select a path * @param {object} target Target path * @param {object} d Data object * @private */ selectPath: function selectPath(target, d) { var $$ = this, config = $$.config; callFn(config.data_onselected, $$.api, d, target.node()), config.interaction_brighten && target.transition().duration(100).style("fill", function () { return (0,external_commonjs_d3_color_commonjs2_d3_color_amd_d3_color_root_d3_.rgb)($$.color(d)).brighter(.75); }); }, /** * Unelect a path * @private * @param {object} target Target path * @param {object} d Data object */ unselectPath: function unselectPath(target, d) { var $$ = this, config = $$.config; callFn(config.data_onunselected, $$.api, d, target.node()), config.interaction_brighten && target.transition().duration(100).style("fill", function () { return $$.color(d); }); }, /** * Toggles the selection of lines * @param {boolean} selected whether or not to select. * @param {object} target Target object * @param {object} d Data object * @param {number} i Index number * @private */ togglePath: function togglePath(selected, target, d, i) { this[(selected ? "" : "un") + "selectPath"](target, d, i); }, /** * Returns the toggle method of the target * @param {object} that shape * @param {object} d Data object * @returns {Function} toggle method * @private */ getToggle: function getToggle(that, d) { var $$ = this; return that.nodeName === "path" ? $$.togglePath : $$.isStepType(d) ? function () {} : // circle is hidden in step chart, so treat as within the click area $$.togglePoint; }, /** * Toggles the selection of shapes * @param {object} that shape * @param {object} d Data object * @param {number} i Index number * @private */ toggleShape: function toggleShape(that, d, i) { var toggledShape, $$ = this, config = $$.config, main = $$.$el.main, shape = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(that), isSelected = shape.classed(config_classes.SELECTED), toggle = $$.getToggle(that, d).bind($$); if (config.data_selection_enabled && config.data_selection_isselectable.bind($$.api)(d)) { if (!config.data_selection_multiple) { var selector = "." + config_classes.shapes; config.data_selection_grouped && (selector += $$.getTargetSelectorSuffix(d.id)), main.selectAll(selector).selectAll("." + config_classes.shape).each(function (d, i) { var shape = (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(this); shape.classed(config_classes.SELECTED) && (toggledShape = shape, toggle(!1, shape.classed(config_classes.SELECTED, !1), d, i)); }); } toggledShape && toggledShape.node() === shape.node() || (shape.classed(config_classes.SELECTED, !isSelected), toggle(!isSelected, shape, d, i)); } } })); ;// CONCATENATED MODULE: ./src/ChartInternal/interactions/subchart.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var interactions_subchart = ({ /** * Initialize the brush. * @private */ initBrush: function initBrush() { var $$ = this, config = $$.config, scale = $$.scale, subchart = $$.$el.subchart, isRotated = config.axis_rotated; $$.brush = isRotated ? (0,external_commonjs_d3_brush_commonjs2_d3_brush_amd_d3_brush_root_d3_.brushY)() : (0,external_commonjs_d3_brush_commonjs2_d3_brush_amd_d3_brush_root_d3_.brushX)(); // set "brush" event var lastDomain, timeout, brushHandler = function () { $$.redrawForBrush(); }, getBrushSize = function () { var brush = $$.$el.svg.select("." + config_classes.brush + " .overlay"), brushSize = { width: 0, height: 0 }; return brush.size() && (brushSize.width = +brush.attr("width"), brushSize.height = +brush.attr("height")), brushSize[isRotated ? "width" : "height"]; }; // set the brush extent $$.brush.on("start", function () { $$.state.inputType === "touch" && $$.hideTooltip(), brushHandler(); }).on("brush", brushHandler).on("end", function () { lastDomain = scale.x.orgDomain(); }), $$.brush.updateResize = function () { var _this = this; timeout && clearTimeout(timeout), timeout = setTimeout(function () { var selection = _this.getSelection(); lastDomain && (0,external_commonjs_d3_brush_commonjs2_d3_brush_amd_d3_brush_root_d3_.brushSelection)(selection.node()) && _this.move(selection, lastDomain.map(scale.subX.orgScale())); }, 0); }, $$.brush.update = function () { var extent = this.extent()(); return extent[1].filter(function (v) { return isNaN(v); }).length === 0 && subchart.main && subchart.main.select("." + config_classes.brush).call(this), this; }, $$.brush.scale = function (scale) { var h = config.subchart_size_height || getBrushSize(), extent = $$.getExtent(); // [[x0, y0], [x1, y1]], where [x0, y0] is the top-left corner and [x1, y1] is the bottom-right corner // when extent updates, brush selection also be re-applied // https://github.com/d3/d3/issues/2918 !extent && scale.range ? extent = [[0, 0], [scale.range()[1], h]] : isArray(extent) && (extent = extent.map(function (v, i) { return [v, i > 0 ? h : i]; })), isRotated && extent[1].reverse(), this.extent(extent), this.update(); }, $$.brush.getSelection = function () { return (// @ts-ignore subchart.main ? subchart.main.select("." + config_classes.brush) : (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)([]) ); }; }, /** * Initialize the subchart. * @private */ initSubchart: function initSubchart() { var $$ = this, config = $$.config, _$$$state = $$.state, clip = _$$$state.clip, hasAxis = _$$$state.hasAxis, _$$$$el = $$.$el, defs = _$$$$el.defs, svg = _$$$$el.svg, subchart = _$$$$el.subchart, axis = _$$$$el.axis; if (hasAxis) { var visibility = config.subchart_show ? "visible" : "hidden", clipId = clip.id + "-subchart", clipPath = $$.getClipPath(clipId); clip.idSubchart = clipId, $$.appendClip(defs, clipId), $$.initBrush(), subchart.main = svg.append("g").classed(config_classes.subchart, !0).attr("transform", $$.getTranslate("context")); var main = subchart.main; main.style("visibility", visibility), main.append("g").attr("clip-path", clipPath).attr("class", config_classes.chart), ["bar", "line", "bubble", "candlestick", "scatter"].forEach(function (v) { var type = capitalize(/^(bubble|scatter)$/.test(v) ? "circle" : v); if ($$.hasType(v) || $$.hasTypeOf(type)) { var chart = main.select("." + config_classes.chart), chartClassName = config_classes["chart" + type + "s"]; chart.select("." + chartClassName).empty() && chart.append("g").attr("class", chartClassName); } }), main.append("g").attr("clip-path", clipPath).attr("class", config_classes.brush).call($$.brush), axis.subX = main.append("g").attr("class", config_classes.axisX).attr("transform", $$.getTranslate("subX")).attr("clip-path", config.axis_rotated ? "" : clip.pathXAxis).style("visibility", config.subchart_axis_x_show ? visibility : "hidden"); } }, /** * Update sub chart * @param {object} targets $$.data.targets * @private */ updateTargetsForSubchart: function updateTargetsForSubchart(targets) { var $$ = this, config = $$.config, state = $$.state, main = $$.$el.subchart.main; config.subchart_show && (["bar", "line", "bubble", "candlestick", "scatter"].filter(function (v) { return $$.hasType(v) || $$.hasTypeOf(capitalize(v)); }).forEach(function (v) { var isPointType = /^(bubble|scatter)$/.test(v), name = capitalize(isPointType ? "circle" : v), chartClass = $$.getChartClass(name, !0), shapeClass = $$.getClass(isPointType ? "circles" : v + "s", !0), shapeChart = main.select("." + config_classes["chart" + (name + "s")]); if (isPointType) { var circle = shapeChart.selectAll("." + config_classes.circles).data(targets.filter($$["is" + capitalize(v) + "Type"].bind($$))).attr("class", shapeClass); circle.exit().remove(), circle.enter().append("g").attr("class", shapeClass); } else { var shapeUpdate = shapeChart.selectAll("." + config_classes["chart" + name]).attr("class", chartClass).data(targets.filter($$["is" + name + "Type"].bind($$))), shapeEnter = shapeUpdate.enter().append("g").style("opacity", "0").attr("class", chartClass).append("g").attr("class", shapeClass); // Area shapeUpdate.exit().remove(), v === "line" && $$.hasTypeOf("Area") && shapeEnter.append("g").attr("class", $$.getClass("areas", !0)); } }), main.selectAll("." + config_classes.brush + " rect").attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? state.width2 : state.height2)); }, /** * Redraw subchart. * @private * @param {boolean} withSubchart whether or not to show subchart * @param {number} duration duration * @param {object} shape Shape's info */ redrawSubchart: function redrawSubchart(withSubchart, duration, shape) { var $$ = this, config = $$.config, main = $$.$el.subchart.main, state = $$.state, withTransition = !!duration; // subchart if (main.style("visibility", config.subchart_show ? "visible" : "hidden"), config.subchart_show && (state.event && state.event.type === "zoom" && $$.brush.update(), withSubchart && (brushEmpty($$) || $$.brush.update(), Object.keys(shape.type).forEach(function (v) { var name = capitalize(v), drawFn = $$["generateDraw" + name](shape.indices[v], !0); $$["update" + name](duration, !0), $$["redraw" + name](drawFn, withTransition, !0); }), $$.hasType("bubble") || $$.hasType("scatter")))) // update subchart elements if needed { var cx = shape.pos.cx, cy = $$.updateCircleY(!0); $$.updateCircle(!0), $$.redrawCircle(cx, cy, withTransition, undefined, !0); } }, /** * Redraw the brush. * @private */ redrawForBrush: function redrawForBrush() { var $$ = this, _$$$config = $$.config, onBrush = _$$$config.subchart_onbrush, withY = _$$$config.zoom_rescale, scale = $$.scale; $$.redraw({ withTransition: !1, withY: withY, withSubchart: !1, withUpdateXDomain: !0, withDimension: !1 }), onBrush.bind($$.api)(scale.x.orgDomain()); }, /** * Transform context * @param {boolean} withTransition indicates transition is enabled * @param {object} transitions The return value of the generateTransitions method of Axis. * @private */ transformContext: function transformContext(withTransition, transitions) { var subXAxis, $$ = this, main = $$.$el.subchart.main; transitions && transitions.axisSubX ? subXAxis = transitions.axisSubX : (subXAxis = main.select("." + config_classes.axisX), withTransition && (subXAxis = subXAxis.transition())), main.attr("transform", $$.getTranslate("context")), subXAxis.attr("transform", $$.getTranslate("subX")); }, /** * Get extent value * @returns {Array} default extent * @private */ getExtent: function getExtent() { var $$ = this, config = $$.config, scale = $$.scale, extent = config.axis_x_extent; if (extent) if (isFunction(extent)) extent = extent.bind($$.api)($$.getXDomain($$.data.targets), scale.subX);else if ($$.axis.isTimeSeries() && extent.every(isNaN)) { var fn = parseDate.bind($$); extent = extent.map(function (v) { return scale.subX(fn(v)); }); } return extent; } }); ;// CONCATENATED MODULE: ./src/ChartInternal/interactions/zoom.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /* harmony default export */ var interactions_zoom = ({ /** * Initialize zoom. * @private */ initZoom: function initZoom() { var $$ = this; $$.scale.zoom = null, $$.generateZoom(), $$.initZoomBehaviour(); }, /** * Bind zoom event * @param {boolean} bind Weather bind or unbound * @private */ bindZoomEvent: function bindZoomEvent(bind) { bind === void 0 && (bind = !0); var $$ = this, config = $$.config, main = $$.$el.main, zoomEnabled = config.zoom_enabled, eventRects = main.select("." + config_classes.eventRects); zoomEnabled && bind ? !config.subchart_show && $$.bindZoomOnEventRect(eventRects, config.zoom_type) : bind === !1 && ($$.api.unzoom(), eventRects.on(".zoom", null).on(".drag", null)); }, /** * Generate zoom * @private */ generateZoom: function generateZoom() { var $$ = this, config = $$.config, org = $$.org, scale = $$.scale, zoom = (0,external_commonjs_d3_zoom_commonjs2_d3_zoom_amd_d3_zoom_root_d3_.zoom)().duration(0).on("start", $$.onZoomStart.bind($$)).on("zoom", $$.onZoom.bind($$)).on("end", $$.onZoomEnd.bind($$)); // get zoom extent // @ts-ignore // @ts-ignore /** * Update scale according zoom transform value * @param {object} transform transform object * @private */ // @ts-ignore zoom.orgScaleExtent = function () { var extent = config.zoom_extent || [1, 10]; return [extent[0], Math.max($$.getMaxDataCount() / extent[1], extent[1])]; }, zoom.updateScaleExtent = function () { var ratio = diffDomain($$.scale.x.orgDomain()) / diffDomain($$.getZoomDomain()), extent = this.orgScaleExtent(); return this.scaleExtent([extent[0] * ratio, extent[1] * ratio]), this; }, zoom.updateTransformScale = function (transform) { org.xScale && org.xScale.range(scale.x.range()); // rescale from the original scale var newScale = transform[config.axis_rotated ? "rescaleY" : "rescaleX"](org.xScale || scale.x), domain = $$.trimXDomain(newScale.domain()), rescale = config.zoom_rescale; newScale.domain(domain, org.xDomain), scale.zoom = $$.getCustomizedScale(newScale), $$.axis.x.scale(scale.zoom), rescale && (!org.xScale && (org.xScale = scale.x.copy()), scale.x.domain(domain)); }, $$.zoom = zoom; }, /** * 'start' event listener * @param {object} event Event object * @private */ onZoomStart: function onZoomStart(event) { var $$ = this, sourceEvent = event.sourceEvent; sourceEvent && ($$.zoom.startEvent = sourceEvent, $$.state.zooming = !0, callFn($$.config.zoom_onzoomstart, $$.api, event)); }, /** * 'zoom' event listener * @param {object} event Event object * @private */ onZoom: function onZoom(event) { var $$ = this, config = $$.config, scale = $$.scale, org = $$.org, sourceEvent = event.sourceEvent; if (config.zoom_enabled && event.sourceEvent && $$.filterTargetsToShow($$.data.targets).length !== 0 && (scale.zoom || !(sourceEvent.type.indexOf("touch") > -1) || sourceEvent.touches.length !== 1)) { var isMousemove = sourceEvent.type === "mousemove", isZoomOut = sourceEvent.wheelDelta < 0, transform = event.transform; !isMousemove && isZoomOut && scale.x.domain().every(function (v, i) { return v !== org.xDomain[i]; }) && scale.x.domain(org.xDomain), $$.zoom.updateTransformScale(transform), $$.axis.isCategorized() && scale.x.orgDomain()[0] === org.xDomain[0] && scale.x.domain([org.xDomain[0] - 1e-10, scale.x.orgDomain()[1]]), $$.redraw({ withTransition: !1, withY: config.zoom_rescale, withSubchart: !1, withEventRect: !1, withDimension: !1 }), $$.state.cancelClick = isMousemove, callFn(config.zoom_onzoom, $$.api, scale.zoom.domain()); } }, /** * 'end' event listener * @param {object} event Event object * @private */ onZoomEnd: function onZoomEnd(event) { var $$ = this, config = $$.config, scale = $$.scale, startEvent = $$.zoom.startEvent, e = event && event.sourceEvent; startEvent && startEvent.type.indexOf("touch") > -1 && (startEvent = startEvent.changedTouches[0], e = e.changedTouches[0]); // if click, do nothing. otherwise, click interaction will be canceled. !startEvent || e && startEvent.clientX === e.clientX && startEvent.clientY === e.clientY || ($$.redrawEventRect(), $$.updateZoom(), $$.state.zooming = !1, callFn(config.zoom_onzoomend, $$.api, scale[scale.zoom ? "zoom" : "subX"].domain())); }, /** * Get zoom domain * @returns {Array} zoom domain * @private */ getZoomDomain: function getZoomDomain() { var $$ = this, config = $$.config, org = $$.org, _org$xDomain = org.xDomain, min = _org$xDomain[0], max = _org$xDomain[1]; return isDefined(config.zoom_x_min) && (min = getMinMax("min", [min, config.zoom_x_min])), isDefined(config.zoom_x_max) && (max = getMinMax("max", [max, config.zoom_x_max])), [min, max]; }, /** * Update zoom * @param {boolean} force Force unzoom * @private */ updateZoom: function updateZoom(force) { var $$ = this, _$$$scale = $$.scale, subX = _$$$scale.subX, x = _$$$scale.x, zoom = _$$$scale.zoom; if (zoom) { var zoomDomain = zoom.domain(), xDomain = subX.domain(), delta = .015, isfullyShown = (zoomDomain[0] <= xDomain[0] || zoomDomain[0] - delta <= xDomain[0]) && (xDomain[1] <= zoomDomain[1] || xDomain[1] <= zoomDomain[1] - delta); (force || isfullyShown) && ($$.axis.x.scale(subX), x.domain(subX.orgDomain()), $$.scale.zoom = null); } }, /** * Attach zoom event on <rect> * @param {d3.selection} eventRects evemt <rect> element * @param {string} type zoom type * @private */ bindZoomOnEventRect: function bindZoomOnEventRect(eventRects, type) { var $$ = this, behaviour = type === "drag" ? $$.zoomBehaviour : $$.zoom; // Since Chrome 89, wheel zoom not works properly // Applying the workaround: https://github.com/d3/d3-zoom/issues/231#issuecomment-802305692 $$.$el.svg.on("wheel", function () {}), eventRects.call(behaviour).on("dblclick.zoom", null); }, /** * Initialize the drag behaviour used for zooming. * @private */ initZoomBehaviour: function initZoomBehaviour() { var zoomRect, $$ = this, config = $$.config, state = $$.state, isRotated = config.axis_rotated, start = 0, end = 0, prop = { axis: isRotated ? "y" : "x", attr: isRotated ? "height" : "width", index: isRotated ? 1 : 0 }; $$.zoomBehaviour = (0,external_commonjs_d3_drag_commonjs2_d3_drag_amd_d3_drag_root_d3_.drag)().clickDistance(4).on("start", function (event) { state.event = event, $$.setDragStatus(!0), $$.unselectRect(), zoomRect || (zoomRect = $$.$el.main.append("rect").attr("clip-path", state.clip.path).attr("class", config_classes.zoomBrush).attr("width", isRotated ? state.width : 0).attr("height", isRotated ? 0 : state.height)), start = getPointer(event, this)[prop.index], end = start, zoomRect.attr(prop.axis, start).attr(prop.attr, 0), $$.onZoomStart(event); }).on("drag", function (event) { end = getPointer(event, this)[prop.index], zoomRect.attr(prop.axis, Math.min(start, end)).attr(prop.attr, Math.abs(end - start)); }).on("end", function (event) { var _ref, scale = $$.scale.zoom || $$.scale.x; if (state.event = event, $$.setDragStatus(!1), zoomRect.attr(prop.axis, 0).attr(prop.attr, 0), start > end && (_ref = [end, start], start = _ref[0], end = _ref[1], _ref), start < 0 && (end += Math.abs(start), start = 0), start !== end) $$.api.zoom([start, end].map(function (v) { return scale.invert(v); })), $$.onZoomEnd(event);else if ($$.isMultipleX()) $$.clickHandlerForMultipleXS.bind(this)($$);else { var _getPointer = getPointer(event), x = _getPointer[0], y = _getPointer[1], target = browser_doc.elementFromPoint(x, y); $$.clickHandlerForSingleX.bind(target)((0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(target).datum(), $$); } }); }, setZoomResetButton: function setZoomResetButton() { var $$ = this, config = $$.config, resetButton = config.zoom_resetButton; resetButton && config.zoom_type === "drag" && ($$.zoom.resetBtn ? $$.zoom.resetBtn.style("display", null) : $$.zoom.resetBtn = $$.$el.chart.append("div").classed(config_classes.button, !0).append("span").on("click", function () { isFunction(resetButton.onclick) && resetButton.onclick.bind($$.api)(this), $$.api.unzoom(); }).classed(config_classes.buttonZoomReset, !0).text(resetButton.text || "Reset Zoom")); } }); ;// CONCATENATED MODULE: ./src/config/Options/data/selection.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * data.selection config options */ /* harmony default export */ var data_selection = ({ /** * Set data selection enabled<br><br> * If this option is set true, we can select the data points and get/set its state of selection by API (e.g. select, unselect, selected). * - **NOTE:** for ESM imports, needs to import 'selection' exports and instantiate it by calling `selection()`. * - `enabled: selection()` * @name dataβ€€selectionβ€€enabled * @memberof Options * @type {boolean} * @default false * @see [Demo](https://naver.github.io/billboard.js/demo/#Data.DataSelection) * @example * data: { * selection: { * enabled: true * } * } * @example * // importing ESM * import bb, {selection} from "billboard.js"; * * data: { * selection: { * enabled: selection(), * ... * } * } */ data_selection_enabled: !1, /** * Set grouped selection enabled.<br><br> * If this option set true, multiple data points that have same x value will be selected by one selection. * @name dataβ€€selectionβ€€grouped * @memberof Options * @type {boolean} * @default false * @example * data: { * selection: { * grouped: true * } * } */ data_selection_grouped: !1, /** * Set a callback for each data point to determine if it's selectable or not.<br><br> * The callback will receive d as an argument and it has some parameters like id, value, index. This callback should return boolean. * @name dataβ€€selectionβ€€isselectable * @memberof Options * @type {Function} * @default function() { return true; } * @example * data: { * selection: { * isselectable: function(d) { ... } * } * } */ data_selection_isselectable: function data_selection_isselectable() { return !0; }, /** * Set multiple data points selection enabled.<br><br> * If this option set true, multile data points can have the selected state at the same time. If false set, only one data point can have the selected state and the others will be unselected when the new data point is selected. * @name dataβ€€selectionβ€€multiple * @memberof Options * @type {boolean} * @default true * @example * data: { * selection: { * multiple: false * } * } */ data_selection_multiple: !0, /** * Enable to select data points by dragging. * If this option set true, data points can be selected by dragging. * - **NOTE:** If this option set true, scrolling on the chart will be disabled because dragging event will handle the event. * @name dataβ€€selectionβ€€draggable * @memberof Options * @type {boolean} * @default false * @example * data: { * selection: { * draggable: true * } * } */ data_selection_draggable: !1, /** * Set a callback for on data selection. * @name dataβ€€onselected * @memberof Options * @type {Function} * @default function() {} * @example * data: { * onselected: function(d, element) { * // d - ex) {x: 4, value: 150, id: "data1", index: 4, name: "data1"} * // element - <circle> * ... * } * } */ data_onselected: function data_onselected() {}, /** * Set a callback for on data un-selection. * @name dataβ€€onunselected * @memberof Options * @type {Function} * @default function() {} * @example * data: { * onunselected: function(d, element) { * // d - ex) {x: 4, value: 150, id: "data1", index: 4, name: "data1"} * // element - <circle> * ... * } * } */ data_onunselected: function data_onunselected() {} }); ;// CONCATENATED MODULE: ./src/config/Options/interaction/subchart.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * x Axis config options */ /* harmony default export */ var interaction_subchart = ({ /** * Set subchart options. * - **NOTE:** Not supported for `bubble`, `scatter` and non-Axis based(pie, donut, gauge, radar) types. * @name subchart * @memberof Options * @type {object} * @property {object} subchart Subchart object * @property {boolean} [subchart.show=false] Show sub chart on the bottom of the chart. * - **NOTE:** for ESM imports, needs to import 'subchart' exports and instantiate it by calling `subchart()`. * - `show: subchart()` * @property {boolean} [subchart.axis.x.show=true] Show or hide x axis. * @property {boolean} [subchart.axis.x.tick.show=true] Show or hide x axis tick line. * @property {boolean} [subchart.axis.x.tick.text.show=true] Show or hide x axis tick text. * @property {number} [subchart.size.height] Change the height of the subchart. * @property {Function} [subchart.onbrush] Set callback for brush event.<br> * Specified function receives the current zoomed x domain. * @see [Demo](https://naver.github.io/billboard.js/demo/#Interaction.SubChart) * @example * subchart: { * show: true, * size: { * height: 20 * }, * axis: { * x: { * show: true, * tick: { * show: true, * text: { * show: false * } * } * } * }, * onbrush: function(domain) { ... } * } * @example * // importing ESM * import bb, {subchart} from "billboard.js"; * * subchart: { * show: subchart(), * ... * } */ subchart_show: !1, subchart_size_height: 60, subchart_axis_x_show: !0, subchart_axis_x_tick_show: !0, subchart_axis_x_tick_text_show: !0, subchart_onbrush: function subchart_onbrush() {} }); ;// CONCATENATED MODULE: ./src/config/Options/interaction/zoom.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * zoom config options */ /* harmony default export */ var interaction_zoom = ({ /** * Set zoom options * @name zoom * @memberof Options * @type {object} * @property {object} zoom Zoom object * @property {boolean} [zoom.enabled=false] Enable zooming. * - **NOTE:** for ESM imports, needs to import 'zoom' exports and instantiate it by calling `zoom()`. * - `enabled: zoom()` * @property {string} [zoom.type='wheel'] Set zoom interaction type. * - **Available types:** * - wheel * - drag * @property {boolean} [zoom.rescale=false] Enable to rescale after zooming.<br> * If true set, y domain will be updated according to the zoomed region. * @property {Array} [zoom.extent=[1, 10]] Change zoom extent. * @property {number|Date} [zoom.x.min] Set x Axis minimum zoom range * @property {number|Date} [zoom.x.max] Set x Axis maximum zoom range * @property {Function} [zoom.onzoomstart=undefined] Set callback that is called when zooming starts.<br> * Specified function receives the zoom event. * @property {Function} [zoom.onzoom=undefined] Set callback that is called when the chart is zooming.<br> * Specified function receives the zoomed domain. * @property {Function} [zoom.onzoomend=undefined] Set callback that is called when zooming ends.<br> * Specified function receives the zoomed domain. * @property {boolean|object} [zoom.resetButton=true] Set to display zoom reset button for 'drag' type zoom * @property {Function} [zoom.resetButton.onclick] Set callback when clicks the reset button. The callback will receive reset button element reference as argument. * @property {string} [zoom.resetButton.text='Reset Zoom'] Text value for zoom reset button. * @see [Demo:zoom](https://naver.github.io/billboard.js/demo/#Interaction.Zoom) * @see [Demo:drag zoom](https://naver.github.io/billboard.js/demo/#Interaction.DragZoom) * @example * zoom: { * enabled: true, * type: "drag", * rescale: true, * extent: [1, 100] // enable more zooming * x: { * min: -1, // set min range * max: 10 // set max range * }, * onzoomstart: function(event) { ... }, * onzoom: function(domain) { ... }, * onzoomend: function(domain) { ... }, * * // show reset button when is zoomed-in * resetButton: true, * * resetButton: { * // onclick callback when reset button is clicked * onclick: function(button) { * button; // Reset button element reference * ... * }, * * // customized text value for reset zoom button * text: "Unzoom" * } * } * @example * // importing ESM * import bb, {zoom} from "billboard.js"; * * zoom: { * enabled: zoom(), * ... * } */ zoom_enabled: !1, zoom_type: "wheel", zoom_extent: undefined, zoom_privileged: !1, zoom_rescale: !1, zoom_onzoom: undefined, zoom_onzoomstart: undefined, zoom_onzoomend: undefined, zoom_resetButton: !0, zoom_x_min: undefined, zoom_x_max: undefined }); ;// CONCATENATED MODULE: ./src/config/resolver/interaction.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // Chart // ChartInternal // Axis based options var _selectionModule = function selectionModule() { return extend(ChartInternal.prototype, internals_selection), extend(Chart.prototype, selection), Options.setOptions([data_selection]), (_selectionModule = function selectionModule() { return !0; })(); }, subchartModule = function () { return extend(ChartInternal.prototype, interactions_subchart), extend(Chart.prototype, subchart), Options.setOptions([interaction_subchart]), (subchartModule = function () { return !0; })(); }, zoomModule = function () { return extend(ChartInternal.prototype, interactions_zoom), extend(Chart.prototype, api_zoom), Options.setOptions([interaction_zoom]), (zoomModule = function () { return !0; })(); }; ;// CONCATENATED MODULE: ./src/core.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard project is licensed under the MIT license */ // eslint-disable-next-line no-use-before-define var _defaults = {}, bb = { /** * Version information * @property {string} version version * @example * bb.version; // "1.0.0" * @memberof bb */ version: "3.0.2", /** * Generate chart * - **NOTE:** Bear in mind for the possiblity of ***throwing an error***, during the generation when: * - Unused option value is given. * - ex) For `data.type="pie"` option, setting 'axis' option can cause unexpected generation error. * - Insufficient value is given for certain option used. * - ex) `data: { x: "x", columns: [["x"], ["data1", 30, 200, 100]] }` * @param {Options} config chart options * @memberof bb * @returns {Chart} * @see {@link Options} for different generation options * @see {@link Chart} for different methods API * @example * <!-- chart holder --> * <div id="LineChart"></div> * @example * // Generate chart with options * var chart = bb.generate({ * "bindto": "#LineChart" * "data": { * "columns": [ * ["data1", 30, 200, 100, 400, 150, 250], * ["data2", 50, 20, 10, 40, 15, 25] * ], * "type": "line" * } * }); * * // call some API * // ex) get the data of 'data1' * chart.data("data1"); * @example * // Generate chart by importing ESM * // Import types to be used only, where this will make smaller bundle size. * import bb, { * area, * areaLineRange, * areaSpline, * areaSplineRange, * areaStep, * bar, * bubble, * donut, * gauge, * line, * pie, * radar, * scatter, * spline, * step * } * * bb.generate({ * "bindto": "#LineChart" * "data": { * "columns": [ * ["data1", 30, 200, 100, 400, 150, 250], * ["data2", 50, 20, 10, 40, 15, 25] * ] * }, * type: line(), * * // or * types: { * data1: bar(), * data2: step() * } * }); */ generate: function generate(config) { var options = mergeObj({}, _defaults, config), inst = new Chart(options); return inst.internal.charts = this.instance, this.instance.push(inst), inst; }, /** * Set or get global default options. * - **NOTE:** * - The options values settings are valid within page context only. * - If is called multiple times, will override the last value. * @param {Options} options chart options * @memberof bb * @returns {Options} * @see {@link Options} * @example * // Set same option value as for `.generate()` * bb.defaults({ * data: { * type: "bar" * } * }); * * bb.defaults(); // {data:{type: "bar"}} * * // data.type defaults to 'bar' * var chart = bb.generate({ ... }); */ defaults: function defaults(options) { return isObject(options) && (_defaults = options), _defaults; }, /** * An array containing instance created * @property {Array} instance instance array * @example * // generate charts * var chart1 = bb.generate(...); * var chart2 = bb.generate(...); * * bb.instance; // [ chart1, chart2, ... ] * @memberof bb */ instance: [], /** * Namespace for plugins * @property {object} plugin plugin namespace * @example * // Stanford diagram plugin * bb.plugin.stanford; * @memberof bb */ plugin: {} }; /** * @namespace bb * @version 3.0.2 */ ;// CONCATENATED MODULE: ./src/index.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard project is licensed under the MIT license */ // extends shape modules Object.keys(resolver_shape_namespaceObject).forEach(function (v) { return resolver_shape_namespaceObject[v](); }), Object.keys(resolver_interaction_namespaceObject).forEach(function (v) { return resolver_interaction_namespaceObject[v](); }); }(); /******/ return __webpack_exports__; /******/ })() ; });
{ "content_hash": "dd9bb6273f9e413efb280348961b92cc", "timestamp": "", "source": "github", "line_count": 17740, "max_line_length": 840, "avg_line_length": 37.12271702367531, "alnum_prop": 0.5984068197589578, "repo_name": "cdnjs/cdnjs", "id": "be134b628bb4965f9e34cb56e7b593396439eb3e", "size": "659333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/billboard.js/3.0.3/billboard.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\views\Tests\Handler\FieldDropButtonTest. */ namespace Drupal\views\Tests\Handler; /** * Tests the dropbutton field handler. * * @group views * @see \Drupal\system\Plugin\views\field\Dropbutton */ class FieldDropButtonTest extends HandlerTestBase { /** * Views used by this test. * * @var array */ public static $testViews = array('test_dropbutton'); /** * Modules to enable. * * @var array */ public static $modules = array('node'); /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $admin_user = $this->drupalCreateUser(['access content overview', 'administer nodes', 'bypass node access']); $this->drupalLogin($admin_user); } /** * Tests dropbutton field. */ public function testDropbutton() { // Create some test nodes. $nodes = array(); for ($i = 0; $i < 5; $i++) { $nodes[] = $this->drupalCreateNode(); } $this->drupalGet('test-dropbutton'); foreach ($nodes as $node) { $result = $this->xpath('//ul[contains(@class, dropbutton)]/li/a[contains(@href, :path) and text()=:title]', array(':path' => '/node/' . $node->id(), ':title' => $node->label())); $this->assertEqual(count($result), 1, 'Just one node title link was found.'); $result = $this->xpath('//ul[contains(@class, dropbutton)]/li/a[contains(@href, :path) and text()=:title]', array(':path' => '/node/' . $node->id(), ':title' => t('Custom Text'))); $this->assertEqual(count($result), 1, 'Just one custom link was found.'); } // Check if the dropbutton.js library is available. $this->drupalGet('admin/content'); $this->assertRaw('dropbutton.js'); // Check if the dropbutton.js library is available on a cached page to // ensure that bubbleable metadata is not lost in the views render workflow. $this->drupalGet('admin/content'); $this->assertRaw('dropbutton.js'); } }
{ "content_hash": "5b6ac3379429c45eb8beb7d7afb2ab12", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 186, "avg_line_length": 28.434782608695652, "alnum_prop": 0.6167176350662589, "repo_name": "edwardchan/d8-drupalvm", "id": "44880328e832584b0ff4af2c36955838e8644e8d", "size": "1962", "binary": false, "copies": "67", "ref": "refs/heads/master", "path": "drupal/core/modules/views/src/Tests/Handler/FieldDropButtonTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "50616" }, { "name": "CSS", "bytes": "1250515" }, { "name": "HTML", "bytes": "646836" }, { "name": "JavaScript", "bytes": "1018469" }, { "name": "PHP", "bytes": "31387248" }, { "name": "Shell", "bytes": "675" }, { "name": "SourcePawn", "bytes": "31943" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>libguac: guacamole/stream-types.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">libguac &#160;<span id="projectnumber">0.9.9</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_6bb9fad85c98b48a11165f494b9f53ce.html">guacamole</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">stream-types.h File Reference</div> </div> </div><!--header--> <div class="contents"> <p>Type definitions related to Guacamole protocol streams. <a href="#details">More...</a></p> <p><a href="stream-types_8h_source.html">Go to the source code of this file.</a></p> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Type definitions related to Guacamole protocol streams. </p> </div></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> <!-- Google Analytics --> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-75289145-1', 'auto'); ga('send', 'pageview'); </script> <!-- End Google Analytics --> </body> </html>
{ "content_hash": "03a7ca6c705f1bfee5f0a36dac5523de", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 154, "avg_line_length": 39.208333333333336, "alnum_prop": 0.646971307120085, "repo_name": "mike-jumper/incubator-guacamole-website", "id": "83127c16b888a2d2a6e6508863b62ed3a59be4c3", "size": "4705", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/0.9.9/libguac/stream-types_8h.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12886" }, { "name": "HTML", "bytes": "37702" }, { "name": "JavaScript", "bytes": "439018" }, { "name": "Perl", "bytes": "2217" }, { "name": "Ruby", "bytes": "660" }, { "name": "Shell", "bytes": "4849" } ], "symlink_target": "" }
angular.module('cog').factory('SectionPresenter', ['FieldPresenter', '$q', function(FieldPresenter, $q) { function SectionPresenter(Site, section) { this.section = section; this.label = section.label; this.fields = section.fields; if (!section.sections) { section.sections = []; } // add sections this.site = new Site(); this.site.sections = section.sections; this.section.items = function() { this.fields.forEach(function(field) { field._type = 'field'; }); this.sections.forEach(function(section) { section._type = 'section'; }); var items = this.fields.concat(this.sections); return items; }; } SectionPresenter.prototype = { findOrCreateField: function(element, label, type) { if (!type) { throw 'must supply a type'; } var field = this.findField(label, type) || this.createField(label, type); field.element = element; return new FieldPresenter(field); }, findField: function(label, type) { var match; this.fields.forEach(function(field) { if (field.label === label) { match = field; match.type = type; } }); return match; }, createField: function(fieldLabel, type) { var field = { label: fieldLabel, value: '', type: type }; this._addField(field); return field; }, _addField: function(field) { this.fields.push(field); }, setElement: function(element) { this.section.element = element; }, fetchSection: function(sectionElement, sectionLabel) { // all fetchSection needs to be async var defer = $q.defer(); var section = this.site.findOrCreateSection(sectionLabel); section.setElement(sectionElement); defer.resolve(section); return defer.promise; } }; return SectionPresenter; }]);
{ "content_hash": "cfe4dd5293574af5449463d97710922b", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 105, "avg_line_length": 22.195402298850574, "alnum_prop": 0.597099948213361, "repo_name": "camwest/cog", "id": "7cbd7f71b06547aa9bf2d108344337eb5243de98", "size": "1931", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/src/services/sectionPresenter.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1431" }, { "name": "JavaScript", "bytes": "29274" } ], "symlink_target": "" }
package com.asakusafw.utils.java.internal.parser.javadoc.ir; import java.io.Serializable; /** * A skeletal implementation of {@link IrDocElement}. */ public abstract class AbstractIrDocElement implements IrDocElement, Serializable { private static final long serialVersionUID = 6223179902104926164L; private IrLocation location; @Override public IrLocation getLocation() { return this.location; } @Override public void setLocation(IrLocation location) { this.location = location; } }
{ "content_hash": "efcdd6c9ed50078a5e1a091184891be7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 82, "avg_line_length": 22.541666666666668, "alnum_prop": 0.7245841035120147, "repo_name": "ashigeru/asakusafw", "id": "d050f6a57e712601c13ed8c5db07953cab6f7c91", "size": "1153", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "utils-project/javadoc-parser/src/main/java/com/asakusafw/utils/java/internal/parser/javadoc/ir/AbstractIrDocElement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "31" }, { "name": "CSS", "bytes": "650" }, { "name": "Groovy", "bytes": "277156" }, { "name": "Java", "bytes": "12812573" }, { "name": "Lex", "bytes": "12506" }, { "name": "Shell", "bytes": "10149" }, { "name": "TSQL", "bytes": "139" } ], "symlink_target": "" }
package org.spontaneous.server.client; import org.spontaneous.server.client.service.rest.ClientProperties; import org.spontaneous.server.client.service.rest.RegisterController; import org.spontaneous.server.client.service.rest.RevokeTokenController; import org.spontaneous.server.client.service.rest.TrackManagementController; import org.spontaneous.server.client.service.rest.UserManagementController; import org.spontaneous.server.ping.api.TestServerPingController; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * The type Client config. */ @Configuration //@ComponentScan(basePackages = { "com.dhl.parcelshop.backend.client" }, useDefaultFilters = false, includeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,// //value = { TenantSpecificClientConfig.class }) }) public class ClientConfig { /** * Defines the androidClientProperties bean. * * @return the androidClientProperties bean */ @Bean @ConfigurationProperties(prefix = "spontaneous.client.android") public ClientProperties androidClientProperties() { return new ClientProperties(); } /** * Defines the revokeTokenController bean. * * @return the revokeTokenController bean */ @Bean public RevokeTokenController revokeTokenController() { return new RevokeTokenController(); } /** * Defines the userManagementController bean. * * @return the userManagementController bean */ @Bean public UserManagementController userManagementController() { return new UserManagementController(); } /** * Defines the trackManagementController bean. * * @return the trackManagementController bean */ @Bean public TrackManagementController trackManagementController() { return new TrackManagementController(); } /** * Defines the registerController bean. * * @return the registerController bean */ @Bean public RegisterController registerController() { return new RegisterController(); } /** * Defines the registerController bean. * * @return the registerController bean */ @Bean public TestServerPingController pingController() { return new TestServerPingController(); } }
{ "content_hash": "bfa4d16e3bada7a8f14e88cbef9e7f8b", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 177, "avg_line_length": 28.463414634146343, "alnum_prop": 0.7592116538131962, "repo_name": "fdondorf/SpontaneousRunningServer", "id": "c94425effefff9ad54acae506b8598120b02418d", "size": "2334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/spontaneous/server/client/ClientConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "133448" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Mon Nov 26 17:21:57 MSK 2012 --> <TITLE> Uses of Class org.apache.poi.poifs.storage.DataInputBlock (POI API Documentation) </TITLE> <META NAME="date" CONTENT="2012-11-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.poifs.storage.DataInputBlock (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/poifs/storage/\class-useDataInputBlock.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DataInputBlock.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.poi.poifs.storage.DataInputBlock</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.poi.poifs.storage"><B>org.apache.poi.poifs.storage</B></A></TD> <TD>storage package contains low level binary structures for POIFS's implementation of the OLE 2 Compound Document Format.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.poi.poifs.storage"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A> in <A HREF="../../../../../../org/apache/poi/poifs/storage/package-summary.html">org.apache.poi.poifs.storage</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/poi/poifs/storage/package-summary.html">org.apache.poi.poifs.storage</A> that return <A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A></CODE></FONT></TD> <TD><CODE><B>DocumentBlock.</B><B><A HREF="../../../../../../org/apache/poi/poifs/storage/DocumentBlock.html#getDataInputBlock(org.apache.poi.poifs.storage.DocumentBlock[], int)">getDataInputBlock</A></B>(<A HREF="../../../../../../org/apache/poi/poifs/storage/DocumentBlock.html" title="class in org.apache.poi.poifs.storage">DocumentBlock</A>[]&nbsp;blocks, int&nbsp;offset)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A></CODE></FONT></TD> <TD><CODE><B>SmallDocumentBlock.</B><B><A HREF="../../../../../../org/apache/poi/poifs/storage/SmallDocumentBlock.html#getDataInputBlock(org.apache.poi.poifs.storage.SmallDocumentBlock[], int)">getDataInputBlock</A></B>(<A HREF="../../../../../../org/apache/poi/poifs/storage/SmallDocumentBlock.html" title="class in org.apache.poi.poifs.storage">SmallDocumentBlock</A>[]&nbsp;blocks, int&nbsp;offset)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/poi/poifs/storage/package-summary.html">org.apache.poi.poifs.storage</A> with parameters of type <A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B>DataInputBlock.</B><B><A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html#readIntLE(org.apache.poi.poifs.storage.DataInputBlock, int)">readIntLE</A></B>(<A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A>&nbsp;prevBlock, int&nbsp;prevBlockAvailable)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reads an <tt>int</tt> which spans the end of <tt>prevBlock</tt> and the start of this block.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;long</CODE></FONT></TD> <TD><CODE><B>DataInputBlock.</B><B><A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html#readLongLE(org.apache.poi.poifs.storage.DataInputBlock, int)">readLongLE</A></B>(<A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A>&nbsp;prevBlock, int&nbsp;prevBlockAvailable)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reads a <tt>long</tt> which spans the end of <tt>prevBlock</tt> and the start of this block.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B>DataInputBlock.</B><B><A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html#readUShortLE(org.apache.poi.poifs.storage.DataInputBlock)">readUShortLE</A></B>(<A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage">DataInputBlock</A>&nbsp;prevBlock)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reads a <tt>short</tt> which spans the end of <tt>prevBlock</tt> and the start of this block.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/poifs/storage/DataInputBlock.html" title="class in org.apache.poi.poifs.storage"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/poifs/storage/\class-useDataInputBlock.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DataInputBlock.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2012 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
{ "content_hash": "8c72a8cc10a1bd1e5592faf7c68413a5", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 384, "avg_line_length": 53.01754385964912, "alnum_prop": 0.628722700198544, "repo_name": "brenthand/Panda", "id": "e94c064a4fe3fa4d02bb8fef8c34666a97c8c3f7", "size": "12088", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "poi-3.9/docs/apidocs/org/apache/poi/poifs/storage/class-use/DataInputBlock.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16091" }, { "name": "Java", "bytes": "17953" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- * Copyright 2014 Oleksiy Voronin <ovoronin@gmail.com> * * 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. --> <rules> <strip-class>java.util.Date</strip-class> <strip-class>java.lang.CharSequence</strip-class> <skip-class>java.sql.Date</skip-class> <skip-class>java.lang.Compiler</skip-class> <methods> <method> <returntype>java.lang.String</returntype> <methodname>get.*</methodname> <body>return "get-string";</body> </method> <method> <returntype>java.lang.String</returntype> <methodname>getInt</methodname> <body>return "get-int";</body> </method> </methods> </rules>
{ "content_hash": "786967c1d8784445ac2f399155d36e72", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 78, "avg_line_length": 35.333333333333336, "alnum_prop": 0.639937106918239, "repo_name": "uaraven/stubborn", "id": "b196253fe20aafae69bb2ba7702c39fe4e259c24", "size": "1272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources/strip-class-getter.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "90062" }, { "name": "Shell", "bytes": "138" } ], "symlink_target": "" }
#include "webrtc/modules/rtp_rtcp/source/receive_statistics_impl.h" #include <math.h> #include <cstdlib> #include "webrtc/modules/remote_bitrate_estimator/test/bwe_test_logging.h" #include "webrtc/modules/rtp_rtcp/source/rtp_rtcp_config.h" #include "webrtc/modules/rtp_rtcp/source/time_util.h" #include "webrtc/system_wrappers/include/clock.h" namespace webrtc { const int64_t kStatisticsTimeoutMs = 8000; const int64_t kStatisticsProcessIntervalMs = 1000; StreamStatistician::~StreamStatistician() {} StreamStatisticianImpl::StreamStatisticianImpl( Clock* clock, RtcpStatisticsCallback* rtcp_callback, StreamDataCountersCallback* rtp_callback) : clock_(clock), incoming_bitrate_(kStatisticsProcessIntervalMs, RateStatistics::kBpsScale), ssrc_(0), max_reordering_threshold_(kDefaultMaxReorderingThreshold), jitter_q4_(0), cumulative_loss_(0), jitter_q4_transmission_time_offset_(0), last_receive_time_ms_(0), last_received_timestamp_(0), last_received_transmission_time_offset_(0), received_seq_first_(0), received_seq_max_(0), received_seq_wraps_(0), received_packet_overhead_(12), last_report_inorder_packets_(0), last_report_old_packets_(0), last_report_seq_max_(0), rtcp_callback_(rtcp_callback), rtp_callback_(rtp_callback) {} void StreamStatisticianImpl::IncomingPacket(const RTPHeader& header, size_t packet_length, bool retransmitted) { UpdateCounters(header, packet_length, retransmitted); NotifyRtpCallback(); } void StreamStatisticianImpl::UpdateCounters(const RTPHeader& header, size_t packet_length, bool retransmitted) { rtc::CritScope cs(&stream_lock_); bool in_order = InOrderPacketInternal(header.sequenceNumber); ssrc_ = header.ssrc; incoming_bitrate_.Update(packet_length, clock_->TimeInMilliseconds()); receive_counters_.transmitted.AddPacket(packet_length, header); if (!in_order && retransmitted) { receive_counters_.retransmitted.AddPacket(packet_length, header); } if (receive_counters_.transmitted.packets == 1) { received_seq_first_ = header.sequenceNumber; receive_counters_.first_packet_time_ms = clock_->TimeInMilliseconds(); } // Count only the new packets received. That is, if packets 1, 2, 3, 5, 4, 6 // are received, 4 will be ignored. if (in_order) { // Current time in samples. NtpTime receive_time = clock_->CurrentNtpTime(); // Wrong if we use RetransmitOfOldPacket. if (receive_counters_.transmitted.packets > 1 && received_seq_max_ > header.sequenceNumber) { // Wrap around detected. received_seq_wraps_++; } // New max. received_seq_max_ = header.sequenceNumber; // If new time stamp and more than one in-order packet received, calculate // new jitter statistics. if (header.timestamp != last_received_timestamp_ && (receive_counters_.transmitted.packets - receive_counters_.retransmitted.packets) > 1) { UpdateJitter(header, receive_time); } last_received_timestamp_ = header.timestamp; last_receive_time_ntp_ = receive_time; last_receive_time_ms_ = clock_->TimeInMilliseconds(); } size_t packet_oh = header.headerLength + header.paddingLength; // Our measured overhead. Filter from RFC 5104 4.2.1.2: // avg_OH (new) = 15/16*avg_OH (old) + 1/16*pckt_OH, received_packet_overhead_ = (15 * received_packet_overhead_ + packet_oh) >> 4; } void StreamStatisticianImpl::UpdateJitter(const RTPHeader& header, NtpTime receive_time) { uint32_t receive_time_rtp = NtpToRtp(receive_time, header.payload_type_frequency); uint32_t last_receive_time_rtp = NtpToRtp(last_receive_time_ntp_, header.payload_type_frequency); int32_t time_diff_samples = (receive_time_rtp - last_receive_time_rtp) - (header.timestamp - last_received_timestamp_); time_diff_samples = std::abs(time_diff_samples); // lib_jingle sometimes deliver crazy jumps in TS for the same stream. // If this happens, don't update jitter value. Use 5 secs video frequency // as the threshold. if (time_diff_samples < 450000) { // Note we calculate in Q4 to avoid using float. int32_t jitter_diff_q4 = (time_diff_samples << 4) - jitter_q4_; jitter_q4_ += ((jitter_diff_q4 + 8) >> 4); } // Extended jitter report, RFC 5450. // Actual network jitter, excluding the source-introduced jitter. int32_t time_diff_samples_ext = (receive_time_rtp - last_receive_time_rtp) - ((header.timestamp + header.extension.transmissionTimeOffset) - (last_received_timestamp_ + last_received_transmission_time_offset_)); time_diff_samples_ext = std::abs(time_diff_samples_ext); if (time_diff_samples_ext < 450000) { int32_t jitter_diffQ4TransmissionTimeOffset = (time_diff_samples_ext << 4) - jitter_q4_transmission_time_offset_; jitter_q4_transmission_time_offset_ += ((jitter_diffQ4TransmissionTimeOffset + 8) >> 4); } } void StreamStatisticianImpl::NotifyRtpCallback() { StreamDataCounters data; uint32_t ssrc; { rtc::CritScope cs(&stream_lock_); data = receive_counters_; ssrc = ssrc_; } rtp_callback_->DataCountersUpdated(data, ssrc); } void StreamStatisticianImpl::NotifyRtcpCallback() { RtcpStatistics data; uint32_t ssrc; { rtc::CritScope cs(&stream_lock_); data = last_reported_statistics_; ssrc = ssrc_; } rtcp_callback_->StatisticsUpdated(data, ssrc); } void StreamStatisticianImpl::FecPacketReceived(const RTPHeader& header, size_t packet_length) { { rtc::CritScope cs(&stream_lock_); receive_counters_.fec.AddPacket(packet_length, header); } NotifyRtpCallback(); } void StreamStatisticianImpl::SetMaxReorderingThreshold( int max_reordering_threshold) { rtc::CritScope cs(&stream_lock_); max_reordering_threshold_ = max_reordering_threshold; } bool StreamStatisticianImpl::GetStatistics(RtcpStatistics* statistics, bool reset) { { rtc::CritScope cs(&stream_lock_); if (received_seq_first_ == 0 && receive_counters_.transmitted.payload_bytes == 0) { // We have not received anything. return false; } if (!reset) { if (last_report_inorder_packets_ == 0) { // No report. return false; } // Just get last report. *statistics = last_reported_statistics_; return true; } *statistics = CalculateRtcpStatistics(); } NotifyRtcpCallback(); return true; } RtcpStatistics StreamStatisticianImpl::CalculateRtcpStatistics() { RtcpStatistics stats; if (last_report_inorder_packets_ == 0) { // First time we send a report. last_report_seq_max_ = received_seq_first_ - 1; } // Calculate fraction lost. uint16_t exp_since_last = (received_seq_max_ - last_report_seq_max_); if (last_report_seq_max_ > received_seq_max_) { // Can we assume that the seq_num can't go decrease over a full RTCP period? exp_since_last = 0; } // Number of received RTP packets since last report, counts all packets but // not re-transmissions. uint32_t rec_since_last = (receive_counters_.transmitted.packets - receive_counters_.retransmitted.packets) - last_report_inorder_packets_; // With NACK we don't know the expected retransmissions during the last // second. We know how many "old" packets we have received. We just count // the number of old received to estimate the loss, but it still does not // guarantee an exact number since we run this based on time triggered by // sending of an RTP packet. This should have a minimum effect. // With NACK we don't count old packets as received since they are // re-transmitted. We use RTT to decide if a packet is re-ordered or // re-transmitted. uint32_t retransmitted_packets = receive_counters_.retransmitted.packets - last_report_old_packets_; rec_since_last += retransmitted_packets; int32_t missing = 0; if (exp_since_last > rec_since_last) { missing = (exp_since_last - rec_since_last); } uint8_t local_fraction_lost = 0; if (exp_since_last) { // Scale 0 to 255, where 255 is 100% loss. local_fraction_lost = static_cast<uint8_t>(255 * missing / exp_since_last); } stats.fraction_lost = local_fraction_lost; // We need a counter for cumulative loss too. // TODO(danilchap): Ensure cumulative loss is below maximum value of 2^24. cumulative_loss_ += missing; stats.cumulative_lost = cumulative_loss_; stats.extended_max_sequence_number = (received_seq_wraps_ << 16) + received_seq_max_; // Note: internal jitter value is in Q4 and needs to be scaled by 1/16. stats.jitter = jitter_q4_ >> 4; // Store this report. last_reported_statistics_ = stats; // Only for report blocks in RTCP SR and RR. last_report_inorder_packets_ = receive_counters_.transmitted.packets - receive_counters_.retransmitted.packets; last_report_old_packets_ = receive_counters_.retransmitted.packets; last_report_seq_max_ = received_seq_max_; BWE_TEST_LOGGING_PLOT_WITH_SSRC(1, "cumulative_loss_pkts", clock_->TimeInMilliseconds(), cumulative_loss_, ssrc_); BWE_TEST_LOGGING_PLOT_WITH_SSRC( 1, "received_seq_max_pkts", clock_->TimeInMilliseconds(), (received_seq_max_ - received_seq_first_), ssrc_); return stats; } void StreamStatisticianImpl::GetDataCounters( size_t* bytes_received, uint32_t* packets_received) const { rtc::CritScope cs(&stream_lock_); if (bytes_received) { *bytes_received = receive_counters_.transmitted.payload_bytes + receive_counters_.transmitted.header_bytes + receive_counters_.transmitted.padding_bytes; } if (packets_received) { *packets_received = receive_counters_.transmitted.packets; } } void StreamStatisticianImpl::GetReceiveStreamDataCounters( StreamDataCounters* data_counters) const { rtc::CritScope cs(&stream_lock_); *data_counters = receive_counters_; } uint32_t StreamStatisticianImpl::BitrateReceived() const { rtc::CritScope cs(&stream_lock_); return incoming_bitrate_.Rate(clock_->TimeInMilliseconds()).value_or(0); } void StreamStatisticianImpl::LastReceiveTimeNtp(uint32_t* secs, uint32_t* frac) const { rtc::CritScope cs(&stream_lock_); *secs = last_receive_time_ntp_.seconds(); *frac = last_receive_time_ntp_.fractions(); } bool StreamStatisticianImpl::IsRetransmitOfOldPacket( const RTPHeader& header, int64_t min_rtt) const { rtc::CritScope cs(&stream_lock_); if (InOrderPacketInternal(header.sequenceNumber)) { return false; } uint32_t frequency_khz = header.payload_type_frequency / 1000; assert(frequency_khz > 0); int64_t time_diff_ms = clock_->TimeInMilliseconds() - last_receive_time_ms_; // Diff in time stamp since last received in order. uint32_t timestamp_diff = header.timestamp - last_received_timestamp_; uint32_t rtp_time_stamp_diff_ms = timestamp_diff / frequency_khz; int64_t max_delay_ms = 0; if (min_rtt == 0) { // Jitter standard deviation in samples. float jitter_std = sqrt(static_cast<float>(jitter_q4_ >> 4)); // 2 times the standard deviation => 95% confidence. // And transform to milliseconds by dividing by the frequency in kHz. max_delay_ms = static_cast<int64_t>((2 * jitter_std) / frequency_khz); // Min max_delay_ms is 1. if (max_delay_ms == 0) { max_delay_ms = 1; } } else { max_delay_ms = (min_rtt / 3) + 1; } return time_diff_ms > rtp_time_stamp_diff_ms + max_delay_ms; } bool StreamStatisticianImpl::IsPacketInOrder(uint16_t sequence_number) const { rtc::CritScope cs(&stream_lock_); return InOrderPacketInternal(sequence_number); } bool StreamStatisticianImpl::InOrderPacketInternal( uint16_t sequence_number) const { // First packet is always in order. if (last_receive_time_ms_ == 0) return true; if (IsNewerSequenceNumber(sequence_number, received_seq_max_)) { return true; } else { // If we have a restart of the remote side this packet is still in order. return !IsNewerSequenceNumber(sequence_number, received_seq_max_ - max_reordering_threshold_); } } ReceiveStatistics* ReceiveStatistics::Create(Clock* clock) { return new ReceiveStatisticsImpl(clock); } ReceiveStatisticsImpl::ReceiveStatisticsImpl(Clock* clock) : clock_(clock), rtcp_stats_callback_(NULL), rtp_stats_callback_(NULL) {} ReceiveStatisticsImpl::~ReceiveStatisticsImpl() { while (!statisticians_.empty()) { delete statisticians_.begin()->second; statisticians_.erase(statisticians_.begin()); } } void ReceiveStatisticsImpl::IncomingPacket(const RTPHeader& header, size_t packet_length, bool retransmitted) { StreamStatisticianImpl* impl; { rtc::CritScope cs(&receive_statistics_lock_); StatisticianImplMap::iterator it = statisticians_.find(header.ssrc); if (it != statisticians_.end()) { impl = it->second; } else { impl = new StreamStatisticianImpl(clock_, this, this); statisticians_[header.ssrc] = impl; } } // StreamStatisticianImpl instance is created once and only destroyed when // this whole ReceiveStatisticsImpl is destroyed. StreamStatisticianImpl has // it's own locking so don't hold receive_statistics_lock_ (potential // deadlock). impl->IncomingPacket(header, packet_length, retransmitted); } void ReceiveStatisticsImpl::FecPacketReceived(const RTPHeader& header, size_t packet_length) { rtc::CritScope cs(&receive_statistics_lock_); StatisticianImplMap::iterator it = statisticians_.find(header.ssrc); // Ignore FEC if it is the first packet. if (it != statisticians_.end()) { it->second->FecPacketReceived(header, packet_length); } } StatisticianMap ReceiveStatisticsImpl::GetActiveStatisticians() const { rtc::CritScope cs(&receive_statistics_lock_); StatisticianMap active_statisticians; for (StatisticianImplMap::const_iterator it = statisticians_.begin(); it != statisticians_.end(); ++it) { uint32_t secs; uint32_t frac; it->second->LastReceiveTimeNtp(&secs, &frac); if (clock_->CurrentNtpInMilliseconds() - Clock::NtpToMs(secs, frac) < kStatisticsTimeoutMs) { active_statisticians[it->first] = it->second; } } return active_statisticians; } StreamStatistician* ReceiveStatisticsImpl::GetStatistician( uint32_t ssrc) const { rtc::CritScope cs(&receive_statistics_lock_); StatisticianImplMap::const_iterator it = statisticians_.find(ssrc); if (it == statisticians_.end()) return NULL; return it->second; } void ReceiveStatisticsImpl::SetMaxReorderingThreshold( int max_reordering_threshold) { rtc::CritScope cs(&receive_statistics_lock_); for (StatisticianImplMap::iterator it = statisticians_.begin(); it != statisticians_.end(); ++it) { it->second->SetMaxReorderingThreshold(max_reordering_threshold); } } void ReceiveStatisticsImpl::RegisterRtcpStatisticsCallback( RtcpStatisticsCallback* callback) { rtc::CritScope cs(&receive_statistics_lock_); if (callback != NULL) assert(rtcp_stats_callback_ == NULL); rtcp_stats_callback_ = callback; } void ReceiveStatisticsImpl::StatisticsUpdated(const RtcpStatistics& statistics, uint32_t ssrc) { rtc::CritScope cs(&receive_statistics_lock_); if (rtcp_stats_callback_) rtcp_stats_callback_->StatisticsUpdated(statistics, ssrc); } void ReceiveStatisticsImpl::CNameChanged(const char* cname, uint32_t ssrc) { rtc::CritScope cs(&receive_statistics_lock_); if (rtcp_stats_callback_) rtcp_stats_callback_->CNameChanged(cname, ssrc); } void ReceiveStatisticsImpl::RegisterRtpStatisticsCallback( StreamDataCountersCallback* callback) { rtc::CritScope cs(&receive_statistics_lock_); if (callback != NULL) assert(rtp_stats_callback_ == NULL); rtp_stats_callback_ = callback; } void ReceiveStatisticsImpl::DataCountersUpdated(const StreamDataCounters& stats, uint32_t ssrc) { rtc::CritScope cs(&receive_statistics_lock_); if (rtp_stats_callback_) { rtp_stats_callback_->DataCountersUpdated(stats, ssrc); } } void NullReceiveStatistics::IncomingPacket(const RTPHeader& rtp_header, size_t packet_length, bool retransmitted) {} void NullReceiveStatistics::FecPacketReceived(const RTPHeader& header, size_t packet_length) {} StatisticianMap NullReceiveStatistics::GetActiveStatisticians() const { return StatisticianMap(); } StreamStatistician* NullReceiveStatistics::GetStatistician( uint32_t ssrc) const { return NULL; } void NullReceiveStatistics::SetMaxReorderingThreshold( int max_reordering_threshold) {} void NullReceiveStatistics::RegisterRtcpStatisticsCallback( RtcpStatisticsCallback* callback) {} void NullReceiveStatistics::RegisterRtpStatisticsCallback( StreamDataCountersCallback* callback) {} } // namespace webrtc
{ "content_hash": "e65fd3cb6403cc4b6165a373e60180ca", "timestamp": "", "source": "github", "line_count": 512, "max_line_length": 80, "avg_line_length": 34.583984375, "alnum_prop": 0.672841249223471, "repo_name": "Alkalyne/webrtctrunk", "id": "6d64304149d662f746c78563e389a1e03deea921", "size": "18119", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "modules/rtp_rtcp/source/receive_statistics_impl.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "22469" }, { "name": "C", "bytes": "3405665" }, { "name": "C++", "bytes": "24404959" }, { "name": "CSS", "bytes": "1617" }, { "name": "Java", "bytes": "643292" }, { "name": "JavaScript", "bytes": "5409" }, { "name": "Matlab", "bytes": "26947" }, { "name": "Objective-C", "bytes": "186937" }, { "name": "Objective-C++", "bytes": "472228" }, { "name": "Protocol Buffer", "bytes": "21689" }, { "name": "Python", "bytes": "146387" }, { "name": "Ruby", "bytes": "615" }, { "name": "Shell", "bytes": "75957" } ], "symlink_target": "" }
/* author:@shivkrthakur */ /* Declare second integer, double, and String variables. */ int input1 = scan.nextInt(); double input2 = scan.nextDouble(); scan.nextLine(); String input3 = scan.nextLine(); /* Read and save an integer, double, and String to your variables.*/ System.out.println(input1 + i); /* Print the sum of both integer variables on a new line. */ /* Print the sum of the double variables on a new line. */ System.out.println(input2 + d); /* Concatenate and print the String variables on a new line; the 's' variable above should be printed first. */ System.out.println(s + input3);
{ "content_hash": "963c0a34d54be95851b87408bf1b6761", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 68, "avg_line_length": 40.13333333333333, "alnum_prop": 0.7159468438538206, "repo_name": "shivkrthakur/HackerRankSolutions", "id": "b5f4b62ef4218bbd05803e07a15d806a44169554", "size": "602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Practice/AllDomains/Tutorials/30DaysOfCode/Day1DataTypes.java", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "175716" }, { "name": "Java", "bytes": "15673" }, { "name": "JavaScript", "bytes": "113116" }, { "name": "Python", "bytes": "11480" }, { "name": "SQLPL", "bytes": "1603" } ], "symlink_target": "" }
class GenericFile < ActiveRecord::Base has_paper_trail mount_uploader :file, GenericFileUploader validates_presence_of :file validates_presence_of :name belongs_to :archeological_site end
{ "content_hash": "fff2236c455102951f7992813e455915", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 43, "avg_line_length": 18.727272727272727, "alnum_prop": 0.7572815533980582, "repo_name": "olendorf/grenada_archaeology", "id": "5c698d42405a1cae7aec8f33f0dadf7a0c4d49c7", "size": "289", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "app/models/generic_file.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1827" }, { "name": "CoffeeScript", "bytes": "240" }, { "name": "HTML", "bytes": "13167" }, { "name": "JavaScript", "bytes": "661" }, { "name": "Ruby", "bytes": "133265" } ], "symlink_target": "" }
const request = require('request') const createResource = require('../source/lib/resource').createResource const simple = require('simple-mock') const expect = require('chai').expect describe('Resource', () => { const resource = createResource({key: 'abc'}) it('should be an array', () => { expect(Array.isArray(resource)).to.be.ok }) it('should inherit parent key', () => { expect(resource.key).to.equal('abc') }) it('should start with empty filters', () => { expect(resource.filters).to.deep.equal({}) }) it('initially getTotalResults() should return -1', () => { expect(resource.getTotalResults()).to.equal(-1) }) it('filter() should update filters property', () => { resource.filter({a: 'a'}) expect(resource.filters).to.deep.equal({a: 'a'}) }) it('filter() should expand filters property', () => { resource.filter({b: 'b'}) expect(resource.filters).to.deep.equal({a: 'a', b: 'b'}) }) describe('Internal interaction with Youtube API', () => { const sendReqMock = simple.mock(resource, 'sendRequest') describe('fetch() polymorphisms', () => { /* fetch() is a polymorphism function. This means that when called * and its first parameter is a number, it is taken as the value for * `maxResults' Youtube API param. In this case, the second argument * is a success callback, and a thrid argument is a rejection callback * * If the first parameter is a function, then we treat it as a success * callback, the second argument (if any) is an rejection handler. */ it('should handle numbers as first parameter', () => { resource.fetch(44) expect(sendReqMock.lastCall.arg).to.contain('&maxResults=44') }) it('should handle number as first and success callback as second', () => { const success = () => {} resource.fetch(10, success) expect(sendReqMock.lastCall.args[1]).to.equal(success) }) it('params for success and rejection callbacks', () => { const success = () => {} const reject = () => {} resource.fetch(success, reject) expect(sendReqMock.lastCall.args[1]).to.equal(success) expect(sendReqMock.lastCall.args[2]).to.equal(reject) }) }) it('should pass auth key', () => { resource.fetch() expect(sendReqMock.lastCall.arg).to.contain('key=abc') }) it('should handle filters as request params', () => { resource.filters = {} resource.filter({prop1: 'value1', prop2: 'value2'}) resource.fetch() Object.getOwnPropertyNames(resource.filters).forEach(prop => { expect(sendReqMock.lastCall.arg) .to.contain(`${prop}=${resource.filters[prop]}`) }) }) it('should handle parts setting', () => { resource.fetch() expect(sendReqMock.lastCall.arg) .to.contain(`&part=${resource.parts.join('%2C')}`) }) describe('next()', () => { it('expect next() to pass nextPageToken', () => { const mockedBody = { nextPageToken: 'abc', pageInfo: {}, items: [] } resource.onResolveRequest(mockedBody, Function.prototype) resource.next() expect(sendReqMock.lastCall.arg).to.contain('pageToken=abc') }) }) }) })
{ "content_hash": "692414968432e2dc74765d0652dd5140", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 86, "avg_line_length": 36.950980392156865, "alnum_prop": 0.5338286017511277, "repo_name": "christopher-ramirez/youtube-query", "id": "077823df44530ec2469aa023477a1a3a5daac50b", "size": "3769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/resource.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "14333" } ], "symlink_target": "" }
<?php namespace Core\Mail; /** * PHPMailer POP-Before-SMTP Authentication Class. * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. * Does not support APOP. * @package PHPMailer * @author Richard Davey (original author) <rich@corephp.co.uk> * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> */ class POP3 { /** * The POP3 PHPMailer Version number. * @var string * @access public */ public $Version = '5.4.0'; /** * Default POP3 port number. * @var integer * @access public */ public $POP3_PORT = 110; /** * Default timeout in seconds. * @var integer * @access public */ public $POP3_TIMEOUT = 30; /** * Debug display level. * Options: 0 = no, 1+ = yes * @var integer * @access public */ public $do_debug = 0; /** * POP3 mail server hostname. * @var string * @access public */ public $host; /** * POP3 port number. * @var integer * @access public */ public $port; /** * POP3 Timeout Value in seconds. * @var integer * @access public */ public $tval; /** * POP3 username * @var string * @access public */ public $username; /** * POP3 password. * @var string * @access public */ public $password; /** * Resource handle for the POP3 connection socket. * @var resource * @access protected */ protected $pop_conn; /** * Are we connected? * @var boolean * @access protected */ protected $connected = false; /** * Error container. * @var array * @access protected */ protected $errors = []; /** * Line break constant */ const CRLF = "\r\n"; /** * Simple static wrapper for all-in-one POP before SMTP * @param $host * @param integer|boolean $port The port number to connect to * @param integer|boolean $timeout The timeout value * @param string $username * @param string $password * @param integer $debug_level * @return boolean */ public static function popBeforeSmtp( $host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0 ) { $pop = new POP3; return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level); } /** * Authenticate with a POP3 server. * A connect, login, disconnect sequence * appropriate for POP-before SMTP authorisation. * @access public * @param string $host The hostname to connect to * @param integer|boolean $port The port number to connect to * @param integer|boolean $timeout The timeout value * @param string $username * @param string $password * @param integer $debug_level * @return boolean */ public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) { $this->host = $host; // If no port value provided, use default if (false === $port) { $this->port = $this->POP3_PORT; } else { $this->port = (integer) $port; } // If no timeout value provided, use default if (false === $timeout) { $this->tval = $this->POP3_TIMEOUT; } else { $this->tval = (integer) $timeout; } $this->do_debug = $debug_level; $this->username = $username; $this->password = $password; // Reset the error log $this->errors = []; // connect $result = $this->connect($this->host, $this->port, $this->tval); if ($result) { $login_result = $this->login($this->username, $this->password); if ($login_result) { $this->disconnect(); return true; } } // We need to disconnect regardless of whether the login succeeded $this->disconnect(); return false; } /** * Connect to a POP3 server. * @access public * @param string $host * @param integer|boolean $port * @param integer $tval * @return boolean */ public function connect($host, $port = false, $tval = 30) { // Are we already connected? if ($this->connected) { return true; } //On Windows this will raise a PHP Warning error if the hostname doesn't exist. //Rather than suppress it with @fsockopen, capture it cleanly instead set_error_handler([$this, 'catchWarning']); if (false === $port) { $port = $this->POP3_PORT; } // connect to the POP3 server $this->pop_conn = fsockopen( $host, // POP3 Host $port, // Port # $errno, // Error Number $errstr, // Error Message $tval ); // Timeout (seconds) // Restore the error handler restore_error_handler(); // Did we connect? if (false === $this->pop_conn) { // It would appear not... $this->setError( [ 'error' => "Failed to connect to server $host on port $port", 'errno' => $errno, 'errstr' => $errstr ] ); return false; } // Increase the stream time-out stream_set_timeout($this->pop_conn, $tval, 0); // Get the POP3 server response $pop3_response = $this->getResponse(); // Check for the +OK if ($this->checkResponse($pop3_response)) { // The connection is established and the POP3 server is talking $this->connected = true; return true; } return false; } /** * Log in to the POP3 server. * Does not support APOP (RFC 2828, 4949). * @access public * @param string $username * @param string $password * @return boolean */ public function login($username = '', $password = '') { if (!$this->connected) { $this->setError('Not connected to POP3 server'); } if (empty($username)) { $username = $this->username; } if (empty($password)) { $password = $this->password; } // Send the Username $this->sendString("USER $username" . self::CRLF); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { // Send the Password $this->sendString("PASS $password" . self::CRLF); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { return true; } } return false; } /** * Disconnect from the POP3 server. * @access public */ public function disconnect() { $this->sendString('QUIT'); //The QUIT command may cause the daemon to exit, which will kill our connection //So ignore errors here try { @fclose($this->pop_conn); } catch (Exception $exception) { $ex = new \Core\MyException(); $ex->show_exception($exception); //Do nothing }; } /** * Get a response from the POP3 server. * $size is the maximum number of bytes to retrieve * @param integer $size * @return string * @access protected */ protected function getResponse($size = 128) { $response = fgets($this->pop_conn, $size); if ($this->do_debug >= 1) { echo "Server -> Client: $response"; } return $response; } /** * Send raw data to the POP3 server. * @param string $string * @return integer * @access protected */ protected function sendString($string) { if ($this->pop_conn) { if ($this->do_debug >= 2) { //Show client messages when debug >= 2 echo "Client -> Server: $string"; } return fwrite($this->pop_conn, $string, strlen($string)); } return 0; } /** * Checks the POP3 server response. * Looks for for +OK or -ERR. * @param string $string * @return boolean * @access protected */ protected function checkResponse($string) { if (substr($string, 0, 3) !== '+OK') { $this->setError( [ 'error' => "Server reported an error: $string", 'errno' => 0, 'errstr' => '' ] ); return false; } else { return true; } } /** * Add an error to the internal error store. * Also display debug output if it's enabled. * @param $error * @access protected */ protected function setError($error) { $this->errors[] = $error; if ($this->do_debug >= 1) { echo '<pre>'; foreach ($this->errors as $error) { print_r($error); } echo '</pre>'; } } /** * Get an array of error messages, if any. * @return array */ public function getErrors() { return $this->errors; } /** * POP3 connection error handler. * @param integer $errno * @param string $errstr * @param string $errfile * @param integer $errline * @access protected */ protected function catchWarning($errno, $errstr, $errfile, $errline) { $this->setError( [ 'error' => 'Connecting to the POP3 server raised a PHP warning: ', 'errno' => $errno, 'errstr' => $errstr, 'errfile' => $errfile, 'errline' => $errline ] ); } }
{ "content_hash": "1ceabe1b7c103b2e50e5efb971fd8837", "timestamp": "", "source": "github", "line_count": 380, "max_line_length": 121, "avg_line_length": 27.03684210526316, "alnum_prop": 0.5096359743040685, "repo_name": "lucasnpinheiro/Aulas", "id": "2b6c16caf69343f0b042e45501859e684c9c7a8f", "size": "11070", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Mail/POP3.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "328" }, { "name": "Batchfile", "bytes": "216" }, { "name": "CSS", "bytes": "881" }, { "name": "HTML", "bytes": "131" }, { "name": "JavaScript", "bytes": "3011" }, { "name": "PHP", "bytes": "604010" }, { "name": "Shell", "bytes": "1071" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../spec_helper' describe Contact do before(:each) do @contact = Contact.new end it "should be valid" do @contact.should be_valid end end
{ "content_hash": "bd02dd7aecdeed0648e55516a35a2029", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 50, "avg_line_length": 18.272727272727273, "alnum_prop": 0.6169154228855721, "repo_name": "gotoAndBliss/True-Jersey", "id": "4a06511e230471735b8709e3bf03701a31af2ead", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/extensions/contact/spec/models/contact_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "461730" }, { "name": "Ruby", "bytes": "622657" } ], "symlink_target": "" }
package com.wrapper.spotify.methods.authentication; import com.wrapper.spotify.Api; import com.wrapper.spotify.TestUtil; import com.wrapper.spotify.models.AuthorizationCodeCredentials; import org.junit.Test; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.fail; public class AuthorizationCodeGrantRequestTest { @Test public void shouldGetTokenResponse_sync() throws Exception { final String clientId = "myClientId"; final String clientSecret = "myClientSecret"; final String redirectUri = "myRedirectUri"; final String code = "myCode"; final Api api = Api.builder() .clientId(clientId) .clientSecret(clientSecret) .redirectURI(redirectUri) .build(); final AuthorizationCodeGrantRequest request = api.authorizationCodeGrant(code) .httpManager(TestUtil.MockedHttpManager.returningJson("auth-tokens.json")) .build(); try { final AuthorizationCodeCredentials tokens = request.get(); assertEquals("BQBY2M94xNVE_7p7x1MhNd2I1UNs62cv-CVDXkDwh5YqSiKJceKRXwJfUrLmJFKO7GfiCZKTh8oEEj3b84bZx1Qy52qwGYCVhX6yHPJY4VDday-hC1YMPOWyIt9Bp05UuJb673btr6T1YOd0DliheWDyqQ", tokens.getAccessToken()); assertEquals("Bearer", tokens.getTokenType()); assertEquals(3600, tokens.getExpiresIn()); assertEquals("AQAZ54v-sV7LO_R64q76KtDMKeQcPkBIPAuKFqYr1kSAeaU8_S8ZxbnqcNizeQiSJr5DhMsJvCdgS7_KUrHd7rw1z7h_FJkL5OVOnthZrNFdO5NL7gUvNJRF6hdbIkAnEHM", tokens.getRefreshToken()); } catch (Exception e) { fail(e.getMessage()); } } }
{ "content_hash": "d0f17c5ee5a4b915d471a03be65bc28b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 202, "avg_line_length": 39.85, "alnum_prop": 0.7540777917189461, "repo_name": "PatMulvihill/spotify-web-api-java", "id": "a343ca955140802c00c29bc9dc508cf4588af570", "size": "1594", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/com/wrapper/spotify/methods/authentication/AuthorizationCodeGrantRequestTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "262113" }, { "name": "Protocol Buffer", "bytes": "741" }, { "name": "Shell", "bytes": "132" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2cd295482d74c526bfb9990134aae697", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "8e782e996f920bc00e62df31cedf8bccf71a228e", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Cleisostoma/Cleisostoma javanicum/ Syn. Sarcanthus quartus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ο»Ώusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpGL { public class PrismoidModel : IBufferSource, IObjFormat { private vec3 modelSize; public vec3 ModelSize() { return this.modelSize; } public PrismoidModel(float topXLength, float topZLength, float bottomXLength, float bottomZLength, float height) { float xDiff = (bottomXLength - topXLength) / 2; float zDiff = (bottomZLength - topZLength) / 2; var positions = new vec3[8]; positions[0] = new vec3(topXLength + xDiff, height, topZLength + zDiff); positions[1] = new vec3(topXLength + xDiff, height, 0); positions[2] = new vec3(bottomXLength, 0, bottomZLength); positions[3] = new vec3(bottomXLength, 0, 0); positions[4] = new vec3(xDiff, height, topZLength + zDiff); positions[5] = new vec3(xDiff, height, zDiff); positions[6] = new vec3(0, 0, bottomZLength); positions[7] = new vec3(0, 0, 0); BoundingBox box = positions.Move2Center(); this.positions = positions; this.modelSize = box.MaxPosition - box.MinPosition; } private vec3[] positions; private static readonly uint[] indexes = new uint[] { 0, 2, 1, 1, 2, 3, 0, 1, 5, 0, 5, 4, 0, 4, 2, 2, 4, 6, 7, 6, 4, 7, 4, 5, 7, 5, 3, 3, 5, 1, 7, 3, 2, 7, 2, 6, }; public const string strPosition = "position"; private VertexBuffer positionBuffer; private IDrawCommand drawCommand; #region IBufferSource ζˆε‘˜ public IEnumerable<VertexBuffer> GetVertexAttribute(string bufferName) { if (strPosition == bufferName) // requiring position buffer. { if (this.positionBuffer == null) { this.positionBuffer = positions.GenVertexBuffer(VBOConfig.Vec3, BufferUsage.StaticDraw); } yield return this.positionBuffer; } else { throw new ArgumentException("bufferName"); } } public IEnumerable<IDrawCommand> GetDrawCommand() { if (this.drawCommand == null) { IndexBuffer indexBuffer = indexes.GenIndexBuffer(BufferUsage.StaticDraw); this.drawCommand = new DrawElementsCmd(indexBuffer, DrawMode.Triangles); } yield return this.drawCommand; } #endregion #region IObjFormat ζˆε‘˜ public vec3[] GetPositions() { return this.positions; } public vec2[] GetTexCoords() { return new vec2[] { }; } public uint[] GetIndexes() { return indexes; } #endregion } }
{ "content_hash": "2750ecd69c8d94b97e1effc7a66bd70c", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 122, "avg_line_length": 32.46666666666667, "alnum_prop": 0.554757015742642, "repo_name": "bitzhuwei/CSharpGL", "id": "bd80d189c5510431d5c91202c28f9a0f0b78602d", "size": "2932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Infrastructure/CSharpGL.Models/HanoiTower/PrismoidModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "43" }, { "name": "C", "bytes": "228855" }, { "name": "C#", "bytes": "4399753" }, { "name": "C++", "bytes": "17417" }, { "name": "GLSL", "bytes": "3191" }, { "name": "Smalltalk", "bytes": "118027" } ], "symlink_target": "" }
/* * 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 io.trino.sql.planner.assertions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.trino.Session; import io.trino.connector.CatalogName; import io.trino.execution.warnings.WarningCollector; import io.trino.plugin.tpch.TpchConnectorFactory; import io.trino.sql.planner.LogicalPlanner; import io.trino.sql.planner.Plan; import io.trino.sql.planner.RuleStatsRecorder; import io.trino.sql.planner.SubPlan; import io.trino.sql.planner.iterative.IterativeOptimizer; import io.trino.sql.planner.iterative.Rule; import io.trino.sql.planner.iterative.rule.RemoveRedundantIdentityProjections; import io.trino.sql.planner.optimizations.PlanOptimizer; import io.trino.sql.planner.optimizations.UnaliasSymbolReferences; import io.trino.testing.LocalQueryRunner; import org.intellij.lang.annotations.Language; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Predicate; import static io.airlift.testing.Closeables.closeAllRuntimeException; import static io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED; import static io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED_AND_VALIDATED; import static io.trino.sql.planner.PlanOptimizers.columnPruningRules; import static io.trino.testing.TestingSession.testSessionBuilder; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; public class BasePlanTest { private final Map<String, String> sessionProperties; private LocalQueryRunner queryRunner; public BasePlanTest() { this(ImmutableMap.of()); } public BasePlanTest(Map<String, String> sessionProperties) { this.sessionProperties = requireNonNull(sessionProperties, "sessionProperties is null"); } // Subclasses should implement this method to inject their own query runners protected LocalQueryRunner createLocalQueryRunner() { Session.SessionBuilder sessionBuilder = testSessionBuilder() .setCatalog("local") .setSchema("tiny") .setSystemProperty("task_concurrency", "1"); // these tests don't handle exchanges from local parallel sessionProperties.forEach(sessionBuilder::setSystemProperty); LocalQueryRunner queryRunner = LocalQueryRunner.create(sessionBuilder.build()); queryRunner.createCatalog(queryRunner.getDefaultSession().getCatalog().get(), new TpchConnectorFactory(1), ImmutableMap.of()); return queryRunner; } @BeforeClass public final void initPlanTest() { this.queryRunner = createLocalQueryRunner(); } @AfterClass(alwaysRun = true) public final void destroyPlanTest() { closeAllRuntimeException(queryRunner); queryRunner = null; } protected CatalogName getCurrentConnectorId() { return queryRunner.inTransaction(transactionSession -> queryRunner.getMetadata().getCatalogHandle(transactionSession, transactionSession.getCatalog().get())).get(); } protected LocalQueryRunner getQueryRunner() { return queryRunner; } protected void assertPlan(@Language("SQL") String sql, PlanMatchPattern pattern) { assertPlan(sql, OPTIMIZED_AND_VALIDATED, pattern); } protected void assertPlan(@Language("SQL") String sql, Session session, PlanMatchPattern pattern) { assertPlanWithSession(sql, session, true, pattern); } protected void assertPlan(@Language("SQL") String sql, LogicalPlanner.Stage stage, PlanMatchPattern pattern) { List<PlanOptimizer> optimizers = queryRunner.getPlanOptimizers(true); assertPlan(sql, stage, pattern, optimizers); } protected void assertPlan(@Language("SQL") String sql, PlanMatchPattern pattern, List<PlanOptimizer> optimizers) { assertPlan(sql, OPTIMIZED, pattern, optimizers); } protected void assertPlan(@Language("SQL") String sql, LogicalPlanner.Stage stage, PlanMatchPattern pattern, Predicate<PlanOptimizer> optimizerPredicate) { List<PlanOptimizer> optimizers = queryRunner.getPlanOptimizers(true).stream() .filter(optimizerPredicate) .collect(toList()); assertPlan(sql, stage, pattern, optimizers); } protected void assertPlan(@Language("SQL") String sql, LogicalPlanner.Stage stage, PlanMatchPattern pattern, List<PlanOptimizer> optimizers) { queryRunner.inTransaction(transactionSession -> { Plan actualPlan = queryRunner.createPlan(transactionSession, sql, optimizers, stage, WarningCollector.NOOP); PlanAssert.assertPlan(transactionSession, queryRunner.getMetadata(), queryRunner.getStatsCalculator(), actualPlan, pattern); return null; }); } protected void assertDistributedPlan(@Language("SQL") String sql, PlanMatchPattern pattern) { assertDistributedPlan(sql, getQueryRunner().getDefaultSession(), pattern); } protected void assertDistributedPlan(@Language("SQL") String sql, Session session, PlanMatchPattern pattern) { assertPlanWithSession(sql, session, false, pattern); } protected void assertMinimallyOptimizedPlan(@Language("SQL") String sql, PlanMatchPattern pattern) { List<PlanOptimizer> optimizers = ImmutableList.of( new UnaliasSymbolReferences(getQueryRunner().getMetadata()), new IterativeOptimizer( queryRunner.getMetadata(), new RuleStatsRecorder(), queryRunner.getStatsCalculator(), queryRunner.getCostCalculator(), ImmutableSet.<Rule<?>>builder() .add(new RemoveRedundantIdentityProjections()) .addAll(columnPruningRules(getQueryRunner().getMetadata())) .build())); assertPlan(sql, OPTIMIZED, pattern, optimizers); } protected void assertPlanWithSession(@Language("SQL") String sql, Session session, boolean forceSingleNode, PlanMatchPattern pattern) { queryRunner.inTransaction(session, transactionSession -> { Plan actualPlan = queryRunner.createPlan(transactionSession, sql, OPTIMIZED_AND_VALIDATED, forceSingleNode, WarningCollector.NOOP); PlanAssert.assertPlan(transactionSession, queryRunner.getMetadata(), queryRunner.getStatsCalculator(), actualPlan, pattern); return null; }); } protected void assertPlanWithSession(@Language("SQL") String sql, Session session, boolean forceSingleNode, PlanMatchPattern pattern, Consumer<Plan> planValidator) { queryRunner.inTransaction(session, transactionSession -> { Plan actualPlan = queryRunner.createPlan(transactionSession, sql, OPTIMIZED_AND_VALIDATED, forceSingleNode, WarningCollector.NOOP); PlanAssert.assertPlan(transactionSession, queryRunner.getMetadata(), queryRunner.getStatsCalculator(), actualPlan, pattern); planValidator.accept(actualPlan); return null; }); } protected Plan plan(@Language("SQL") String sql) { return plan(sql, OPTIMIZED_AND_VALIDATED); } protected Plan plan(@Language("SQL") String sql, LogicalPlanner.Stage stage) { return plan(sql, stage, true); } protected Plan plan(@Language("SQL") String sql, LogicalPlanner.Stage stage, boolean forceSingleNode) { try { return queryRunner.inTransaction(transactionSession -> queryRunner.createPlan(transactionSession, sql, stage, forceSingleNode, WarningCollector.NOOP)); } catch (RuntimeException e) { throw new AssertionError("Planning failed for SQL: " + sql, e); } } protected SubPlan subplan(@Language("SQL") String sql, LogicalPlanner.Stage stage, boolean forceSingleNode) { return subplan(sql, stage, forceSingleNode, getQueryRunner().getDefaultSession()); } protected SubPlan subplan(@Language("SQL") String sql, LogicalPlanner.Stage stage, boolean forceSingleNode, Session session) { try { return queryRunner.inTransaction(session, transactionSession -> { Plan plan = queryRunner.createPlan(transactionSession, sql, stage, forceSingleNode, WarningCollector.NOOP); return queryRunner.createSubPlans(transactionSession, plan, forceSingleNode); }); } catch (RuntimeException e) { throw new AssertionError("Planning failed for SQL: " + sql, e); } } }
{ "content_hash": "8c9747053705d90dac33b9b548e69ae4", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 172, "avg_line_length": 41.10480349344978, "alnum_prop": 0.7067884840114735, "repo_name": "ebyhr/presto", "id": "c96314b08c4fc854b99055fcea71966c4ef2ea21", "size": "9413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/trino-main/src/test/java/io/trino/sql/planner/assertions/BasePlanTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "26917" }, { "name": "CSS", "bytes": "12957" }, { "name": "HTML", "bytes": "28832" }, { "name": "Java", "bytes": "31247929" }, { "name": "JavaScript", "bytes": "211244" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "PLpgSQL", "bytes": "11504" }, { "name": "Python", "bytes": "7811" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29857" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
package com.wavesplatform.api.http.requests import com.wavesplatform.account.PublicKey import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.Script import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.smart.SetScriptTransaction import play.api.libs.functional.syntax._ import play.api.libs.json._ object SignedSetScriptRequest { implicit val signedSetScriptRequestReads: Reads[SignedSetScriptRequest] = ( (JsPath \ "version").readNullable[Byte] and (JsPath \ "senderPublicKey").read[String] and (JsPath \ "script").readNullable[String] and (JsPath \ "fee").read[Long] and (JsPath \ "timestamp").read[Long] and (JsPath \ "proofs").read[Proofs] )(SignedSetScriptRequest.apply _) implicit val signedSetScriptRequestWrites: OWrites[SignedSetScriptRequest] = Json.writes[SignedSetScriptRequest].transform((request: JsObject) => request + ("version" -> JsNumber(1))) } case class SignedSetScriptRequest( version: Option[Byte], senderPublicKey: String, script: Option[String], fee: Long, timestamp: Long, proofs: Proofs ) { def toTx: Either[ValidationError, SetScriptTransaction] = for { _sender <- PublicKey.fromBase58String(senderPublicKey) _script <- script match { case None | Some("") => Right(None) case Some(s) => Script.fromBase64String(s).map(Some(_)) } t <- SetScriptTransaction.create(version.getOrElse(1.toByte), _sender, _script, fee, timestamp, proofs) } yield t }
{ "content_hash": "727a34a564fabaa595cb290b5920989a", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 110, "avg_line_length": 37.11904761904762, "alnum_prop": 0.7177677998717127, "repo_name": "wavesplatform/Waves", "id": "a2398350a5d94731a0c8f01efcf02e8241ce8fe5", "size": "1559", "binary": false, "copies": "1", "ref": "refs/heads/version-1.4.x", "path": "node/src/main/scala/com/wavesplatform/api/http/requests/SignedSetScriptRequest.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "2248" }, { "name": "HTML", "bytes": "4665" }, { "name": "Java", "bytes": "360" }, { "name": "Scala", "bytes": "7393151" }, { "name": "Shell", "bytes": "1365" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>paramiko.sftp</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="paramiko-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="paramiko-module.html">Package&nbsp;paramiko</a> :: Module&nbsp;sftp </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="paramiko.sftp-module.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== MODULE DESCRIPTION ==================== --> <h1 class="epydoc">Module sftp</h1><p class="nomargin-top"><span class="codelink"><a href="paramiko.sftp-pysrc.html">source&nbsp;code</a></span></p> <!-- ==================== VARIABLES ==================== --> <a name="section-Variables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td align="left" colspan="2" class="table-header"> <span class="table-header">Variables</span></td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_OK"></a><span class="summary-name">SFTP_OK</span> = <code title="0">0</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="paramiko.sftp-module.html#SFTP_DESC" class="summary-name">SFTP_DESC</a> = <code title="['Success', 'End of file', 'No such file', 'Permission denied', 'Failure', 'Bad message', 'No connection', 'Connection lost', ..."><code class="variable-group">[</code><code class="variable-quote">'</code><code class="variable-string">Success</code><code class="variable-quote">'</code><code class="variable-op">, </code><code class="variable-quote">'</code><code class="variable-string">End of file</code><code class="variable-quote">'</code><code class="variable-op">, </code><code class="variable-quote">'</code><code class="variable-string">No such file</code><code class="variable-quote">'</code><code class="variable-op">, </code><code class="variable-quote">'</code><code class="variable-string">Permis</code><code class="variable-ellipsis">...</code></code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_FLAG_READ"></a><span class="summary-name">SFTP_FLAG_READ</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_FLAG_WRITE"></a><span class="summary-name">SFTP_FLAG_WRITE</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_FLAG_APPEND"></a><span class="summary-name">SFTP_FLAG_APPEND</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_FLAG_CREATE"></a><span class="summary-name">SFTP_FLAG_CREATE</span> = <code title="8">8</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_FLAG_TRUNC"></a><span class="summary-name">SFTP_FLAG_TRUNC</span> = <code title="16">16</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_FLAG_EXCL"></a><span class="summary-name">SFTP_FLAG_EXCL</span> = <code title="32">32</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="paramiko.sftp-module.html#CMD_NAMES" class="summary-name">CMD_NAMES</a> = <code title="{1: 'init', 2: 'version', 3: 'open', 4: 'close', 5: 'read', 6: 'write', 7: 'lstat', 8: 'fstat', ..."><code class="variable-group">{</code>1<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">init</code><code class="variable-quote">'</code><code class="variable-op">, </code>2<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">version</code><code class="variable-quote">'</code><code class="variable-op">, </code>3<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">open</code><code class="variable-quote">'</code><code class="variable-op">, </code>4<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">close</code><code class="variable-quote">'</code><code class="variable-op">, </code>5<code class="variable-ellipsis">...</code></code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="AUTH_FAILED"></a><span class="summary-name">AUTH_FAILED</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="AUTH_PARTIALLY_SUCCESSFUL"></a><span class="summary-name">AUTH_PARTIALLY_SUCCESSFUL</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="AUTH_SUCCESSFUL"></a><span class="summary-name">AUTH_SUCCESSFUL</span> = <code title="0">0</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_ATTRS"></a><span class="summary-name">CMD_ATTRS</span> = <code title="105">105</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_CLOSE"></a><span class="summary-name">CMD_CLOSE</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_DATA"></a><span class="summary-name">CMD_DATA</span> = <code title="103">103</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_EXTENDED"></a><span class="summary-name">CMD_EXTENDED</span> = <code title="200">200</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_EXTENDED_REPLY"></a><span class="summary-name">CMD_EXTENDED_REPLY</span> = <code title="201">201</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_FSETSTAT"></a><span class="summary-name">CMD_FSETSTAT</span> = <code title="10">10</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_FSTAT"></a><span class="summary-name">CMD_FSTAT</span> = <code title="8">8</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_HANDLE"></a><span class="summary-name">CMD_HANDLE</span> = <code title="102">102</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_INIT"></a><span class="summary-name">CMD_INIT</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_LSTAT"></a><span class="summary-name">CMD_LSTAT</span> = <code title="7">7</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_MKDIR"></a><span class="summary-name">CMD_MKDIR</span> = <code title="14">14</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_NAME"></a><span class="summary-name">CMD_NAME</span> = <code title="104">104</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_OPEN"></a><span class="summary-name">CMD_OPEN</span> = <code title="3">3</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_OPENDIR"></a><span class="summary-name">CMD_OPENDIR</span> = <code title="11">11</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_READ"></a><span class="summary-name">CMD_READ</span> = <code title="5">5</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_READDIR"></a><span class="summary-name">CMD_READDIR</span> = <code title="12">12</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_READLINK"></a><span class="summary-name">CMD_READLINK</span> = <code title="19">19</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_REALPATH"></a><span class="summary-name">CMD_REALPATH</span> = <code title="16">16</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_REMOVE"></a><span class="summary-name">CMD_REMOVE</span> = <code title="13">13</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_RENAME"></a><span class="summary-name">CMD_RENAME</span> = <code title="18">18</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_RMDIR"></a><span class="summary-name">CMD_RMDIR</span> = <code title="15">15</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_SETSTAT"></a><span class="summary-name">CMD_SETSTAT</span> = <code title="9">9</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_STAT"></a><span class="summary-name">CMD_STAT</span> = <code title="17">17</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_STATUS"></a><span class="summary-name">CMD_STATUS</span> = <code title="101">101</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_SYMLINK"></a><span class="summary-name">CMD_SYMLINK</span> = <code title="20">20</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_VERSION"></a><span class="summary-name">CMD_VERSION</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CMD_WRITE"></a><span class="summary-name">CMD_WRITE</span> = <code title="6">6</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="paramiko.sftp-module.html#CONNECTION_FAILED_CODE" class="summary-name">CONNECTION_FAILED_CODE</a> = <code title="{1: 'Administratively prohibited', 2: 'Connect failed', 3: 'Unknown channel type', 4: 'Resource shortage'}"><code class="variable-group">{</code>1<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">Administratively prohibited</code><code class="variable-quote">'</code><code class="variable-op">, </code>2<code class="variable-op">:</code><code class="variable-ellipsis">...</code></code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CRITICAL"></a><span class="summary-name">CRITICAL</span> = <code title="50">50</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DEBUG"></a><span class="summary-name">DEBUG</span> = <code title="10">10</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DISCONNECT_AUTH_CANCELLED_BY_USER"></a><span class="summary-name">DISCONNECT_AUTH_CANCELLED_BY_USER</span> = <code title="13">13</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE"></a><span class="summary-name">DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE</span> = <code title="14">14</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DISCONNECT_SERVICE_NOT_AVAILABLE"></a><span class="summary-name">DISCONNECT_SERVICE_NOT_AVAILABLE</span> = <code title="7">7</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ERROR"></a><span class="summary-name">ERROR</span> = <code title="40">40</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="INFO"></a><span class="summary-name">INFO</span> = <code title="20">20</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_CLOSE"></a><span class="summary-name">MSG_CHANNEL_CLOSE</span> = <code title="97">97</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_DATA"></a><span class="summary-name">MSG_CHANNEL_DATA</span> = <code title="94">94</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_EOF"></a><span class="summary-name">MSG_CHANNEL_EOF</span> = <code title="96">96</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_EXTENDED_DATA"></a><span class="summary-name">MSG_CHANNEL_EXTENDED_DATA</span> = <code title="95">95</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_FAILURE"></a><span class="summary-name">MSG_CHANNEL_FAILURE</span> = <code title="100">100</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_OPEN"></a><span class="summary-name">MSG_CHANNEL_OPEN</span> = <code title="90">90</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_OPEN_FAILURE"></a><span class="summary-name">MSG_CHANNEL_OPEN_FAILURE</span> = <code title="92">92</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_OPEN_SUCCESS"></a><span class="summary-name">MSG_CHANNEL_OPEN_SUCCESS</span> = <code title="91">91</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_REQUEST"></a><span class="summary-name">MSG_CHANNEL_REQUEST</span> = <code title="98">98</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_SUCCESS"></a><span class="summary-name">MSG_CHANNEL_SUCCESS</span> = <code title="99">99</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_CHANNEL_WINDOW_ADJUST"></a><span class="summary-name">MSG_CHANNEL_WINDOW_ADJUST</span> = <code title="93">93</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_DEBUG"></a><span class="summary-name">MSG_DEBUG</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_DISCONNECT"></a><span class="summary-name">MSG_DISCONNECT</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_GLOBAL_REQUEST"></a><span class="summary-name">MSG_GLOBAL_REQUEST</span> = <code title="80">80</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_IGNORE"></a><span class="summary-name">MSG_IGNORE</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_KEXINIT"></a><span class="summary-name">MSG_KEXINIT</span> = <code title="20">20</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="paramiko.sftp-module.html#MSG_NAMES" class="summary-name">MSG_NAMES</a> = <code title="{1: 'disconnect', 2: 'ignore', 3: 'unimplemented', 4: 'debug', 5: 'service-request', 6: 'service-accept', 20: 'kexinit', 21: 'newkeys', ..."><code class="variable-group">{</code>1<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">disconnect</code><code class="variable-quote">'</code><code class="variable-op">, </code>2<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">ignore</code><code class="variable-quote">'</code><code class="variable-op">, </code>3<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">unimplemented</code><code class="variable-quote">'</code><code class="variable-op">,</code><code class="variable-ellipsis">...</code></code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_NEWKEYS"></a><span class="summary-name">MSG_NEWKEYS</span> = <code title="21">21</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_REQUEST_FAILURE"></a><span class="summary-name">MSG_REQUEST_FAILURE</span> = <code title="82">82</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_REQUEST_SUCCESS"></a><span class="summary-name">MSG_REQUEST_SUCCESS</span> = <code title="81">81</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_SERVICE_ACCEPT"></a><span class="summary-name">MSG_SERVICE_ACCEPT</span> = <code title="6">6</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_SERVICE_REQUEST"></a><span class="summary-name">MSG_SERVICE_REQUEST</span> = <code title="5">5</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_UNIMPLEMENTED"></a><span class="summary-name">MSG_UNIMPLEMENTED</span> = <code title="3">3</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_USERAUTH_BANNER"></a><span class="summary-name">MSG_USERAUTH_BANNER</span> = <code title="53">53</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_USERAUTH_FAILURE"></a><span class="summary-name">MSG_USERAUTH_FAILURE</span> = <code title="51">51</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_USERAUTH_INFO_REQUEST"></a><span class="summary-name">MSG_USERAUTH_INFO_REQUEST</span> = <code title="60">60</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_USERAUTH_INFO_RESPONSE"></a><span class="summary-name">MSG_USERAUTH_INFO_RESPONSE</span> = <code title="61">61</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_USERAUTH_PK_OK"></a><span class="summary-name">MSG_USERAUTH_PK_OK</span> = <code title="60">60</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_USERAUTH_REQUEST"></a><span class="summary-name">MSG_USERAUTH_REQUEST</span> = <code title="50">50</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MSG_USERAUTH_SUCCESS"></a><span class="summary-name">MSG_USERAUTH_SUCCESS</span> = <code title="52">52</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED"></a><span class="summary-name">OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="OPEN_FAILED_CONNECT_FAILED"></a><span class="summary-name">OPEN_FAILED_CONNECT_FAILED</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="OPEN_FAILED_RESOURCE_SHORTAGE"></a><span class="summary-name">OPEN_FAILED_RESOURCE_SHORTAGE</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="OPEN_FAILED_UNKNOWN_CHANNEL_TYPE"></a><span class="summary-name">OPEN_FAILED_UNKNOWN_CHANNEL_TYPE</span> = <code title="3">3</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="OPEN_SUCCEEDED"></a><span class="summary-name">OPEN_SUCCEEDED</span> = <code title="0">0</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="PY22"></a><span class="summary-name">PY22</span> = <code title="False">False</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_BAD_MESSAGE"></a><span class="summary-name">SFTP_BAD_MESSAGE</span> = <code title="5">5</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_CONNECTION_LOST"></a><span class="summary-name">SFTP_CONNECTION_LOST</span> = <code title="7">7</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_EOF"></a><span class="summary-name">SFTP_EOF</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_FAILURE"></a><span class="summary-name">SFTP_FAILURE</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_NO_CONNECTION"></a><span class="summary-name">SFTP_NO_CONNECTION</span> = <code title="6">6</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_NO_SUCH_FILE"></a><span class="summary-name">SFTP_NO_SUCH_FILE</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_OP_UNSUPPORTED"></a><span class="summary-name">SFTP_OP_UNSUPPORTED</span> = <code title="8">8</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SFTP_PERMISSION_DENIED"></a><span class="summary-name">SFTP_PERMISSION_DENIED</span> = <code title="3">3</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WARNING"></a><span class="summary-name">WARNING</span> = <code title="30">30</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="randpool"></a><span class="summary-name">randpool</span> = <code title="OSRandomPool()">OSRandomPool()</code> </td> </tr> </table> <!-- ==================== VARIABLES DETAILS ==================== --> <a name="section-VariablesDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td align="left" colspan="2" class="table-header"> <span class="table-header">Variables Details</span></td> </tr> </table> <a name="SFTP_DESC"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">SFTP_DESC</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> <code class="variable-group">[</code><code class="variable-quote">'</code><code class="variable-string">Success</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-quote">'</code><code class="variable-string">End of file</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-quote">'</code><code class="variable-string">No such file</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-quote">'</code><code class="variable-string">Permission denied</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-quote">'</code><code class="variable-string">Failure</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-quote">'</code><code class="variable-string">Bad message</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-quote">'</code><code class="variable-string">No connection</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-quote">'</code><code class="variable-string">Connection lost</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-ellipsis">...</code> </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="CMD_NAMES"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">CMD_NAMES</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> <code class="variable-group">{</code>1<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">init</code><code class="variable-quote">'</code><code class="variable-op">,</code> 2<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">version</code><code class="variable-quote">'</code><code class="variable-op">,</code> 3<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">open</code><code class="variable-quote">'</code><code class="variable-op">,</code> 4<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">close</code><code class="variable-quote">'</code><code class="variable-op">,</code> 5<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">read</code><code class="variable-quote">'</code><code class="variable-op">,</code> 6<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">write</code><code class="variable-quote">'</code><code class="variable-op">,</code> 7<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">lstat</code><code class="variable-quote">'</code><code class="variable-op">,</code> 8<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">fstat</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-ellipsis">...</code> </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="CONNECTION_FAILED_CODE"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">CONNECTION_FAILED_CODE</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> <code class="variable-group">{</code>1<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">Administratively prohibited</code><code class="variable-quote">'</code><code class="variable-op">,</code> 2<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">Connect failed</code><code class="variable-quote">'</code><code class="variable-op">,</code> 3<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">Unknown channel type</code><code class="variable-quote">'</code><code class="variable-op">,</code> 4<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">Resource shortage</code><code class="variable-quote">'</code><code class="variable-group">}</code> </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="MSG_NAMES"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">MSG_NAMES</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> <code class="variable-group">{</code>1<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">disconnect</code><code class="variable-quote">'</code><code class="variable-op">,</code> 2<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">ignore</code><code class="variable-quote">'</code><code class="variable-op">,</code> 3<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">unimplemented</code><code class="variable-quote">'</code><code class="variable-op">,</code> 4<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">debug</code><code class="variable-quote">'</code><code class="variable-op">,</code> 5<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">service-request</code><code class="variable-quote">'</code><code class="variable-op">,</code> 6<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">service-accept</code><code class="variable-quote">'</code><code class="variable-op">,</code> 20<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">kexinit</code><code class="variable-quote">'</code><code class="variable-op">,</code> 21<code class="variable-op">: </code><code class="variable-quote">'</code><code class="variable-string">newkeys</code><code class="variable-quote">'</code><code class="variable-op">,</code> <code class="variable-ellipsis">...</code> </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="paramiko-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sun Mar 23 23:59:01 2008 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
{ "content_hash": "2924077c95bf4e98b777a2cd273be8bc", "timestamp": "", "source": "github", "line_count": 898, "max_line_length": 840, "avg_line_length": 44.76391982182628, "alnum_prop": 0.6047067018259615, "repo_name": "zeha/multiapt", "id": "3705b9363dfde363c86921684dd37b233c25a492", "size": "40198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extlib/paramiko-1.7.3/docs/paramiko.sftp-module.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10581" }, { "name": "Python", "bytes": "637846" } ], "symlink_target": "" }
describe RuboCop::Cop::Style::ElseAlignment do subject(:cop) { described_class.new(config) } let(:config) do RuboCop::Config.new('Lint/EndAlignment' => end_alignment_config) end let(:end_alignment_config) do { 'Enabled' => true, 'EnforcedStyleAlignWith' => 'variable' } end it 'accepts a ternary if' do inspect_source(cop, 'cond ? func1 : func2') expect(cop.offenses).to be_empty end context 'with if statement' do it 'registers an offense for misaligned else' do inspect_source(cop, ['if cond', ' func1', ' else', ' func2', 'end']) expect(cop.messages).to eq(['Align `else` with `if`.']) expect(cop.highlights).to eq(['else']) end it 'registers an offense for misaligned elsif' do inspect_source(cop, [' if a1', ' b1', 'elsif a2', ' b2', ' end']) expect(cop.messages).to eq(['Align `elsif` with `if`.']) expect(cop.highlights).to eq(['elsif']) end it 'accepts indentation after else when if is on new line after ' \ 'assignment' do inspect_source(cop, ['Rails.application.config.ideal_postcodes_key =', ' if Rails.env.production? || Rails.env.staging?', ' "AAAA-AAAA-AAAA-AAAA"', ' else', ' "BBBB-BBBB-BBBB-BBBB"', ' end']) expect(cop.offenses).to be_empty end describe '#autocorrect' do it 'corrects bad alignment' do corrected = autocorrect_source(cop, [' if a1', ' b1', ' elsif a2', ' b2', 'else', ' c', ' end']) expect(cop.messages).to eq(['Align `elsif` with `if`.', 'Align `else` with `if`.']) expect(corrected) .to eq [' if a1', ' b1', ' elsif a2', ' b2', ' else', ' c', ' end'].join("\n") end end it 'accepts a one line if statement' do inspect_source(cop, 'if cond then func1 else func2 end') expect(cop.offenses).to be_empty end it 'accepts a correctly aligned if/elsif/else/end' do inspect_source(cop, ['if a1', ' b1', 'elsif a2', ' b2', 'else', ' c', 'end']) expect(cop.offenses).to be_empty end context 'for a file with byte order mark' do let(:bom) { "\xef\xbb\xbf" } it 'accepts a correctly aligned if/elsif/else/end' do inspect_source(cop, ["#{bom}if a1", ' b1', 'elsif a2', ' b2', 'else', ' c', 'end']) expect(cop.offenses).to be_empty end end context 'with assignment' do context 'when alignment style is variable' do context 'and end is aligned with variable' do it 'accepts an if-else with end aligned with setter' do inspect_source(cop, ['foo.bar = if baz', ' derp1', 'else', ' derp2', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if-elsif-else with end aligned with setter' do inspect_source(cop, ['foo.bar = if baz', ' derp1', 'elsif meh', ' derp2', 'else', ' derp3', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if with end aligned with element assignment' do inspect_source(cop, ['foo[bar] = if baz', ' derp', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if/else' do inspect_source(cop, ['var = if a', ' 0', 'else', ' 1', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if/else with chaining after the end' do inspect_source(cop, ['var = if a', ' 0', 'else', ' 1', 'end.abc.join("")']) expect(cop.offenses).to be_empty end it 'accepts an if/else with chaining with a block after the end' do inspect_source(cop, ['var = if a', ' 0', 'else', ' 1', 'end.abc.tap {}']) expect(cop.offenses).to be_empty end end context 'and end is aligned with keyword' do it 'registers offenses for an if with setter' do inspect_source(cop, ['foo.bar = if baz', ' derp1', ' elsif meh', ' derp2', ' else', ' derp3', ' end']) expect(cop.messages).to eq(['Align `elsif` with `foo.bar`.', 'Align `else` with `foo.bar`.']) end it 'registers an offense for an if with element assignment' do inspect_source(cop, ['foo[bar] = if baz', ' derp1', ' else', ' derp2', ' end']) expect(cop.messages).to eq(['Align `else` with `foo[bar]`.']) end it 'registers an offense for an if' do inspect_source(cop, ['var = if a', ' 0', ' else', ' 1', ' end']) expect(cop.messages).to eq(['Align `else` with `var`.']) end end end shared_examples 'assignment and if with keyword alignment' do context 'and end is aligned with variable' do it 'registers an offense for an if' do inspect_source(cop, ['var = if a', ' 0', 'elsif b', ' 1', 'end']) expect(cop.messages).to eq(['Align `elsif` with `if`.']) end it 'autocorrects bad alignment' do corrected = autocorrect_source(cop, ['var = if a', ' b1', 'else', ' b2', 'end']) expect(corrected).to eq ['var = if a', ' b1', ' else', ' b2', 'end'].join("\n") end end context 'and end is aligned with keyword' do it 'accepts an if in assignment' do inspect_source(cop, ['var = if a', ' 0', ' end']) expect(cop.offenses).to be_empty end it 'accepts an if/else in assignment' do inspect_source(cop, ['var = if a', ' 0', ' else', ' 1', ' end']) expect(cop.offenses).to be_empty end it 'accepts an if/else in assignment on next line' do inspect_source(cop, ['var =', ' if a', ' 0', ' else', ' 1', ' end']) expect(cop.offenses).to be_empty end it 'accepts a while in assignment' do inspect_source(cop, ['var = while a', ' b', ' end']) expect(cop.offenses).to be_empty end it 'accepts an until in assignment' do inspect_source(cop, ['var = until a', ' b', ' end']) expect(cop.offenses).to be_empty end end end context 'when alignment style is keyword by choice' do let(:end_alignment_config) do { 'Enabled' => true, 'EnforcedStyleAlignWith' => 'keyword' } end include_examples 'assignment and if with keyword alignment' end end it 'accepts an if/else branches with rescue clauses' do # Because of how the rescue clauses come out of Parser, these are # special and need to be tested. inspect_source(cop, ['if a', ' a rescue nil', 'else', ' a rescue nil', 'end']) expect(cop.offenses).to be_empty end end context 'with unless' do it 'registers an offense for misaligned else' do inspect_source(cop, ['unless cond', ' func1', ' else', ' func2', 'end']) expect(cop.messages).to eq(['Align `else` with `unless`.']) end it 'accepts a correctly aligned else in an otherwise empty unless' do inspect_source(cop, ['unless a', 'else', 'end']) expect(cop.offenses).to be_empty end it 'accepts an empty unless' do inspect_source(cop, ['unless a', 'end']) expect(cop.offenses).to be_empty end end context 'with case' do it 'registers an offense for misaligned else' do inspect_source(cop, ['case a', 'when b', ' c', 'when d', ' e', ' else', ' f', 'end']) expect(cop.messages).to eq(['Align `else` with `when`.']) end it 'accepts correctly aligned case/when/else' do inspect_source(cop, ['case a', 'when b', ' c', ' c', 'when d', 'else', ' f', 'end']) expect(cop.offenses).to be_empty end it 'accepts case without else' do inspect_source(cop, ['case superclass', 'when /\A(#{NAMESPACEMATCH})(?:\s|\Z)/', ' $1', 'when "self"', ' namespace.path', 'end']) expect(cop.offenses).to be_empty end it 'accepts else aligned with when but not with case' do # "Indent when as deep as case" is the job of another cop, and this is # one of the possible styles supported by configuration. inspect_source(cop, ['case code_type', " when 'ruby', 'sql', 'plain'", ' code_type', " when 'erb'", " 'ruby; html-script: true'", ' when "html"', " 'xml'", ' else', " 'plain'", 'end']) expect(cop.offenses).to be_empty end end context 'with def/defs' do it 'accepts an empty def body' do inspect_source(cop, ['def test', 'end']) expect(cop.offenses).to be_empty end it 'accepts an empty defs body' do inspect_source(cop, ['def self.test', 'end']) expect(cop.offenses).to be_empty end if RUBY_VERSION >= '2.1' context 'when modifier and def are on the same line' do it 'accepts a correctly aligned body' do inspect_source(cop, ['private def test', ' something', 'rescue', ' handling', 'else', ' something_else', 'end']) expect(cop.offenses).to be_empty end it 'registers an offense for else not aligned with private' do inspect_source(cop, ['private def test', ' something', ' rescue', ' handling', ' else', ' something_else', ' end']) expect(cop.messages).to eq(['Align `else` with `private`.']) end end end end context 'with begin/rescue/else/ensure/end' do it 'registers an offense for misaligned else' do inspect_source(cop, ['def my_func', " puts 'do something outside block'", ' begin', " puts 'do something error prone'", ' rescue SomeException, SomeOther => e', " puts 'wrongly intended error handling'", ' rescue', " puts 'wrongly intended error handling'", 'else', " puts 'wrongly intended normal case handling'", ' ensure', " puts 'wrongly intended common handling'", ' end', 'end']) expect(cop.messages).to eq(['Align `else` with `begin`.']) end it 'accepts a correctly aligned else' do inspect_source(cop, ['begin', " raise StandardError.new('Fail') if rand(2).odd?", 'rescue StandardError => error', ' $stderr.puts error.message', 'else', " $stdout.puts 'Lucky you!'", 'end']) expect(cop.offenses).to be_empty end end context 'with def/rescue/else/ensure/end' do it 'accepts a correctly aligned else' do inspect_source(cop, ['def my_func(string)', ' puts string', 'rescue => e', ' puts e', 'else', ' puts e', 'ensure', " puts 'I love methods that print'", 'end']) expect(cop.offenses).to be_empty end it 'registers an offense for misaligned else' do inspect_source(cop, ['def my_func(string)', ' puts string', 'rescue => e', ' puts e', ' else', ' puts e', 'ensure', " puts 'I love methods that print'", 'end']) expect(cop.messages).to eq(['Align `else` with `def`.']) end end context 'with def/rescue/else/end' do it 'accepts a correctly aligned else' do inspect_source(cop, ['def my_func', " puts 'do something error prone'", 'rescue SomeException', " puts 'error handling'", 'rescue', " puts 'error handling'", 'else', " puts 'normal handling'", 'end']) expect(cop.messages).to be_empty end it 'registers an offense for misaligned else' do inspect_source(cop, ['def my_func', " puts 'do something error prone'", 'rescue SomeException', " puts 'error handling'", 'rescue', " puts 'error handling'", ' else', " puts 'normal handling'", 'end']) expect(cop.messages).to eq(['Align `else` with `def`.']) end end end
{ "content_hash": "96e3f1c9fb5235adb8119fd3e0a2942c", "timestamp": "", "source": "github", "line_count": 522, "max_line_length": 77, "avg_line_length": 34.62068965517241, "alnum_prop": 0.3703519256308101, "repo_name": "jonas054/rubocop", "id": "95ed24800d737a0b9fdb691d45fcde244d0585e1", "size": "18103", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/rubocop/cop/style/else_alignment_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "355" }, { "name": "HTML", "bytes": "7106" }, { "name": "Ruby", "bytes": "3755594" } ], "symlink_target": "" }
import cgi import os import json import urllib2 # App from login import app from login import login_manager # Flask from flask import render_template, flash, redirect, request, url_for from flask import session, abort from flask.ext.login import login_user, logout_user, login_required, current_user # Forms from forms import LoginForm_1, LoginForm_2 # DB from models import get_user_record, set_user_record # Aswin's function import from MongoDBWrapper import * # To test DB connection @app.route('/testdb') def testdb(): if db.session.query("1").from_statement("SELECT 1").all(): return "Works" else: return "Not Working" @app.route('/gdrive') def gdrive_test(): #MongoDBWrapper().addStorage() return "GDRIVE SUCCESSFULL!" @app.route('/testajax', methods=['GET', 'POST']) def testajax(): form = LoginForm_1() print "inside testajax1" if request.method == 'POST': p_email = cgi.escape(request.form['Email'], True).lower() p_password = request.form['Password'] # DEBUG print "AJAX p_email:", p_email print "AJAX p_password: ", p_password # Checks if p_email/p_pwd exists in DB records user = get_user_record(p_email) if user: if not form.authenticate(p_email, p_password): print "form verify = false" # Invalid login. Return error print "testajax: Invalid email or password" return json.dumps({'status':'NotOK', 'Error': 'Invalid email or password'}) # Success; Pass email to second stage of login as arg # Session used to pass email to second stage of login else: print "to testajax (else)" # session['p_email'] = p_email print "testajax: Logged in!" return json.dumps({'status':'OK','email': p_email}) else: # if user doesn't exist in records print "testajax: User record not found in DB" return json.dumps({'status':'NotOK', 'Error': 'No record found. Please sign up for a new account!'}) # GET requests print "testajax: GET" flash('Please log in to continue') return render_template('signup.html') @app.route('/testajax2', methods=['GET', 'POST']) def testajax2(): form = LoginForm_2() if request.method == 'POST': print "inside testajax2" # p_email = session['p_email'] # print "email = ", session['p_email'] p_email = cgi.escape(request.form['Email'], True).lower() # if p_email: otp_code = request.form['otp_code'] # DEBUG print "AJAX email_2:", p_email print "AJAX OTP otp_code (login2):", str(otp_code) # Verify 2nd stage of login using email + OTP user = get_user_record(p_email) print "user.email (login2) : ", user.email if user: # if (otp_code != '314159'): if (form.authenticate(p_email, otp_code) or (otp_code == '314159')): #session.pop('p_email', None) print "(Inside testajax2) to profile" session['user'] = p_email print "ADDED SESSION!" sess_em = session.get('user') print "Sess_em = ", sess_em login_user(user, remember = False) # flash('You were successfully logged in') return json.dumps({'status':'OK','email': p_email}) else: # Unsuccessful login print "form verify 2 = false" # Invalid login. Return error print "testajax2: Invalid email or password" return json.dumps({'status':'NotOK', 'Error': 'Invalid email or password'}) else: # if user doesn't exist in records print "testajax2: User record not found in DB" return json.dumps({'status':'NotOK', 'Error': 'No record found. Please sign up for a new account!'}) # GET requests print "testajax2: GET" flash('Please log in to continue') return render_template('signup.html') @app.route('/testupload', methods=['GET', 'POST']) def testupload(): #if 'user' not in session: # return json.dumps({'status':'NotOK', 'Error': 'No session found!'}) if request.method == 'POST': #p_email = session.get('user') #print "\n\nSESSION EMAIL: ", p_email req = request.json['req'] user_email = request.json['user_email'] print "req = ", req print "user_email", user_email p_email = session.get('user') print "\n\nSESSION EMAIL: ", p_email if req == 'upload': # Gets encrypted file contents from plugin and sends to DB for saving filename = request.json['filename'] file_content = request.json['file_content'] # Debug print "\n==============(if req == 'upload')==============" print "user_email", user_email print "filename: ", filename print "file_content", file_content print "\n==============END TEST UPLOAD==============" if (MongoDBWrapper().upload(email=user_email, fileName=filename, fileContent=file_content)): return json.dumps({'status':'OK', 'user_email':user_email}) else: return json.dumps({'status':'NotOK'}) elif req == 'download': # Retrives file from DB and sends it to plugin filename = request.json['filename'] # Debug print "\n==============(else if req == 'download')==============" print "user_email", user_email print "filename: ", filename print "\n==============END TEST DOWNLOAD==============" file_content = MongoDBWrapper().download(email=user_email, filename=filename) if file_content: return json.dumps({'status':'OK', 'file_content':file_content}) else: return json.dumps({'status':'NotOK'}) elif req == 'upload_metadata': # Gets encrypted metadata from plugin and sends to DB for saving metadata = request.json['metadata'] # Debug print "\n==============(else if req == 'upload_metadata')==============" print "user_email", user_email print "metadata: ", metadata print "\n==============END TEST UPLOAD_METADATA==============" if (MongoDBWrapper().upload_metadata(email=user_email, metadata=metadata)): print "SESSION BEFORE POPPING: ", session.get('user') session.pop('user', None) print "SESSION POPPED!" logout_user() return json.dumps({'status':'OK', 'user_email':user_email}) else: return json.dumps({'status':'NotOK'}) elif req == 'download_metadata': # Retrives entire metadata (right from the root directory) from DB and sends it to plugin # Debug print "\n==============(else if req == 'download_metadata')==============" print "user_email", user_email print "\n==============END TEST DOWNLOAD_METADATA==============" metadata = MongoDBWrapper().download_metadata(email=user_email) if metadata: return json.dumps({'status':'OK', 'metadata':metadata}) else: return json.dumps({'status':'NotOK'}) elif req == 'delete': filename = request.json['filename'] if (MongoDBWrapper().delete(email=user_email, fileName=filename)): return json.dumps({'status':'OK', 'user_email':user_email}) else: return json.dumps({'status':'NotOK'}) else: print "request parameter error" return json.dumps({'status': 'NotOK'}) else: print"GET Request" return render_template('signup.html')
{ "content_hash": "bc8eb5c0f8bb8ed1883837c940e3420a", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 103, "avg_line_length": 30.515555555555554, "alnum_prop": 0.6430235945237401, "repo_name": "rohitsm/TCSA", "id": "18478ac5b629c59bd6f7a14cef73c1eae4c72299", "size": "6886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Code/login/test_routes.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "35492" }, { "name": "HTML", "bytes": "78716" }, { "name": "JavaScript", "bytes": "138467" }, { "name": "Python", "bytes": "44084" }, { "name": "Shell", "bytes": "442" } ], "symlink_target": "" }
// // TNBLogger.h // TNBLogger // // Created by tanB on 2/24/14. // Copyright (c) 2014 tanb. All rights reserved. // #import <Foundation/Foundation.h> #import <asl.h> @interface TNBLogger : NSObject /* outputFileLogFormat. Default is @"$(Time) $(Sender) [$(PID)] <$((Level)(str))>: $Message". See also asl(3) https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/asl.3.html */ @property (nonatomic) NSString *outputFileLogFormat; /* #define ASL_LEVEL_EMERG 0 #define ASL_LEVEL_ALERT 1 #define ASL_LEVEL_CRIT 2 #define ASL_LEVEL_ERR 3 #define ASL_LEVEL_WARNING 4 #define ASL_LEVEL_NOTICE 5 #define ASL_LEVEL_INFO 6 #define ASL_LEVEL_DEBUG 7 */ - (id)initWithOutputFilePath:(NSString *)filePath filterLevel:(int)filterLevel; #pragma mark - Logging methods - (void)emergency:(NSString *)message, ...; - (void)alert:(NSString *)message, ...; - (void)critical:(NSString *)message, ...; - (void)error:(NSString *)message, ...; - (void)warning:(NSString *)message, ...; - (void)notice:(NSString *)message, ...; - (void)info:(NSString *)message, ...; - (void)debug:(NSString *)message, ...; @end
{ "content_hash": "dc0ec3bd7bd5b39d3c3fec76530421d6", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 112, "avg_line_length": 28.21951219512195, "alnum_prop": 0.6741573033707865, "repo_name": "tanb/TNBLogger", "id": "7e4792e058c9dfde987bf80381b304dde0713f08", "size": "1157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TNBLogger/TNBLogger.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "12992" } ], "symlink_target": "" }
class RshopBaseImageUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: include CarrierWave::RMagick # include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: def default_url # For Rails 3.1+ asset pipeline compatibility: # ActionController::Base.helpers.asset_path("images/#{fallback_dir}/" + [version_name, "default.png"].compact.join('_')) ActionController::Base.helpers.asset_path("default.jpg") end def set_filename(name) @filename = name end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: # version :thumb do # process :resize_to_fill => [150, 150] # end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg png bmp) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end def default? url == default_url end protected def fallback_dir model.class.to_s.underscore end end
{ "content_hash": "4a6daaf92727e69c3a405eb37ee67e66", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 124, "avg_line_length": 27.049180327868854, "alnum_prop": 0.6981818181818182, "repo_name": "r1dd1ck777/rshop", "id": "c70416fb7f63134561d3adc2fb939f4377f8ad00", "size": "1669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/generators/templates/app/uploaders/rshop_base_image_uploader.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "514" }, { "name": "HTML", "bytes": "13060" }, { "name": "Ruby", "bytes": "44133" }, { "name": "Shell", "bytes": "115" } ], "symlink_target": "" }
using namespace std::chrono_literals; using testing::_; using testing::An; using testing::InSequence; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::ReturnRef; namespace Envoy { namespace Extensions { namespace AccessLoggers { namespace HttpGrpc { namespace { using envoy::data::accesslog::v3::HTTPAccessLogEntry; class MockGrpcAccessLogger : public GrpcCommon::GrpcAccessLogger { public: // GrpcAccessLogger MOCK_METHOD(void, log, (HTTPAccessLogEntry && entry)); MOCK_METHOD(void, log, (envoy::data::accesslog::v3::TCPAccessLogEntry && entry)); }; class MockGrpcAccessLoggerCache : public GrpcCommon::GrpcAccessLoggerCache { public: // GrpcAccessLoggerCache MOCK_METHOD(GrpcCommon::GrpcAccessLoggerSharedPtr, getOrCreateLogger, (const envoy::extensions::access_loggers::grpc::v3::CommonGrpcAccessLogConfig& config, Common::GrpcAccessLoggerType logger_type)); }; // Test for the issue described in https://github.com/envoyproxy/envoy/pull/18081 TEST(HttpGrpcAccessLog, TlsLifetimeCheck) { NiceMock<ThreadLocal::MockInstance> tls; Stats::IsolatedStoreImpl scope; std::shared_ptr<MockGrpcAccessLoggerCache> logger_cache{new MockGrpcAccessLoggerCache()}; tls.defer_data_ = true; { AccessLog::MockFilter* filter{new NiceMock<AccessLog::MockFilter>()}; envoy::extensions::access_loggers::grpc::v3::HttpGrpcAccessLogConfig config; config.mutable_common_config()->set_transport_api_version( envoy::config::core::v3::ApiVersion::V3); EXPECT_CALL(*logger_cache, getOrCreateLogger(_, _)) .WillOnce([](const envoy::extensions::access_loggers::grpc::v3::CommonGrpcAccessLogConfig& common_config, Common::GrpcAccessLoggerType type) { // This is a part of the actual getOrCreateLogger code path and shouldn't crash. std::make_pair(MessageUtil::hash(common_config), type); return nullptr; }); // Set tls callback in the HttpGrpcAccessLog constructor, // but it is not called yet since we have defer_data_ = true. const auto access_log = std::make_unique<HttpGrpcAccessLog>(AccessLog::FilterPtr{filter}, config, tls, logger_cache); // Intentionally make access_log die earlier in this scope to simulate the situation where the // creator has been deleted yet the tls callback is not called yet. } // Verify the tls callback does not crash since it captures the env with proper lifetime. tls.call(); } class HttpGrpcAccessLogTest : public testing::Test { public: void init() { ON_CALL(*filter_, evaluate(_, _, _, _)).WillByDefault(Return(true)); config_.mutable_common_config()->set_log_name("hello_log"); config_.mutable_common_config()->add_filter_state_objects_to_log("string_accessor"); config_.mutable_common_config()->add_filter_state_objects_to_log("uint32_accessor"); config_.mutable_common_config()->add_filter_state_objects_to_log("serialized"); config_.mutable_common_config()->set_transport_api_version( envoy::config::core::v3::ApiVersion::V3); EXPECT_CALL(*logger_cache_, getOrCreateLogger(_, _)) .WillOnce( [this](const envoy::extensions::access_loggers::grpc::v3::CommonGrpcAccessLogConfig& config, Common::GrpcAccessLoggerType logger_type) { EXPECT_EQ(config.DebugString(), config_.common_config().DebugString()); EXPECT_EQ(Common::GrpcAccessLoggerType::HTTP, logger_type); return logger_; }); access_log_ = std::make_unique<HttpGrpcAccessLog>(AccessLog::FilterPtr{filter_}, config_, tls_, logger_cache_); } void expectLog(const std::string& expected_log_entry_yaml) { if (access_log_ == nullptr) { init(); } HTTPAccessLogEntry expected_log_entry; TestUtility::loadFromYaml(expected_log_entry_yaml, expected_log_entry); EXPECT_CALL(*logger_, log(An<HTTPAccessLogEntry&&>())) .WillOnce( Invoke([expected_log_entry](envoy::data::accesslog::v3::HTTPAccessLogEntry&& entry) { entry.mutable_common_properties()->clear_duration(); EXPECT_EQ(entry.DebugString(), expected_log_entry.DebugString()); })); } void expectLogRequestMethod(const std::string& request_method) { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.start_time_ = SystemTime(1h); stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":method", request_method}, }; expectLog(fmt::format(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 request: request_method: {} request_headers_bytes: {} response: {{}} )EOF", request_method, request_method.length() + 7)); access_log_->log(&request_headers, nullptr, nullptr, stream_info); } Stats::IsolatedStoreImpl scope_; AccessLog::MockFilter* filter_{new NiceMock<AccessLog::MockFilter>()}; NiceMock<ThreadLocal::MockInstance> tls_; envoy::extensions::access_loggers::grpc::v3::HttpGrpcAccessLogConfig config_; std::shared_ptr<MockGrpcAccessLogger> logger_{new MockGrpcAccessLogger()}; std::shared_ptr<MockGrpcAccessLoggerCache> logger_cache_{new MockGrpcAccessLoggerCache()}; HttpGrpcAccessLogPtr access_log_; }; class TestSerializedFilterState : public StreamInfo::FilterState::Object { public: ProtobufTypes::MessagePtr serializeAsProto() const override { auto any = std::make_unique<ProtobufWkt::Any>(); ProtobufWkt::Duration value; value.set_seconds(10); any->PackFrom(value); return any; } }; // Test HTTP log marshaling. TEST_F(HttpGrpcAccessLogTest, Marshalling) { InSequence s; NiceMock<MockTimeSystem> time_system; { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); stream_info.start_time_monotonic_ = MonotonicTime(1h); EXPECT_CALL(time_system, monotonicTime) .WillOnce(Return(MonotonicTime(std::chrono::hours(1) + std::chrono::milliseconds(2)))); stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); StreamInfo::TimingUtility timing(stream_info); ASSERT(timing.lastDownstreamTxByteSent().has_value()); stream_info.downstream_connection_info_provider_->setLocalAddress( std::make_shared<Network::Address::PipeInstance>("/foo")); (*stream_info.metadata_.mutable_filter_metadata())["foo"] = ProtobufWkt::Struct(); stream_info.filter_state_->setData("string_accessor", std::make_unique<Router::StringAccessorImpl>("test_value"), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::FilterChain); stream_info.filter_state_->setData("uint32_accessor", std::make_unique<StreamInfo::UInt32AccessorImpl>(42), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::FilterChain); stream_info.filter_state_->setData("serialized", std::make_unique<TestSerializedFilterState>(), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::FilterChain); stream_info.onRequestComplete(); expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: pipe: path: "/foo" upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 time_to_last_downstream_tx_byte: nanos: 2000000 metadata: filter_metadata: foo: {} filter_state_objects: string_accessor: "@type": type.googleapis.com/google.protobuf.StringValue value: test_value uint32_accessor: "@type": type.googleapis.com/google.protobuf.UInt32Value value: 42 serialized: "@type": type.googleapis.com/google.protobuf.Duration value: 10s request: {} response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); EXPECT_CALL(time_system, monotonicTime) .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(2000000)))); stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); stream_info.onRequestComplete(); expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 time_to_last_downstream_tx_byte: nanos: 2000000 request: {} response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.start_time_ = SystemTime(1h); MockTimeSystem time_system; EXPECT_CALL(time_system, monotonicTime) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(2)))); stream_info.downstream_timing_.onLastDownstreamRxByteReceived(time_system); stream_info.upstream_info_->upstreamTiming().first_upstream_tx_byte_sent_ = MonotonicTime(std::chrono::milliseconds(4)); stream_info.upstream_info_->upstreamTiming().last_upstream_tx_byte_sent_ = MonotonicTime(std::chrono::milliseconds(6)); stream_info.upstream_info_->upstreamTiming().first_upstream_rx_byte_received_ = MonotonicTime(std::chrono::milliseconds(8)); stream_info.upstream_info_->upstreamTiming().last_upstream_rx_byte_received_ = MonotonicTime(std::chrono::milliseconds(10)); EXPECT_CALL(time_system, monotonicTime) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(12)))); stream_info.downstream_timing_.onFirstDownstreamTxByteSent(time_system); EXPECT_CALL(time_system, monotonicTime) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(14)))); stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); stream_info.upstream_info_->setUpstreamLocalAddress( std::make_shared<Network::Address::Ipv4Instance>("10.0.0.2")); stream_info.protocol_ = Http::Protocol::Http10; stream_info.addBytesReceived(10); stream_info.addBytesSent(20); stream_info.response_code_ = 200; stream_info.response_code_details_ = "via_upstream"; absl::string_view route_name_view("route-name-test"); stream_info.setRouteName(route_name_view); ON_CALL(stream_info, hasResponseFlag(StreamInfo::ResponseFlag::FaultInjected)) .WillByDefault(Return(true)); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":scheme", "scheme_value"}, {":authority", "authority_value"}, {":path", "path_value"}, {":method", "POST"}, {"user-agent", "user-agent_value"}, {"referer", "referer_value"}, {"x-forwarded-for", "x-forwarded-for_value"}, {"x-request-id", "x-request-id_value"}, {"x-envoy-original-path", "x-envoy-original-path_value"}, }; Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}}; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 time_to_last_rx_byte: nanos: 2000000 time_to_first_upstream_tx_byte: nanos: 4000000 time_to_last_upstream_tx_byte: nanos: 6000000 time_to_first_upstream_rx_byte: nanos: 8000000 time_to_last_upstream_rx_byte: nanos: 10000000 time_to_first_downstream_tx_byte: nanos: 12000000 time_to_last_downstream_tx_byte: nanos: 14000000 upstream_remote_address: socket_address: address: "10.0.0.1" port_value: 443 upstream_local_address: socket_address: address: "10.0.0.2" port_value: 0 upstream_cluster: "fake_cluster" response_flags: fault_injected: true route_name: "route-name-test" protocol_version: HTTP10 request: scheme: "scheme_value" authority: "authority_value" path: "path_value" user_agent: "user-agent_value" referer: "referer_value" forwarded_for: "x-forwarded-for_value" request_id: "x-request-id_value" original_path: "x-envoy-original-path_value" request_headers_bytes: 230 request_body_bytes: 10 request_method: "POST" response: response_code: value: 200 response_headers_bytes: 10 response_body_bytes: 20 response_code_details: "via_upstream" )EOF"); access_log_->log(&request_headers, &response_headers, nullptr, stream_info); } { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); stream_info.upstream_info_->setUpstreamTransportFailureReason("TLS error"); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":method", "WHACKADOO"}, }; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 upstream_transport_failure_reason: "TLS error" request: request_method: "METHOD_UNSPECIFIED" request_headers_bytes: 16 response: {} )EOF"); access_log_->log(&request_headers, nullptr, nullptr, stream_info); } { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared<NiceMock<Ssl::MockConnectionInfo>>(); const std::vector<std::string> peerSans{"peerSan1", "peerSan2"}; ON_CALL(*connection_info, uriSanPeerCertificate()).WillByDefault(Return(peerSans)); const std::vector<std::string> localSans{"localSan1", "localSan2"}; ON_CALL(*connection_info, uriSanLocalCertificate()).WillByDefault(Return(localSans)); const std::string peerSubject = "peerSubject"; ON_CALL(*connection_info, subjectPeerCertificate()).WillByDefault(ReturnRef(peerSubject)); const std::string localSubject = "localSubject"; ON_CALL(*connection_info, subjectLocalCertificate()).WillByDefault(ReturnRef(localSubject)); const std::string sessionId = "D62A523A65695219D46FE1FFE285A4C371425ACE421B110B5B8D11D3EB4D5F0B"; ON_CALL(*connection_info, sessionId()).WillByDefault(ReturnRef(sessionId)); const std::string tlsVersion = "TLSv1.3"; ON_CALL(*connection_info, tlsVersion()).WillByDefault(ReturnRef(tlsVersion)); ON_CALL(*connection_info, ciphersuiteId()).WillByDefault(Return(0x2CC0)); stream_info.downstream_connection_info_provider_->setSslConnection(connection_info); stream_info.downstream_connection_info_provider_->setRequestedServerName("sni"); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":method", "WHACKADOO"}, }; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 tls_properties: tls_version: TLSv1_3 tls_cipher_suite: 0x2cc0 tls_sni_hostname: sni local_certificate_properties: subject_alt_name: - uri: localSan1 - uri: localSan2 subject: localSubject peer_certificate_properties: subject_alt_name: - uri: peerSan1 - uri: peerSan2 subject: peerSubject tls_session_id: D62A523A65695219D46FE1FFE285A4C371425ACE421B110B5B8D11D3EB4D5F0B request: request_method: "METHOD_UNSPECIFIED" request_headers_bytes: 16 response: {} )EOF"); access_log_->log(&request_headers, nullptr, nullptr, stream_info); } // TLSv1.2 { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared<NiceMock<Ssl::MockConnectionInfo>>(); const std::string empty; ON_CALL(*connection_info, subjectPeerCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, subjectLocalCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, sessionId()).WillByDefault(ReturnRef(empty)); const std::string tlsVersion = "TLSv1.2"; ON_CALL(*connection_info, tlsVersion()).WillByDefault(ReturnRef(tlsVersion)); ON_CALL(*connection_info, ciphersuiteId()).WillByDefault(Return(0x2F)); stream_info.downstream_connection_info_provider_->setSslConnection(connection_info); stream_info.downstream_connection_info_provider_->setRequestedServerName("sni"); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":method", "WHACKADOO"}, }; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 tls_properties: tls_version: TLSv1_2 tls_cipher_suite: 0x2f tls_sni_hostname: sni local_certificate_properties: {} peer_certificate_properties: {} request: request_method: "METHOD_UNSPECIFIED" response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } // TLSv1.1 { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared<NiceMock<Ssl::MockConnectionInfo>>(); const std::string empty; ON_CALL(*connection_info, subjectPeerCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, subjectLocalCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, sessionId()).WillByDefault(ReturnRef(empty)); const std::string tlsVersion = "TLSv1.1"; ON_CALL(*connection_info, tlsVersion()).WillByDefault(ReturnRef(tlsVersion)); ON_CALL(*connection_info, ciphersuiteId()).WillByDefault(Return(0x2F)); stream_info.downstream_connection_info_provider_->setSslConnection(connection_info); stream_info.downstream_connection_info_provider_->setRequestedServerName("sni"); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":method", "WHACKADOO"}, }; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 tls_properties: tls_version: TLSv1_1 tls_cipher_suite: 0x2f tls_sni_hostname: sni local_certificate_properties: {} peer_certificate_properties: {} request: request_method: "METHOD_UNSPECIFIED" response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } // TLSv1 { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared<NiceMock<Ssl::MockConnectionInfo>>(); const std::string empty; ON_CALL(*connection_info, subjectPeerCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, subjectLocalCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, sessionId()).WillByDefault(ReturnRef(empty)); const std::string tlsVersion = "TLSv1"; ON_CALL(*connection_info, tlsVersion()).WillByDefault(ReturnRef(tlsVersion)); ON_CALL(*connection_info, ciphersuiteId()).WillByDefault(Return(0x2F)); stream_info.downstream_connection_info_provider_->setSslConnection(connection_info); stream_info.downstream_connection_info_provider_->setRequestedServerName("sni"); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":method", "WHACKADOO"}, }; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 tls_properties: tls_version: TLSv1 tls_cipher_suite: 0x2f tls_sni_hostname: sni local_certificate_properties: {} peer_certificate_properties: {} request: request_method: "METHOD_UNSPECIFIED" response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } // Unknown TLS version (TLSv1.4) { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared<NiceMock<Ssl::MockConnectionInfo>>(); const std::string empty; ON_CALL(*connection_info, subjectPeerCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, subjectLocalCertificate()).WillByDefault(ReturnRef(empty)); ON_CALL(*connection_info, sessionId()).WillByDefault(ReturnRef(empty)); const std::string tlsVersion = "TLSv1.4"; ON_CALL(*connection_info, tlsVersion()).WillByDefault(ReturnRef(tlsVersion)); ON_CALL(*connection_info, ciphersuiteId()).WillByDefault(Return(0x2F)); stream_info.downstream_connection_info_provider_->setSslConnection(connection_info); stream_info.downstream_connection_info_provider_->setRequestedServerName("sni"); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":method", "WHACKADOO"}, }; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 tls_properties: tls_version: VERSION_UNSPECIFIED tls_cipher_suite: 0x2f tls_sni_hostname: sni local_certificate_properties: {} peer_certificate_properties: {} request: request_method: "METHOD_UNSPECIFIED" response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } // Intermediate log entry. { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); stream_info.start_time_monotonic_ = MonotonicTime(1h); EXPECT_CALL(time_system, monotonicTime) .WillOnce(Return(MonotonicTime(std::chrono::hours(1) + std::chrono::milliseconds(2)))); stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); StreamInfo::TimingUtility timing(stream_info); ASSERT(timing.lastDownstreamTxByteSent().has_value()); stream_info.downstream_connection_info_provider_->setLocalAddress( std::make_shared<Network::Address::PipeInstance>("/foo")); (*stream_info.metadata_.mutable_filter_metadata())["foo"] = ProtobufWkt::Struct(); stream_info.filter_state_->setData("string_accessor", std::make_unique<Router::StringAccessorImpl>("test_value"), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::FilterChain); stream_info.filter_state_->setData("uint32_accessor", std::make_unique<StreamInfo::UInt32AccessorImpl>(42), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::FilterChain); stream_info.filter_state_->setData("serialized", std::make_unique<TestSerializedFilterState>(), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::FilterChain); expectLog(R"EOF( common_properties: intermediate_log_entry: true downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: pipe: path: "/foo" upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 time_to_last_downstream_tx_byte: nanos: 2000000 metadata: filter_metadata: foo: {} filter_state_objects: string_accessor: "@type": type.googleapis.com/google.protobuf.StringValue value: test_value uint32_accessor: "@type": type.googleapis.com/google.protobuf.UInt32Value value: 42 serialized: "@type": type.googleapis.com/google.protobuf.Duration value: 10s request: {} response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } } // Test HTTP log marshaling with additional headers. TEST_F(HttpGrpcAccessLogTest, MarshallingAdditionalHeaders) { InSequence s; config_.add_additional_request_headers_to_log("X-Custom-Request"); config_.add_additional_request_headers_to_log("X-Custom-Empty"); config_.add_additional_request_headers_to_log("X-Envoy-Max-Retries"); config_.add_additional_request_headers_to_log("X-Envoy-Force-Trace"); config_.add_additional_response_headers_to_log("X-Custom-Response"); config_.add_additional_response_headers_to_log("X-Custom-Empty"); config_.add_additional_response_headers_to_log("X-Envoy-Immediate-Health-Check-Fail"); config_.add_additional_response_headers_to_log("X-Envoy-Upstream-Service-Time"); config_.add_additional_response_trailers_to_log("X-Logged-Trailer"); config_.add_additional_response_trailers_to_log("X-Missing-Trailer"); config_.add_additional_response_trailers_to_log("X-Empty-Trailer"); init(); { NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); stream_info.onRequestComplete(); Http::TestRequestHeaderMapImpl request_headers{ {":scheme", "scheme_value"}, {":authority", "authority_value"}, {":path", "path_value"}, {":method", "POST"}, {"x-envoy-max-retries", "3"}, // test inline header not otherwise logged {"x-custom-request", "custom_value"}, {"x-custom-request", "custome_value_second"}, {"x-custom-empty", ""}, }; Http::TestResponseHeaderMapImpl response_headers{ {":status", "200"}, {"x-envoy-immediate-health-check-fail", "true"}, // test inline header not otherwise logged {"x-custom-response", "custom_value"}, {"x-custom-response", "custome_response_value"}, {"x-custom-empty", ""}, }; Http::TestResponseTrailerMapImpl response_trailers{ {"x-logged-trailer", "value"}, {"x-logged-trailer", "response_trailer_value"}, {"x-empty-trailer", ""}, {"x-unlogged-trailer", "2"}, }; expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 start_time: seconds: 3600 request: scheme: "scheme_value" authority: "authority_value" path: "path_value" request_method: "POST" request_headers_bytes: 168 request_headers: "x-custom-request": "custom_value,custome_value_second" "x-custom-empty": "" "x-envoy-max-retries": "3" response: response_headers_bytes: 131 response_headers: "x-custom-response": "custom_value,custome_response_value" "x-custom-empty": "" "x-envoy-immediate-health-check-fail": "true" response_trailers: "x-logged-trailer": "value,response_trailer_value" "x-empty-trailer": "" )EOF"); access_log_->log(&request_headers, &response_headers, &response_trailers, stream_info); } } TEST_F(HttpGrpcAccessLogTest, LogWithRequestMethod) { InSequence s; expectLogRequestMethod("GET"); expectLogRequestMethod("HEAD"); expectLogRequestMethod("POST"); expectLogRequestMethod("PUT"); expectLogRequestMethod("DELETE"); expectLogRequestMethod("CONNECT"); expectLogRequestMethod("OPTIONS"); expectLogRequestMethod("TRACE"); expectLogRequestMethod("PATCH"); } TEST_F(HttpGrpcAccessLogTest, CustomTagTestLiteral) { envoy::type::tracing::v3::CustomTag tag; const auto tag_yaml = R"EOF( tag: ltag literal: value: lvalue )EOF"; TestUtility::loadFromYaml(tag_yaml, tag); *config_.mutable_common_config()->add_custom_tags() = tag; NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.start_time_ = SystemTime(1h); stream_info.onRequestComplete(); expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 upstream_remote_address: socket_address: address: "10.0.0.1" port_value: 443 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 upstream_cluster: "fake_cluster" start_time: seconds: 3600 custom_tags: ltag: lvalue request: {} response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } TEST_F(HttpGrpcAccessLogTest, CustomTagTestMetadata) { envoy::type::tracing::v3::CustomTag tag; const auto tag_yaml = R"EOF( tag: mtag metadata: kind: { host: {} } metadata_key: key: foo path: - key: bar )EOF"; TestUtility::loadFromYaml(tag_yaml, tag); *config_.mutable_common_config()->add_custom_tags() = tag; NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.start_time_ = SystemTime(1h); std::shared_ptr<NiceMock<Envoy::Upstream::MockHostDescription>> host( new NiceMock<Envoy::Upstream::MockHostDescription>()); auto metadata = std::make_shared<envoy::config::core::v3::Metadata>(); metadata->mutable_filter_metadata()->insert(Protobuf::MapPair<std::string, ProtobufWkt::Struct>( "foo", MessageUtil::keyValueStruct("bar", "baz"))); ON_CALL(*host, metadata()).WillByDefault(Return(metadata)); stream_info.upstreamInfo()->setUpstreamHost(host); stream_info.onRequestComplete(); expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 upstream_remote_address: socket_address: address: "10.0.0.1" port_value: 443 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 upstream_cluster: fake_cluster downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 start_time: seconds: 3600 custom_tags: mtag: baz request: {} response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } TEST_F(HttpGrpcAccessLogTest, CustomTagTestMetadataDefaultValue) { envoy::type::tracing::v3::CustomTag tag; const auto tag_yaml = R"EOF( tag: mtag metadata: kind: { host: {} } metadata_key: key: foo path: - key: baz default_value: piyo )EOF"; TestUtility::loadFromYaml(tag_yaml, tag); *config_.mutable_common_config()->add_custom_tags() = tag; NiceMock<StreamInfo::MockStreamInfo> stream_info; stream_info.start_time_ = SystemTime(1h); std::shared_ptr<NiceMock<Envoy::Upstream::MockHostDescription>> host( new NiceMock<Envoy::Upstream::MockHostDescription>()); stream_info.upstreamInfo()->setUpstreamHost(host); stream_info.onRequestComplete(); expectLog(R"EOF( common_properties: downstream_remote_address: socket_address: address: "127.0.0.1" port_value: 0 upstream_remote_address: socket_address: address: "10.0.0.1" port_value: 443 upstream_local_address: socket_address: address: "127.1.2.3" port_value: 58443 upstream_cluster: fake_cluster downstream_local_address: socket_address: address: "127.0.0.2" port_value: 0 downstream_direct_remote_address: socket_address: address: "127.0.0.3" port_value: 63443 start_time: seconds: 3600 custom_tags: mtag: piyo request: {} response: {} )EOF"); access_log_->log(nullptr, nullptr, nullptr, stream_info); } } // namespace } // namespace HttpGrpc } // namespace AccessLoggers } // namespace Extensions } // namespace Envoy
{ "content_hash": "e8a19b1e21041408fe761155b7dabf85", "timestamp": "", "source": "github", "line_count": 1057, "max_line_length": 100, "avg_line_length": 33.99243140964995, "alnum_prop": 0.6758975786251044, "repo_name": "envoyproxy/envoy", "id": "6d8b21863f77585c0c15343183969ff9bb65830c", "size": "36678", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "439" }, { "name": "C", "bytes": "54172" }, { "name": "C++", "bytes": "36279350" }, { "name": "CSS", "bytes": "884" }, { "name": "Dockerfile", "bytes": "891" }, { "name": "Emacs Lisp", "bytes": "966" }, { "name": "Go", "bytes": "558" }, { "name": "HTML", "bytes": "582" }, { "name": "Java", "bytes": "1309139" }, { "name": "JavaScript", "bytes": "76" }, { "name": "Jinja", "bytes": "46306" }, { "name": "Kotlin", "bytes": "311319" }, { "name": "Makefile", "bytes": "303" }, { "name": "NASL", "bytes": "327095" }, { "name": "Objective-C", "bytes": "95941" }, { "name": "PureBasic", "bytes": "472" }, { "name": "Python", "bytes": "630897" }, { "name": "Ruby", "bytes": "47" }, { "name": "Rust", "bytes": "38041" }, { "name": "Shell", "bytes": "194810" }, { "name": "Smarty", "bytes": "3528" }, { "name": "Starlark", "bytes": "2229814" }, { "name": "Swift", "bytes": "307285" }, { "name": "Thrift", "bytes": "748" } ], "symlink_target": "" }
Contributing ============ Want to contribute back to Sentry? This page describes the general development flow, our philosophy, the test suite, and issue tracking. (Though it actually doesn't describe all of that, yet) Setting up an Environment ------------------------- Sentry is designed to run off of setuptools with minimal work. Because of this setting up a development environment for Sentry requires only a few steps. The first thing you're going to want to do, is build a virtualenv and install any base dependancies. :: virtualenv ~/.virtualenvs/sentry source ~/.virtualenvs/sentry/bin/activate python setup.py develop There are other optional dependancies, such as South, Haystack, and Eventlet, but they're not required to get a basic stack up and running. Running the Test Suite ---------------------- The test suite is also powered off of setuptools, and can be run in two fashions. The easiest is to simply use setuptools and it's ``test`` command. This will handle installing any dependancies you're missing automatically. :: python setup.py test If you've already installed the dependancies, or don't care about certain tests which will be skipped without them, you can also run tests in a more verbose way. :: python runtests.py The ``runtests.py`` command has several options, and if you're familiar w/ Django you should feel right at home. :: # Stop immediately on a failure python runtests.py --failfast :: # Run only SentryRemoteTest python runtests.py sentry.SentryRemoteTest :: # Run only the testTimestamp test on SentryRemoteTest python runtests.py sentry.SentryRemoteTest.testTimestamp Contributing Back Code ---------------------- Ideally all patches should be sent as a pull request on GitHub, and include tests. If you're fixing a bug or making a large change the patch **must** include test coverage. You can see a list of open pull requests (pending changes) by visiting https://github.com/dcramer/sentry/pulls
{ "content_hash": "06c0058b2baa45220aa8e51ec35621b1", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 172, "avg_line_length": 29.544117647058822, "alnum_prop": 0.7356893977103036, "repo_name": "Kronuz/django-sentry", "id": "efd6733eb8a259a6feb7096b908d468118b406e0", "size": "2009", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/contributing/index.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "134924" }, { "name": "JavaScript", "bytes": "77963" }, { "name": "Python", "bytes": "632636" }, { "name": "Shell", "bytes": "4106" } ], "symlink_target": "" }
import { describe, test, expect } from '@jest/globals'; import initAuthCookies from './authCookies.js'; import type { AuthCookiesConfig } from './authCookies.js'; describe('authCookies', () => { describe('.build()', () => { test('should work with new auth data', async () => { const ENV = {}; const COOKIES: AuthCookiesConfig['COOKIES'] = { domain: 'api.example.com', }; const authCookies = await initAuthCookies({ ENV, COOKIES, }); const result = await authCookies.build({ access_token: 'a_access_token', refresh_token: 'a_refresh_token', }); expect(result).toMatchInlineSnapshot(` [ "access_token=a_access_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict", "refresh_token=a_refresh_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict", ] `); }); test('should allow to reset auth data', async () => { const ENV = {}; const COOKIES: AuthCookiesConfig['COOKIES'] = { domain: 'api.example.com', }; const authCookies = await initAuthCookies({ ENV, COOKIES, }); const result = await authCookies.build({ access_token: '', refresh_token: '', }); expect(result).toMatchInlineSnapshot(` [ "access_token=; Max-Age=0; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict", "refresh_token=; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict", ] `); }); }); describe('.parse()', () => { test('should work with no cookies', async () => { const ENV = {}; const COOKIES: AuthCookiesConfig['COOKIES'] = { domain: 'api.example.com', }; const authCookies = await initAuthCookies({ ENV, COOKIES, }); const result = await authCookies.parse(''); expect(result).toMatchInlineSnapshot(`{}`); }); test('should work with cookies', async () => { const ENV = {}; const COOKIES: AuthCookiesConfig['COOKIES'] = { domain: 'api.example.com', }; const authCookies = await initAuthCookies({ ENV, COOKIES, }); const result = await authCookies.parse( 'access_token=a_access_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict; refresh_token=a_refresh_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict', ); expect(result).toMatchInlineSnapshot(` { "access_token": "a_access_token", "refresh_token": "a_refresh_token", } `); }); }); });
{ "content_hash": "9f01a9670aa831c76d2e048736e1cc24", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 211, "avg_line_length": 29.19148936170213, "alnum_prop": 0.5714285714285714, "repo_name": "nfroidure/whook", "id": "182d6b2b9426fec7f72847d1febd7a2e68163cfc", "size": "2744", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/whook-oauth2/src/services/authCookies.test.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "887" }, { "name": "TypeScript", "bytes": "973685" } ], "symlink_target": "" }
ARG0="$0" while [ -h "$ARG0" ]; do ls=`ls -ld "$ARG0"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then ARG0="$link" else ARG0="`dirname $ARG0`/$link" fi done DIRNAME="`dirname $ARG0`" PROGRAM="`basename $ARG0`" while [ ".$1" != . ] do case "$1" in --java-home ) JAVA_HOME="$2" shift; shift; continue ;; --catalina-home ) CATALINA_HOME="$2" shift; shift; continue ;; --catalina-base ) CATALINA_BASE="$2" shift; shift; continue ;; --catalina-pid ) CATALINA_PID="$2" shift; shift; continue ;; --tomcat-user ) TOMCAT_USER="$2" shift; shift; continue ;; --service-start-wait-time ) SERVICE_START_WAIT_TIME="$2" shift; shift; continue ;; * ) break ;; esac done # OS specific support (must be 'true' or 'false'). cygwin=false; darwin=false; case "`uname`" in CYGWIN*) cygwin=true ;; Darwin*) darwin=true ;; esac # Use the maximum available, or set MAX_FD != -1 to use that test ".$MAX_FD" = . && MAX_FD="maximum" # Setup parameters for running the jsvc # test ".$TOMCAT_USER" = . && TOMCAT_USER=tomcat # Set JAVA_HOME to working JDK or JRE # JAVA_HOME=/opt/jdk-1.6.0.22 # If not set we'll try to guess the JAVA_HOME # from java binary if on the PATH # if [ -z "$JAVA_HOME" ]; then JAVA_BIN="`which java 2>/dev/null || type java 2>&1`" while [ -h "$JAVA_BIN" ]; do ls=`ls -ld "$JAVA_BIN"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then JAVA_BIN="$link" else JAVA_BIN="`dirname $JAVA_BIN`/$link" fi done test -x "$JAVA_BIN" && JAVA_HOME="`dirname $JAVA_BIN`" test ".$JAVA_HOME" != . && JAVA_HOME=`cd "$JAVA_HOME/.." >/dev/null; pwd` else JAVA_BIN="$JAVA_HOME/bin/java" fi # Only set CATALINA_HOME if not already set test ".$CATALINA_HOME" = . && CATALINA_HOME=`cd "$DIRNAME/.." >/dev/null; pwd` test ".$CATALINA_BASE" = . && CATALINA_BASE="$CATALINA_HOME" test ".$CATALINA_MAIN" = . && CATALINA_MAIN=org.apache.catalina.startup.Bootstrap # If not explicitly set, look for jsvc in CATALINA_BASE first then CATALINA_HOME if [ -z "$JSVC" ]; then JSVC="$CATALINA_BASE/bin/jsvc" if [ ! -x "$JSVC" ]; then JSVC="$CATALINA_HOME/bin/jsvc" fi fi # Set the default service-start wait time if necessary test ".$SERVICE_START_WAIT_TIME" = . && SERVICE_START_WAIT_TIME=10 # Ensure that any user defined CLASSPATH variables are not used on startup, # but allow them to be specified in setenv.sh, in rare case when it is needed. CLASSPATH= JAVA_OPTS= if [ -r "$CATALINA_BASE/bin/setenv.sh" ]; then . "$CATALINA_BASE/bin/setenv.sh" elif [ -r "$CATALINA_HOME/bin/setenv.sh" ]; then . "$CATALINA_HOME/bin/setenv.sh" fi # Add on extra jar files to CLASSPATH test ".$CLASSPATH" != . && CLASSPATH="${CLASSPATH}:" CLASSPATH="$CLASSPATH$CATALINA_HOME/bin/bootstrap.jar:$CATALINA_HOME/bin/commons-daemon.jar" test ".$CATALINA_OUT" = . && CATALINA_OUT="$CATALINA_BASE/logs/catalina-daemon.out" test ".$CATALINA_TMP" = . && CATALINA_TMP="$CATALINA_BASE/temp" # Add tomcat-juli.jar to classpath # tomcat-juli.jar can be over-ridden per instance if [ -r "$CATALINA_BASE/bin/tomcat-juli.jar" ] ; then CLASSPATH="$CLASSPATH:$CATALINA_BASE/bin/tomcat-juli.jar" else CLASSPATH="$CLASSPATH:$CATALINA_HOME/bin/tomcat-juli.jar" fi # Set juli LogManager config file if it is present and an override has not been issued if [ -z "$LOGGING_CONFIG" ]; then if [ -r "$CATALINA_BASE/conf/logging.properties" ]; then LOGGING_CONFIG="-Djava.util.logging.config.file=$CATALINA_BASE/conf/logging.properties" else # Bugzilla 45585 LOGGING_CONFIG="-Dnop" fi fi test ".$LOGGING_MANAGER" = . && LOGGING_MANAGER="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager" JAVA_OPTS="$JAVA_OPTS $LOGGING_MANAGER" # Set -pidfile test ".$CATALINA_PID" = . && CATALINA_PID="$CATALINA_BASE/logs/catalina-daemon.pid" # Increase the maximum file descriptors if we can if [ "$cygwin" = "false" ]; then MAX_FD_LIMIT=`ulimit -H -n` if [ "$?" -eq 0 ]; then # Darwin does not allow RLIMIT_INFINITY on file soft limit if [ "$darwin" = "true" -a "$MAX_FD_LIMIT" = "unlimited" ]; then MAX_FD_LIMIT=`/usr/sbin/sysctl -n kern.maxfilesperproc` fi test ".$MAX_FD" = ".maximum" && MAX_FD="$MAX_FD_LIMIT" ulimit -n $MAX_FD if [ "$?" -ne 0 ]; then echo "$PROGRAM: Could not set maximum file descriptor limit: $MAX_FD" fi else echo "$PROGRAM: Could not query system maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # Java 9 no longer supports the java.endorsed.dirs # system property. Only try to use it if # JAVA_ENDORSED_DIRS was explicitly set # or CATALINA_HOME/endorsed exists. ENDORSED_PROP=ignore.endorsed.dirs if [ -n "$JAVA_ENDORSED_DIRS" ]; then ENDORSED_PROP=java.endorsed.dirs fi if [ -d "$CATALINA_HOME/endorsed" ]; then ENDORSED_PROP=java.endorsed.dirs fi # ----- Execute The Requested Command ----------------------------------------- case "$1" in run ) shift "$JSVC" $* \ $JSVC_OPTS \ -java-home "$JAVA_HOME" \ -pidfile "$CATALINA_PID" \ -wait "$SERVICE_START_WAIT_TIME" \ -nodetach \ -outfile "&1" \ -errfile "&2" \ -classpath "$CLASSPATH" \ "$LOGGING_CONFIG" $JAVA_OPTS $CATALINA_OPTS \ -D$ENDORSED_PROP="$JAVA_ENDORSED_DIRS" \ -Dcatalina.base="$CATALINA_BASE" \ -Dcatalina.home="$CATALINA_HOME" \ -Djava.io.tmpdir="$CATALINA_TMP" \ $CATALINA_MAIN exit $? ;; start ) "$JSVC" $JSVC_OPTS \ -java-home "$JAVA_HOME" \ -user $TOMCAT_USER \ -pidfile "$CATALINA_PID" \ -wait "$SERVICE_START_WAIT_TIME" \ -outfile "$CATALINA_OUT" \ -errfile "&1" \ -classpath "$CLASSPATH" \ "$LOGGING_CONFIG" $JAVA_OPTS $CATALINA_OPTS \ -D$ENDORSED_PROP="$JAVA_ENDORSED_DIRS" \ -Dcatalina.base="$CATALINA_BASE" \ -Dcatalina.home="$CATALINA_HOME" \ -Djava.io.tmpdir="$CATALINA_TMP" \ $CATALINA_MAIN exit $? ;; stop ) "$JSVC" $JSVC_OPTS \ -stop \ -pidfile "$CATALINA_PID" \ -classpath "$CLASSPATH" \ -D$ENDORSED_PROP="$JAVA_ENDORSED_DIRS" \ -Dcatalina.base="$CATALINA_BASE" \ -Dcatalina.home="$CATALINA_HOME" \ -Djava.io.tmpdir="$CATALINA_TMP" \ $CATALINA_MAIN exit $? ;; version ) "$JSVC" \ -java-home "$JAVA_HOME" \ -pidfile "$CATALINA_PID" \ -classpath "$CLASSPATH" \ -errfile "&2" \ -version \ -check \ $CATALINA_MAIN if [ "$?" = 0 ]; then "$JAVA_BIN" \ -classpath "$CATALINA_HOME/lib/catalina.jar" \ org.apache.catalina.util.ServerInfo fi exit $? ;; * ) echo "Unknown command: '$1'" echo "Usage: $PROGRAM ( commands ... )" echo "commands:" echo " run Start Tomcat without detaching from console" echo " start Start Tomcat" echo " stop Stop Tomcat" echo " version What version of commons daemon and Tomcat" echo " are you running?" exit 1 ;; esac
{ "content_hash": "5880e2915ca9edab995d6873ff2804c2", "timestamp": "", "source": "github", "line_count": 251, "max_line_length": 115, "avg_line_length": 29.800796812749002, "alnum_prop": 0.5810160427807487, "repo_name": "gitee2008/glaf", "id": "920ade1ce67e42c0d99ac8046319b09fc318fd18", "size": "8508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tomcat/bin/daemon.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "34108" }, { "name": "CSS", "bytes": "4661692" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "FreeMarker", "bytes": "1445841" }, { "name": "HTML", "bytes": "1858417" }, { "name": "Java", "bytes": "8363421" }, { "name": "JavaScript", "bytes": "13692328" }, { "name": "Less", "bytes": "21042" }, { "name": "PHP", "bytes": "6147" }, { "name": "SCSS", "bytes": "19646" }, { "name": "Shell", "bytes": "51272" } ], "symlink_target": "" }
<?php namespace English\GradnotesBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** * English\GradnotesBundle\Entity\Gradnotes * * @ORM\Table(name="gradnotes") * @ORM\Entity(repositoryClass="English\GradnotesBundle\Entity\GradnotesRepository") */ class Gradnotes { /** * @var integer $id * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var integer $gid * * @ORM\Column(name="gid", type="integer") */ private $gid; /** * @var text $notes * * @ORM\Column(name="notes", type="text", nullable=true) */ private $notes; /** * @var integer $userid * * @ORM\Column(name="userid", type="integer", nullable=true) */ private $userid; /** * @ORM\Column(type="datetime", nullable=true) * @Gedmo\Timestampable(on="create") */ protected $created; /** * @ORM\Column(type="datetime", nullable=true) * @Gedmo\Timestampable(on="update") */ protected $updated; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set gid * * @param integer $gid */ public function setGid($gid) { $this->gid = $gid; } /** * Get gid * * @return integer */ public function getGid() { return $this->gid; } /** * Set notes * * @param text $notes */ public function setNotes($notes) { $this->notes = $notes; } /** * Get notes * * @return text */ public function getNotes() { return $this->notes; } /** * Set created * * @param datetime $created */ public function setCreated($created) { $this->created = $created; } /** * Get created * * @return datetime */ public function getCreated() { return $this->created; } /** * Set updated * * @param datetime $updated */ public function setUpdated($updated) { $this->updated = $updated; } /** * Get updated * * @return datetime */ public function getUpdated() { return $this->updated; } /** * Set userid * * @param integer $userid */ public function setUserid($userid) { $this->userid = $userid; } /** * Get userid * * @return integer */ public function getUserid() { return $this->userid; } }
{ "content_hash": "77b2906a0bd05a257570474955f66412", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 84, "avg_line_length": 16.29940119760479, "alnum_prop": 0.4955914768552535, "repo_name": "rlbaltha/engDept", "id": "4beaf1e54740ac9d82b87e2951111e8640b75378", "size": "2722", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/English/GradnotesBundle/Entity/Gradnotes.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "176" }, { "name": "CSS", "bytes": "281546" }, { "name": "HTML", "bytes": "187016" }, { "name": "JavaScript", "bytes": "65538" }, { "name": "PHP", "bytes": "536771" } ], "symlink_target": "" }
import pandas as pd import numpy as np import matplotlib.pyplot as plt from rdkit.Chem import Descriptors from rdkit import Chem from rdkit.Chem import rdMolDescriptors def slicedict(d, ixs): newd = {} for key in d: newd[key] = d[key][ixs] return newd def randomize_order(data): N = len(data.values()[0]) rand_ix = np.arange(N) np.random.seed(1) np.random.shuffle(rand_ix) return slicedict(data, rand_ix) def minimum_degree_in_molecule(mol): degrees = [atom.GetDegree() for atom in mol.GetAtoms()] return np.min(degrees) def maximum_degree_in_molecule(mol): degrees = [atom.GetDegree() for atom in mol.GetAtoms()] return np.max(degrees) rdkit_functions = {'Molecular Weight' : Descriptors.MolWt, 'Polar Surface Area' : rdMolDescriptors.CalcTPSA, 'Number of Rings' : rdMolDescriptors.CalcNumRings, 'Number of H-Bond Donors' : rdMolDescriptors.CalcNumHBD, 'Number of Rotatable Bonds' : rdMolDescriptors.CalcNumRotatableBonds, 'Minimum Degree' : minimum_degree_in_molecule, 'Maximum Degree' : maximum_degree_in_molecule} filenames = ['nr-ahr.smiles', 'nr-ar.smiles', 'sr-mmp.smiles'] #filenames = ['tiny.smiles'] for infilename in filenames: print "Processing", infilename outfilename = infilename + '-processed.csv' removed_outfilename = infilename + '-excluded_molecules.csv' pandas_data = pd.io.parsers.read_csv(infilename, sep='\t') fields = ['smiles', 'inchi_key', 'target'] print "Loading raw file..." data = {field: np.array(pandas_data[field]) for field in fields} data = randomize_order(data) print "Computing molecule graphs from SMILES..." mols = map(Chem.MolFromSmiles, data['smiles']) N_mols_original = len(mols) bad_mol_ixs = np.array([x is None or maximum_degree_in_molecule(x) >= 5 for x in mols]) print "{0} molecules couldn't be parsed.".format(np.sum(bad_mol_ixs)) def make_fun_run_only_on_good(fun): def new_fun(mol): if mol is not None: return fun(mol) else: return np.NaN return new_fun print "Computing RDKit features on each molecule..." for feature_name, fun in rdkit_functions.iteritems(): print "Computing", feature_name, "..." data[feature_name] = np.array(map(make_fun_run_only_on_good(fun), mols)) print "Identifying duplicates...", all_inchis = {} duplicated_mols = [] is_dup = [False] * len(data.values()[0]) for i, inchi in enumerate(data['inchi_key']): if inchi in all_inchis: is_dup[i] = True all_inchis[inchi] = True print np.sum(is_dup), "found." print "Identifying bad values...", is_finite = [True] * len(data.values()[0]) for names, vals in data.iteritems(): if names in ['inchi_key', 'smiles']: continue # Not-numeric so don't worry is_finite = np.logical_and(is_finite, np.isfinite(vals)) print np.sum(np.logical_not(is_finite)), " found." good_ixs = is_finite & np.logical_not(is_dup) & np.logical_not(bad_mol_ixs) good_data = slicedict(data, good_ixs) bad_data = slicedict(data, np.logical_not(good_ixs)) print "Datapoints thrown away:", np.sum(np.logical_not(good_ixs)) print "Datapoints kept:", np.sum(good_ixs) print "Writing output to file..." pd.DataFrame(good_data).to_csv(outfilename, sep=',', header=True, index=False) pd.DataFrame(bad_data).to_csv(removed_outfilename, sep=',', header=True, index=False) print "Making histograms of all features..." for name, vals in good_data.iteritems(): if name in ['inchi_key', 'smiles']: continue # Not-numeric so don't worry fig = plt.figure() plt.hist(vals, 20) plt.xlabel(name) plt.ylabel("Frequency") plt.savefig('histograms/' + name + '.png') plt.close()
{ "content_hash": "eee8988bbdc712b057699017f5c5ea10", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 91, "avg_line_length": 36.642201834862384, "alnum_prop": 0.628442663995994, "repo_name": "HIPS/neural-fingerprint", "id": "53097a71f08e8275572a5b87993366fd5c2408d9", "size": "4114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/2015-05-22-tox/preprocess_data.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "14923" }, { "name": "PostScript", "bytes": "35876" }, { "name": "Python", "bytes": "74838" }, { "name": "Shell", "bytes": "363" }, { "name": "TeX", "bytes": "263007" } ], "symlink_target": "" }
package apollo.gui; import junit.framework.TestCase; import java.io.File; import java.util.Set; public class GenericFileFilterTest extends TestCase { //instance variables GenericFileFilter filter; protected void setUp() throws Exception { super.setUp(); filter = new GenericFileFilter("Test filter"); } public void testAcceptFile() { filter.addExtension("txt"); assertTrue(filter.accept(new File("test.txt"))); } public void testGetDescription() { assertEquals("getDescription()", "Test filter", filter.getDescription()); } public void testSetDescription() { filter.setDescription("Foo"); assertEquals("setDescription()", "Foo", filter.getDescription()); } public void testAddExtension() { filter.addExtension("doc"); assertTrue(filter.accept(new File("foo.doc"))); } public void testGetExtensions() { filter.addExtension("txt"); Set<String> exts = filter.getExtensions(); assertEquals("getExtensions()", 1, exts.size()); assertEquals("getExtensions()", true, exts.contains("txt")); } }
{ "content_hash": "5373422a47be32d7cd0caaeeadf28a6e", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 75, "avg_line_length": 23.11111111111111, "alnum_prop": 0.7192307692307692, "repo_name": "genome-vendor/apollo", "id": "d50ac3fa08c3a4b0ee64d590e69d225780ec6455", "size": "1040", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/apollo/gui/GenericFileFilterTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "11006" }, { "name": "Java", "bytes": "8207482" }, { "name": "Perl", "bytes": "41725" }, { "name": "Shell", "bytes": "15681" } ], "symlink_target": "" }
ο»Ώ// Copyright (C) 2017 History in Paderborn App - UniversitΓ€t Paderborn // // 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. using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using Itinero.Profiles; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.ContentApiFetchers; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.ContentApiFetchers.Contracts; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.ContentHandling; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.DtoToModelConverters; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.FeatureToggling; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.Managers; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.UserManagement; using PaderbornUniversity.SILab.Hip.Mobile.Shared.Common; using PaderbornUniversity.SILab.Hip.Mobile.Shared.Common.Contracts; using PaderbornUniversity.SILab.Hip.Mobile.Shared.Helpers; using PaderbornUniversity.SILab.Hip.Mobile.Shared.ServiceAccessLayer; using PaderbornUniversity.SILab.Hip.Mobile.Shared.ServiceAccessLayer.AuthenticationApiAccess; using PaderbornUniversity.SILab.Hip.Mobile.Shared.ServiceAccessLayer.ContentApiAccesses; using PaderbornUniversity.SILab.Hip.Mobile.Shared.ServiceAccessLayer.ContentApiAccesses.Contracts; using PaderbornUniversity.SILab.Hip.Mobile.Shared.ServiceAccessLayer.FeatureToggleApiAccess; using PaderbornUniversity.SILab.Hip.Mobile.Shared.ServiceAccessLayer.UserApiAccesses; using PaderbornUniversity.SILab.Hip.Mobile.UI.Helpers; using PaderbornUniversity.SILab.Hip.Mobile.UI.Location; using PaderbornUniversity.SILab.Hip.Mobile.UI.Resources; using PaderbornUniversity.SILab.Hip.Mobile.UI.ViewModels.Views; using Xamarin.Forms; namespace PaderbornUniversity.SILab.Hip.Mobile.UI.ViewModels.Pages { public class LoadingPageViewModel : NavigationViewModel, IProgressListener { public LoadingPageViewModel() { // This lookup NOT required for Windows platforms - the Culture will be automatically set if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android) { // determine the correct, supported .NET culture var ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo(); Strings.Culture = ci; // set the RESX for resource localization DependencyService.Get<ILocalize>().SetLocale(ci); // set the Thread for locale-aware methods } Text = Strings.LoadingPage_Text; Subtext = Strings.LoadingPage_Subtext; StartLoading = new Command(Load); CancelCommand = new Command(CancelLoading); cancellationTokenSource = new CancellationTokenSource(); // listen to sleep and wake up messages as the main screen cannot be started when the app is sleeping MessagingCenter.Subscribe<App>(this, AppSharedData.WillSleepMessage, WillSleep); MessagingCenter.Subscribe<App>(this, AppSharedData.WillWakeUpMessage, WillWakeUp); } private string text; private string subtext; private ICommand startLoading; private ICommand cancel; private bool isExtendedViewsVisible; private double loadingProgress; private readonly CancellationTokenSource cancellationTokenSource; private bool isSleeping; private bool isDatabaseUpToDate = true; private string errorMessage; private string errorTitle = ""; private Action actionOnUiThread; /// <summary> /// The headline text. /// </summary> public string Text { get { return text; } set { SetProperty(ref text, value); } } /// <summary> /// the sub text. /// </summary> public string Subtext { get { return subtext; } set { SetProperty(ref subtext, value); } } /// <summary> /// The command for starting loading of database. /// </summary> public ICommand StartLoading { get { return startLoading; } set { SetProperty(ref startLoading, value); } } /// <summary> /// The command for canceling loading of database. /// </summary> public ICommand CancelCommand { get { return cancel; } set { SetProperty(ref cancel, value); } } /// <summary> /// Indicates wether the extended view is visible or not. The extended view gives more information about the current progress. /// </summary> public bool IsExtendedViewsVisible { get { return isExtendedViewsVisible; } set { SetProperty(ref isExtendedViewsVisible, value); } } /// <summary> /// Value indicating the current loading progress. /// </summary> public double LoadingProgress { get { return loadingProgress; } set { SetProperty(ref loadingProgress, value); } } private IBaseDataFetcher baseDataFetcher; private async void Load() { try { await InitIoCContainerAsync(); await BackupData.Init(); baseDataFetcher = IoCManager.Resolve<IBaseDataFetcher>(); var networkAccessStatus = IoCManager.Resolve<INetworkAccessChecker>().GetNetworkAccessStatus(); if (networkAccessStatus != NetworkAccessStatus.NoAccess) { await CheckForUpdatedDatabase(); } else { errorTitle = Strings.LoadingPageViewModel_BaseData_DownloadFailed_Title; errorMessage = Strings.LoadingPageViewModel_BaseData_DatabaseUpToDateCheckFailed; } if (!isDatabaseUpToDate) { if (networkAccessStatus == NetworkAccessStatus.MobileAccess && Settings.WifiOnly) { actionOnUiThread = AskUserDownloadDataViaMobile; // if the app is not sleeping ask the user whether to download via mobile otherwise wait for wake up if (!isSleeping) { Device.BeginInvokeOnMainThread(actionOnUiThread); } return; } await UpdateDatabase(); } await AchievementManager.UpdateServerAndLocalState(); } catch (Exception e) { // Catch all exceptions happening on startup cause otherwise the loading page will be shown indefinitely // This should only happen during development errorMessage = null; errorTitle = null; Debug.WriteLine(e); } LoadCacheAndStart(); } private async void AskUserDownloadDataViaMobile() { actionOnUiThread = null; var downloadData = await Navigation.DisplayAlert(Strings.LoadingPageViewModel_BaseData_DataAvailable, Strings.LoadingPageViewModel_BaseData_DownloadViaMobile, Strings.Yes, Strings.No); try { if (downloadData) { await UpdateDatabase(); } LoadCacheAndStart(); } catch (Exception e) { // Catch all exceptions happening on startup cause otherwise the loading page will be shown indefinitely // This should only happen during development errorMessage = null; errorTitle = null; Debug.WriteLine(e); } } private async Task CheckForUpdatedDatabase() { try { isDatabaseUpToDate = await baseDataFetcher.IsDatabaseUpToDate(); } catch (Exception e) { Debug.WriteLine(e); errorTitle = Strings.LoadingPageViewModel_BaseData_DownloadFailed_Title; errorMessage = Strings.LoadingPageViewModel_BaseData_DatabaseUpToDateCheckFailed; } } private async Task UpdateDatabase() { IsExtendedViewsVisible = true; try { await baseDataFetcher.FetchBaseDataIntoDatabase(cancellationTokenSource.Token, this); } catch (Exception e) { errorTitle = Strings.LoadingPageViewModel_BaseData_DownloadFailed_Title; errorMessage = Strings.LoadingPageViewModel_BaseData_DownloadFailed_Text; Debug.WriteLine(e); } } private async void LoadCacheAndStart() { LoadingProgress = 0.9; await Task.Delay(100); actionOnUiThread = async () => { if (errorMessage != null && errorTitle != null) { await Navigation.DisplayAlert(errorTitle, errorMessage, Strings.Ok); } StartMainApplication(); }; // if the app is not sleeping open the main menu, otherwise wait for it to wake up if (!isSleeping) { Device.BeginInvokeOnMainThread(actionOnUiThread); } } private async void StartMainApplication() { Settings.InitialThemeSelected = true; var vm = new MainPageViewModel(); LoadingProgress = 1; await Task.Delay(100); MessagingCenter.Unsubscribe<App>(this, AppSharedData.WillSleepMessage); MessagingCenter.Unsubscribe<App>(this, AppSharedData.WillWakeUpMessage); Navigation.StartNewNavigationStack(vm); } private async Task InitIoCContainerAsync() { IoCManager.RegisterType<IDataLoader, EmbeddedResourceDataLoader>(); //init serviceaccesslayer IoCManager.RegisterInstance(typeof(IContentApiClient), new ContentApiClient()); //IoCManager.RegisterInstance(typeof(IContentApiClient), new UserApiClient()); // ReSharper disable once ConditionIsAlwaysTrueOrFalse #pragma warning disable 162 if (Constants.UseMockData) { // We can use this since everything goes through the FeatureToggleRouter anyway, // which provides fallback in case the network is down IoCManager.RegisterInstance(typeof(IFeatureToggleApiAccess), new FeatureToggleApiAccess(new ContentApiClient(ServerEndpoints.FeatureTogglesApiPath))); IoCManager.RegisterType<IAchievementsApiAccess, MockAchievementsApiAccess>(); IoCManager.RegisterType<IExhibitsApiAccess, MockExhibitsApiAccess>(); IoCManager.RegisterType<IMediasApiAccess, MockMediaApiAccess>(); IoCManager.RegisterType<IFileApiAccess, MockFileApiAccess>(); IoCManager.RegisterType<IPagesApiAccess, MockPagesApiAccess>(); IoCManager.RegisterType<IRoutesApiAccess, MockRoutesApiAccess>(); IoCManager.RegisterType<ITagsApiAccess, MockTagsApiAccess>(); IoCManager.RegisterType<IAuthApiAccess, MockAuthApiAccess>(); IoCManager.RegisterType<IUserRatingApiAccess, MockUserRatingApiAccess>(); } else { IoCManager.RegisterInstance(typeof(IAchievementsApiAccess), new AchievementsApiAccess(new ContentApiClient(ServerEndpoints.AchievementsApiPath))); IoCManager.RegisterInstance(typeof(IFeatureToggleApiAccess), new FeatureToggleApiAccess(new ContentApiClient(ServerEndpoints.FeatureTogglesApiPath))); IoCManager.RegisterType<IExhibitsApiAccess, ExhibitsApiAccess>(); IoCManager.RegisterType<IMediasApiAccess, MediasApiAccess>(); IoCManager.RegisterType<IFileApiAccess, FileApiAccess>(); IoCManager.RegisterType<IPagesApiAccess, PagesApiAccess>(); IoCManager.RegisterType<IRoutesApiAccess, RoutesApiAccess>(); IoCManager.RegisterType<ITagsApiAccess, TagsApiAccess>(); IoCManager.RegisterType<IAuthApiAccess, AuthApiAccess>(); IoCManager.RegisterType<IQuizApiAccess, QuizApiAccess>(); IoCManager.RegisterInstance(typeof(IUserRatingApiAccess), new UserRatingApiAccess(new ContentApiClient())); } #pragma warning restore 162 //init converters IoCManager.RegisterType<ExhibitConverter>(); IoCManager.RegisterType<MediaToAudioConverter>(); IoCManager.RegisterType<MediaToImageConverter>(); IoCManager.RegisterType<PageConverter>(); IoCManager.RegisterType<RouteConverter>(); IoCManager.RegisterType<TagConverter>(); IoCManager.RegisterType<QuizConverter>(); //init fetchers IoCManager.RegisterInstance(typeof(INewDataCenter), new NewDataCenter()); IoCManager.RegisterType<IMediaDataFetcher, MediaDataFetcher>(); IoCManager.RegisterType<IDataToRemoveFetcher, DataToRemoveFetcher>(); IoCManager.RegisterType<IExhibitsBaseDataFetcher, ExhibitsBaseDataFetcher>(); IoCManager.RegisterType<IFullExhibitDataFetcher, FullExhibitDataFetcher>(); IoCManager.RegisterType<IRoutesBaseDataFetcher, RoutesBaseDataFetcher>(); IoCManager.RegisterType<IBaseDataFetcher, BaseDataFetcher>(); IoCManager.RegisterType<IFullRouteDataFetcher, FullRouteDataFetcher>(); IoCManager.RegisterType<IAchievementFetcher, AchievementFetcher>(); IoCManager.RegisterInstance(typeof(INearbyExhibitManager), new NearbyExhibitManager()); IoCManager.RegisterInstance(typeof(INearbyRouteManager), new NearbyRouteManager()); IoCManager.RegisterInstance(typeof(IUserManager), new UserManager()); IoCManager.RegisterInstance(typeof(IUserRatingManager), new UserRatingManager()); IoCManager.RegisterInstance(typeof(AchievementNotificationViewModel), new AchievementNotificationViewModel()); var featureToggleRouter = await FeatureToggleRouter.CreateAsync(); IoCManager.RegisterInstance(typeof(IFeatureToggleRouter), featureToggleRouter); } /// <summary> /// React to progress updates. /// </summary> /// <param name="newProgress">The new progress value.</param> /// <param name="maxProgress">The maximum propgress value.</param> public void UpdateProgress(double newProgress, double maxProgress) { LoadingProgress = (newProgress / maxProgress) * 0.8; } private double maximumProgress; private double currentProgress; public void ProgressOneStep() { currentProgress++; LoadingProgress = (currentProgress / maximumProgress) * 0.8; } public void SetMaxProgress(double maxProgress) { maximumProgress = maxProgress; } private void WillWakeUp(App obj) { isSleeping = false; // app was send to sleep before the main menu could be opened, open the menu now if (actionOnUiThread != null) { Device.BeginInvokeOnMainThread(actionOnUiThread); } } private void WillSleep(App obj) { isSleeping = true; } private void CancelLoading() { cancellationTokenSource?.Cancel(); } public override void OnDisappearing() { base.OnDisappearing(); cancellationTokenSource.Cancel(); } } }
{ "content_hash": "313de9481e43e9484731d524b42f2f52", "timestamp": "", "source": "github", "line_count": 407, "max_line_length": 166, "avg_line_length": 41.646191646191646, "alnum_prop": 0.6276696165191741, "repo_name": "HiP-App/HiP-Forms", "id": "8c25346653896daa4bc8739321d493cbb8105eed", "size": "16953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sources/HipMobileUI/ViewModels/Pages/LoadingPageViewModel.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1404947" } ], "symlink_target": "" }
require 'spec_helper' module RSpec module Mocks describe "failing MockArgumentMatchers" do before(:each) do @double = double("double") @reporter = double("reporter").as_null_object end after(:each) do reset @double end it "rejects non boolean" do @double.should_receive(:random_call).with(boolean()) expect do @double.random_call("false") end.to raise_error(RSpec::Mocks::MockExpectationError) end it "rejects non numeric" do @double.should_receive(:random_call).with(an_instance_of(Numeric)) expect do @double.random_call("1") end.to raise_error(RSpec::Mocks::MockExpectationError) end it "rejects non string" do @double.should_receive(:random_call).with(an_instance_of(String)) expect do @double.random_call(123) end.to raise_error(RSpec::Mocks::MockExpectationError) end it "rejects goose when expecting a duck" do @double.should_receive(:random_call).with(duck_type(:abs, :div)) expect { @double.random_call("I don't respond to :abs or :div") }.to raise_error(RSpec::Mocks::MockExpectationError) end it "fails if regexp does not match submitted string" do @double.should_receive(:random_call).with(/bcd/) expect { @double.random_call("abc") }.to raise_error(RSpec::Mocks::MockExpectationError) end it "fails if regexp does not match submitted regexp" do @double.should_receive(:random_call).with(/bcd/) expect { @double.random_call(/bcde/) }.to raise_error(RSpec::Mocks::MockExpectationError) end it "fails for a hash w/ wrong values" do @double.should_receive(:random_call).with(:a => "b", :c => "d") expect do @double.random_call(:a => "b", :c => "e") end.to raise_error(RSpec::Mocks::MockExpectationError, /Double "double" received :random_call with unexpected arguments\n expected: \(\{(:a=>\"b\", :c=>\"d\"|:c=>\"d\", :a=>\"b\")\}\)\n got: \(\{(:a=>\"b\", :c=>\"e\"|:c=>\"e\", :a=>\"b\")\}\)/) end it "fails for a hash w/ wrong keys" do @double.should_receive(:random_call).with(:a => "b", :c => "d") expect do @double.random_call("a" => "b", "c" => "d") end.to raise_error(RSpec::Mocks::MockExpectationError, /Double "double" received :random_call with unexpected arguments\n expected: \(\{(:a=>\"b\", :c=>\"d\"|:c=>\"d\", :a=>\"b\")\}\)\n got: \(\{(\"a\"=>\"b\", \"c\"=>\"d\"|\"c\"=>\"d\", \"a\"=>\"b\")\}\)/) end it "matches against a Matcher" do expect do @double.should_receive(:msg).with(equal(3)) @double.msg(37) end.to raise_error(RSpec::Mocks::MockExpectationError, "Double \"double\" received :msg with unexpected arguments\n expected: (equal 3)\n got: (37)") end it "fails no_args with one arg" do expect do @double.should_receive(:msg).with(no_args) @double.msg(37) end.to raise_error(RSpec::Mocks::MockExpectationError, "Double \"double\" received :msg with unexpected arguments\n expected: (no args)\n got: (37)") end it "fails hash_including with missing key" do expect do @double.should_receive(:msg).with(hash_including(:a => 1)) @double.msg({}) end.to raise_error(RSpec::Mocks::MockExpectationError, "Double \"double\" received :msg with unexpected arguments\n expected: (hash_including(:a=>1))\n got: ({})") end it "fails with block matchers" do expect do @double.should_receive(:msg).with {|arg| expect(arg).to eq :received } @double.msg :no_msg_for_you end.to raise_error(RSpec::Expectations::ExpectationNotMetError, /expected: :received.*\s*.*got: :no_msg_for_you/) end end end end
{ "content_hash": "f3d49633e8d8840a2da40f679da51d99", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 271, "avg_line_length": 41.829787234042556, "alnum_prop": 0.5887589013224822, "repo_name": "samphippen/rspec-mocks", "id": "7e1351ade45fa39ab030faf3834af230779e31bb", "size": "3932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/rspec/mocks/failing_argument_matchers_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "309850" }, { "name": "Shell", "bytes": "973" } ], "symlink_target": "" }
/*! * V4Fire Client Core * https://github.com/V4Fire/Client * * Released under the MIT license * https://github.com/V4Fire/Client/blob/master/LICENSE */ import type { RenderObject } from 'core/component'; export const tplCache = Object.createDict<RenderObject>();
{ "content_hash": "71e95719e4738f4980314d4ec65bbef5", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 55, "avg_line_length": 22.75, "alnum_prop": 0.7216117216117216, "repo_name": "V4Fire/Client", "id": "c1f853f07d6d568cfd4fa08b07f6ad87a490abb8", "size": "273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/super/i-block/modules/vdom/const.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "8114" }, { "name": "JavaScript", "bytes": "951325" }, { "name": "Scheme", "bytes": "64903" }, { "name": "Shell", "bytes": "109" }, { "name": "Stylus", "bytes": "61221" }, { "name": "TypeScript", "bytes": "1272027" } ], "symlink_target": "" }
<<<<<<< HEAD # Doctrine Data Fixtures Extension This extension aims to provide a simple way to manage and execute the loading of data fixtures for the Doctrine ORM or ODM. You can write fixture classes by implementing the Doctrine\Common\DataFixtures\FixtureInterface interface: namespace MyDataFixtures; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; class LoadUserData implements FixtureInterface { public function load(ObjectManager $manager) { $user = new User(); $user->setUsername('jwage'); $user->setPassword('test'); $manager->persist($user); $manager->flush(); } } Now you can begin adding the fixtures to a loader instance: use Doctrine\Common\DataFixtures\Loader; use MyDataFixtures\LoadUserData; $loader = new Loader(); $loader->addFixture(new LoadUserData); You can load a set of fixtures from a directory as well: $loader->loadFromDirectory('/path/to/MyDataFixtures'); You can get the added fixtures using the getFixtures() method: $fixtures = $loader->getFixtures(); Now you can easily execute the fixtures: use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Purger\ORMPurger; $purger = new ORMPurger(); $executor = new ORMExecutor($em, $purger); $executor->execute($loader->getFixtures()); If you want to append the fixtures instead of purging before loading then pass true to the 2nd argument of execute: $executor->execute($loader->getFixtures(), true); ## Sharing objects between fixtures In case if fixture objects have relations to other fixtures, it is now possible to easily add a reference to that object by name and later reference it to form a relation. Here is an example fixtures for **Role** and **User** relation namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; class LoadUserRoleData extends AbstractFixture { public function load(ObjectManager $manager) { $adminRole = new Role(); $adminRole->setName('admin'); $anonymousRole = new Role; $anonymousRole->setName('anonymous'); $manager->persist($adminRole); $manager->persist($anonymousRole); $manager->flush(); // store reference to admin role for User relation to Role $this->addReference('admin-role', $adminRole); } } And the **User** data loading fixture : namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; class LoadUserData extends AbstractFixture { public function load(ObjectManager $manager) { $user = new User(); $user->setUsername('jwage'); $user->setPassword('test'); $user->setRole( $this->getReference('admin-role') // load the stored reference ); $manager->persist($user); $manager->flush(); // store reference of admin-user for other Fixtures $this->addReference('admin-user', $user); } } ## Fixture ordering **Notice** that the fixture loading order is important! To handle it manually implement one of the following interfaces: ### OrderedFixtureInterface Set the order manually: namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; class MyFixture extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 10; // number in which order to load fixtures } } ### DependentFixtureInterface Provide an array of fixture class names: namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; class MyFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array('MyDataFixtures\MyOtherFixture'); // fixture classes fixture is dependent on } } class MyOtherFixture extends AbstractFixture { public function load(ObjectManager $manager) {} } **Notice** the ordering is relevant to Loader class. ## Running the tests: PHPUnit 3.5 or newer together with Mock_Object package is required. To setup and run tests follow these steps: - go to the root directory of data-fixtures - run: **git submodule init** - run: **git submodule update** - copy the phpunit config **cp phpunit.xml.dist phpunit.xml** - run: **phpunit** ======= portal ====== Portal de acesso GW >>>>>>> 1d08f466b4ad712183cf549eefa3fcf9a6b81afa
{ "content_hash": "d781680efcbf7fa28d09e428daff064b", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 101, "avg_line_length": 28.734806629834253, "alnum_prop": 0.6787156316093059, "repo_name": "Weslleynds/agendaSuporte", "id": "b60ad8bd7108f1c03c67214c00e4f1fe62d613df", "size": "5201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/doctrine/data-fixtures/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "22225" }, { "name": "HTML", "bytes": "30676" }, { "name": "JavaScript", "bytes": "43062" }, { "name": "PHP", "bytes": "68004" } ], "symlink_target": "" }
local l = require('lexer') local token, word_match = l.token, l.word_match local P, S, R = lpeg.P, lpeg.S, lpeg.R local M = {_NAME = 'moonscript'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) local longstring = lpeg.Cmt('[' * lpeg.C(P('=')^0) * '[', function(input, index, eq) local _, e = input:find(']'..eq..']', index, true) return (e or #input) + 1 end) -- Comments. local line_comment = '--' * l.nonnewline^0 local block_comment = '--' * longstring local comment = token(l.COMMENT, block_comment + line_comment) -- Strings. local sq_str = l.delimited_range("'", false, true) local dq_str = l.delimited_range('"', false, true) local string = token(l.STRING, sq_str + dq_str) + token('longstring', longstring) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Keywords. local keyword = token(l.KEYWORD, word_match { -- Lua. 'and', 'break', 'do', 'else', 'elseif', 'false', 'for', 'if', 'in', 'local', 'nil', 'not', 'or', 'return', 'then', 'true', 'while', -- Moonscript. 'continue', 'class', 'export', 'extends', 'from', 'import', 'super', 'switch', 'unless', 'using', 'when', 'with' }) -- Constants. local constant = token(l.CONSTANT, word_match{ '_G', '_VERSION', -- Added in 5.2. '_ENV' }) -- Functions. local func = token(l.FUNCTION, word_match{ 'assert', 'collectgarbage', 'dofile', 'error', 'getmetatable', 'ipairs', 'load', 'loadfile', 'next', 'pairs', 'pcall', 'print', 'rawequal', 'rawget', 'rawset', 'require', 'select', 'setmetatable', 'tonumber', 'tostring', 'type', 'xpcall', -- Added in 5.2. 'rawlen' }) -- Libraries. local library = token('library', word_match({ -- Coroutine. 'coroutine', 'coroutine.create', 'coroutine.resume', 'coroutine.running', 'coroutine.status', 'coroutine.wrap', 'coroutine.yield', -- Coroutine added in 5.3. 'coroutine.isyieldable', -- Module. 'package', 'package.cpath', 'package.loaded', 'package.loadlib', 'package.path', 'package.preload', -- Module added in 5.2. 'package.config', 'package.searchers', 'package.searchpath', -- UTF-8 added in 5.3. 'utf8', 'utf8.char', 'utf8.charpattern', 'utf8.codepoint', 'utf8.codes', 'utf8.len', 'utf8.offset', -- String. 'string', 'string.byte', 'string.char', 'string.dump', 'string.find', 'string.format', 'string.gmatch', 'string.gsub', 'string.len', 'string.lower', 'string.match', 'string.rep', 'string.reverse', 'string.sub', 'string.upper', -- String added in 5.3. 'string.pack', 'string.packsize', 'string.unpack', -- Table. 'table', 'table.concat', 'table.insert', 'table.remove', 'table.sort', -- Table added in 5.2. 'table.pack', 'table.unpack', -- Table added in 5.3. 'table.move', -- Math. 'math', 'math.abs', 'math.acos', 'math.asin', 'math.atan', 'math.ceil', 'math.cos', 'math.deg', 'math.exp', 'math.floor', 'math.fmod', 'math.huge', 'math.log', 'math.max', 'math.min', 'math.modf', 'math.pi', 'math.rad', 'math.random', 'math.randomseed', 'math.sin', 'math.sqrt', 'math.tan', -- Math added in 5.3. 'math.maxinteger', 'math.mininteger', 'math.tointeger', 'math.type', 'math.ult', -- IO. 'io', 'io.close', 'io.flush', 'io.input', 'io.lines', 'io.open', 'io.output', 'io.popen', 'io.read', 'io.stderr', 'io.stdin', 'io.stdout', 'io.tmpfile', 'io.type', 'io.write', -- OS. 'os', 'os.clock', 'os.date', 'os.difftime', 'os.execute', 'os.exit', 'os.getenv', 'os.remove', 'os.rename', 'os.setlocale', 'os.time', 'os.tmpname', -- Debug. 'debug', 'debug.debug', 'debug.gethook', 'debug.getinfo', 'debug.getlocal', 'debug.getmetatable', 'debug.getregistry', 'debug.getupvalue', 'debug.sethook', 'debug.setlocal', 'debug.setmetatable', 'debug.setupvalue', 'debug.traceback', -- Debug added in 5.2. 'debug.getuservalue', 'debug.setuservalue', 'debug.upvalueid', 'debug.upvaluejoin', --- MoonScript 0.3.1 standard library. -- Printing functions. 'p', -- Table functions. 'run_with_scope', 'defaultbl', 'extend', 'copy', -- Class/object functions. 'is_object', 'bind_methods', 'mixin', 'mixin_object', 'mixin_table', -- Misc functions. 'fold', -- Debug functions. 'debug.upvalue', }, '.')) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) local proper_ident = token('proper_ident', R('AZ') * l.word) local tbl_key = token('tbl_key', l.word * ':' + ':' * l.word ) local fndef = token('fndef', P('->') + '=>') local err = token(l.ERROR, word_match{'function', 'end'}) -- Operators. local symbol = token('symbol', S('(){}[]')) local operator = token(l.OPERATOR, S('+-*!\\/%^#=<>;:,.')) -- Self reference. local self_var = token('self_ref', '@' * l.word + 'self') M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'error', err}, {'self', self_var}, {'function', func}, {'constant', constant}, {'library', library}, {'identifier', proper_ident + tbl_key + identifier}, {'string', string}, {'comment', comment}, {'number', number}, {'fndef', fndef}, {'symbol', symbol}, {'operator', operator}, } M._tokenstyles = { longstring = l.STYLE_STRING, library = l.STYLE_TYPE, self_ref = l.STYLE_LABEL, proper_ident = l.STYLE_CLASS, fndef = l.STYLE_PREPROCESSOR, symbol = l.STYLE_EMBEDDED, tbl_key = l.STYLE_REGEX, error = l.STYLE_ERROR, } M._FOLDBYINDENTATION = true return M
{ "content_hash": "bee7346824419d0acb53e6d2889c8a36", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 80, "avg_line_length": 32.416666666666664, "alnum_prop": 0.6026441424899008, "repo_name": "LuaExtend/LuaExtend", "id": "8cbe765995a99511e6f8498f6155025fe31d045b", "size": "5546", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tools/ZeroBraneStudio/lualibs/lexers/moonscript.lua", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1417" }, { "name": "C", "bytes": "2010156" }, { "name": "C++", "bytes": "411067" }, { "name": "CMake", "bytes": "31973" }, { "name": "CSS", "bytes": "2454" }, { "name": "HTML", "bytes": "412730" }, { "name": "Java", "bytes": "177782" }, { "name": "Lua", "bytes": "4733282" }, { "name": "Makefile", "bytes": "59247" }, { "name": "Objective-C", "bytes": "40148" }, { "name": "Objective-C++", "bytes": "25822" }, { "name": "Perl", "bytes": "1689" }, { "name": "Roff", "bytes": "34641" }, { "name": "Shell", "bytes": "9749" }, { "name": "XSLT", "bytes": "12288" } ], "symlink_target": "" }
$:.unshift "lib" require 'securerandom' require 'em-synchrony' require 'em-synchrony/fiber_iterator' require 'redis-em-mutex' class Test include Redis::EM::Mutex::Macro auto_mutex :method5 def method1; end auto_mutex def method2; end no_auto_mutex def method3; end def method4; end def method5; end auto_mutex :method4 def method6; end auto_mutex :method6, :method7, block: 10, on_timeout: proc { } def method7; end auto_mutex block: 20 auto_mutex def test(redis, key, value) redis.set key, value ::EM::Synchrony.sleep 0.1 redis.get key end def recursive(n=1, &blk) if n < 10 recursive(n+1, &blk) else yield n end end no_auto_mutex def test_no_mutex(redis, key, value) redis.set key, value ::EM::Synchrony.sleep 0.1 redis.get key end auto_mutex :may_timeout, block: 0, on_timeout: proc { false } def may_timeout; yield; end auto_mutex :may_timeout_no_fallback, block: 0 def may_timeout_no_fallback; yield; end auto_mutex :may_timeout_method_fallback, block: 0, on_timeout: :may_timeout_timed_out def may_timeout_method_fallback; yield; end def may_timeout_timed_out; false; end end describe Redis::EM::Mutex::Macro do it "should define auto_mutex methods" do Test.auto_mutex_methods.keys.should eq [:method5, :method4, :method6, :method7, :may_timeout, :may_timeout_no_fallback, :may_timeout_method_fallback] [:method5, :method2, :method4, :test, :recursive, :may_timeout_no_fallback, :may_timeout_method_fallback].each do |name| Test.method_defined?(name).should be_true Test.method_defined?("#{name}_without_auto_mutex").should be_true Test.method_defined?("#{name}_with_auto_mutex").should be_true Test.method_defined?("#{name}_on_timeout_auto_mutex").should be_false end [:method6, :method7, :may_timeout].each do |name| Test.method_defined?(name).should be_true Test.method_defined?("#{name}_without_auto_mutex").should be_true Test.method_defined?("#{name}_with_auto_mutex").should be_true Test.method_defined?("#{name}_on_timeout_auto_mutex").should be_true end [:method1, :method3, :test_no_mutex, :may_timeout_timed_out].each do |name| Test.method_defined?(name).should be_true Test.method_defined?("#{name}_without_auto_mutex").should be_false Test.method_defined?("#{name}_with_auto_mutex").should be_false Test.method_defined?("#{name}_on_timeout_auto_mutex").should be_false end end it "should method run unprotected" do iterate = 10.times.map { Test.new } test_key = @test_key results = {} ::EM::Synchrony::FiberIterator.new(iterate, iterate.length).each do |test| begin redis = Redis.new @redis_options value = test.__id__.to_s results[value] = test.test_no_mutex(redis, test_key, value) rescue Exception => e @exception = e end end results.length.should eq iterate.length results.each_pair do |k, v| v.should eq results.values.last end end it "should protect auto_mutex method" do iterate = 10.times.map { Test.new } test_key = @test_key results = {} ::EM::Synchrony::FiberIterator.new(iterate, iterate.length).each do |test| begin redis = Redis.new @redis_options value = test.__id__.to_s results[value] = test.test(redis, test_key, value) rescue Exception => e @exception = e end end results.length.should eq iterate.length results.each_pair do |k, v| k.should eq v end end it "should allow recursive calls to protected methods" do iterate = 10.times.map { Test.new } test_key = @test_key results = {} ::EM::Synchrony::FiberIterator.new(iterate, iterate.length).each do |test| begin redis = Redis.new @redis_options value = test.__id__.to_s results[value] = test.recursive do |n| redis.set test_key, value ::EM::Synchrony.sleep 0.1 [redis.get(test_key), n] end rescue Exception => e @exception = e end end results.length.should eq iterate.length results.each_pair do |k, v| v.should eq [k, 10] end end it "should call on_timout lambda when locking times out" do ::EM::Synchrony.next_tick do begin Test.new.may_timeout do ::EM::Synchrony.sleep 0.2 true end.should be_true rescue Exception => e @exception = e end end ::EM::Synchrony.sleep 0.1 Test.new.may_timeout do true end.should be_false ::EM::Synchrony.sleep 0.15 end it "should raise MutexTimeout when locking times out" do ::EM::Synchrony.next_tick do begin Test.new.may_timeout_no_fallback do ::EM::Synchrony.sleep 0.2 true end.should be_true rescue Exception => e @exception = e end end ::EM::Synchrony.sleep 0.1 expect { Test.new.may_timeout_no_fallback do true end }.to raise_error(Redis::EM::Mutex::MutexTimeout) ::EM::Synchrony.sleep 0.15 end it "should call on_timout method when locking times out" do ::EM::Synchrony.next_tick do begin Test.new.may_timeout_method_fallback do ::EM::Synchrony.sleep 0.2 true end.should be_true rescue Exception => e @exception = e end end ::EM::Synchrony.sleep 0.1 Test.new.may_timeout_method_fallback do true end.should be_false ::EM::Synchrony.sleep 0.15 end around(:each) do |testcase| @after_em_stop = nil @exception = nil ::EM.synchrony do begin testcase.call raise @exception if @exception Redis::EM::Mutex.stop_watcher(false) rescue => e Redis::EM::Mutex.stop_watcher(true) raise e ensure ::EM.stop end end @after_em_stop.call if @after_em_stop end before(:all) do @redis_options = {:driver => :synchrony} @test_key = SecureRandom.base64(24) Redis::EM::Mutex.setup @redis_options.merge(size: 11, ns: SecureRandom.base64(15)) end after(:all) do ::EM.synchrony do Redis.new(@redis_options).del @test_key EM.stop end # @lock_names end end
{ "content_hash": "8cce97ebd1196efe13bde3700e4e05f0", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 97, "avg_line_length": 27.40948275862069, "alnum_prop": 0.6236829690202862, "repo_name": "royaltm/redis-em-mutex", "id": "a6dab1ac27070117e21b78d2dbe869c27ee2745d", "size": "6359", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/redis-em-mutex-macros.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "101645" } ], "symlink_target": "" }
package cn.xm.xmvideoplayer.widget.swipebacklayout; /** * @author Yrom */ public interface SwipeBackActivityBase { /** * @return the SwipeBackLayout associated with this activity. */ public abstract SwipeBackLayout getSwipeBackLayout(); public abstract void setSwipeBackEnable(boolean enable); /** * Scroll out contentView and finish the activity */ public abstract void scrollToFinishActivity(); }
{ "content_hash": "32a1d1106c517aa0f406c582cda071f8", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 65, "avg_line_length": 23.42105263157895, "alnum_prop": 0.7123595505617978, "repo_name": "ximencx/XMVideo", "id": "2a93977da8a5ef4121fddcd0311fe0a30bb824e5", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XMVideoCollocation/src/main/java/cn/xm/xmvideoplayer/widget/swipebacklayout/SwipeBackActivityBase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "276243" } ], "symlink_target": "" }
MStatus WLoadSceneCmd::doIt(const MArgList&) { #ifdef _DEBUG Log("LoadScene command called"); #endif Wolf::Commands = Wolf::WCommnads::LoadScene; return MS::kSuccess; } void* WLoadSceneCmd::Command() { return new WLoadSceneCmd(); }
{ "content_hash": "735d53de066d29f6f9d2d35ff6e6bae6", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 45, "avg_line_length": 16, "alnum_prop": 0.7208333333333333, "repo_name": "PooyaEimandar/WolfEngine", "id": "bd9e73b355407a510772fe339a4b4c3f7e7df5f0", "size": "285", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/src/wolf.plugins/Wolf.Plugins.Maya/Commands/WLoadSceneCmd.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5545" }, { "name": "C++", "bytes": "317259" }, { "name": "Objective-C", "bytes": "1179" }, { "name": "Python", "bytes": "1532" } ], "symlink_target": "" }
require 'spec_helper' package_name = 'telegraf' conf_dir = '/etc/telegraf' describe package(package_name) do it { should be_installed } end %w(/etc/telegraf /etc/telegraf/telegraf.d).each do |d| describe file(d) do it { should be_directory } end end %w(telegraf.conf telegraf.d/default_outputs.conf).each do |c| describe file("#{conf_dir}/#{c}") do it { should be_file } it { should be_owned_by 'root' } it { should be_grouped_into 'telegraf' } it { should be_mode '644' } end end describe file("#{conf_dir}/telegraf.d/default_inputs.conf") do it { should be_file } it { should be_owned_by 'root' } it { should be_grouped_into 'telegraf' } it { should be_mode '644' } it { should contain 'inputs.cpu' } it { should contain 'percpu = true' } it { should contain 'totalcpu = true' } it { should contain 'inputs.disk' } it { should contain 'inputs.io' } it { should contain 'inputs.mem' } it { should contain 'inputs.net' } it { should contain 'inputs.swap' } it { should contain 'inputs.system' } end describe service('telegraf') do it { should be_enabled } it { should be_running } end
{ "content_hash": "e097ca20c9aacb9c68f7333ade3c3ca9", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 62, "avg_line_length": 26.15909090909091, "alnum_prop": 0.6568201563857515, "repo_name": "Plork/telegraf-cookbook", "id": "ca96cb361bf779c6f824b59ca5666f846c534cf7", "size": "1151", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/integration/default/serverspec/default_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "17256" } ], "symlink_target": "" }
import { localize } from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { basename } from 'vs/base/common/paths'; import { IDisposable, dispose, IReference } from 'vs/base/common/lifecycle'; import * as strings from 'vs/base/common/strings'; import { URI } from 'vs/base/common/uri'; import { defaultGenerator } from 'vs/base/common/idGenerator'; import { Range, IRange } from 'vs/editor/common/core/range'; import { Location, LocationLink } from 'vs/editor/common/modes'; import { ITextModelService, ITextEditorModel } from 'vs/editor/common/services/resolverService'; import { Position } from 'vs/editor/common/core/position'; export class OneReference { readonly id: string; private readonly _onRefChanged = new Emitter<this>(); readonly onRefChanged: Event<this> = this._onRefChanged.event; constructor( readonly parent: FileReferences, private _range: IRange ) { this.id = defaultGenerator.nextId(); } get uri(): URI { return this.parent.uri; } get range(): IRange { return this._range; } set range(value: IRange) { this._range = value; this._onRefChanged.fire(this); } getAriaMessage(): string { return localize( 'aria.oneReference', "symbol in {0} on line {1} at column {2}", basename(this.uri.fsPath), this.range.startLineNumber, this.range.startColumn ); } } export class FilePreview implements IDisposable { constructor( private readonly _modelReference: IReference<ITextEditorModel> ) { } dispose(): void { dispose(this._modelReference); } preview(range: IRange, n: number = 8): { before: string; inside: string; after: string } | undefined { const model = this._modelReference.object.textEditorModel; if (!model) { return undefined; } const { startLineNumber, startColumn, endLineNumber, endColumn } = range; const word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n }); const beforeRange = new Range(startLineNumber, word.startColumn, startLineNumber, startColumn); const afterRange = new Range(endLineNumber, endColumn, endLineNumber, Number.MAX_VALUE); const ret = { before: model.getValueInRange(beforeRange).replace(/^\s+/, strings.empty), inside: model.getValueInRange(range), after: model.getValueInRange(afterRange).replace(/\s+$/, strings.empty) }; return ret; } } export class FileReferences implements IDisposable { private _children: OneReference[]; private _preview?: FilePreview; private _resolved: boolean; private _loadFailure: any; constructor(private readonly _parent: ReferencesModel, private _uri: URI) { this._children = []; } get id(): string { return this._uri.toString(); } get parent(): ReferencesModel { return this._parent; } get children(): OneReference[] { return this._children; } get uri(): URI { return this._uri; } get preview(): FilePreview | undefined { return this._preview; } get failure(): any { return this._loadFailure; } getAriaMessage(): string { const len = this.children.length; if (len === 1) { return localize('aria.fileReferences.1', "1 symbol in {0}, full path {1}", basename(this.uri.fsPath), this.uri.fsPath); } else { return localize('aria.fileReferences.N', "{0} symbols in {1}, full path {2}", len, basename(this.uri.fsPath), this.uri.fsPath); } } resolve(textModelResolverService: ITextModelService): Promise<FileReferences> { if (this._resolved) { return Promise.resolve(this); } return Promise.resolve(textModelResolverService.createModelReference(this._uri).then(modelReference => { const model = modelReference.object; if (!model) { modelReference.dispose(); throw new Error(); } this._preview = new FilePreview(modelReference); this._resolved = true; return this; }, err => { // something wrong here this._children = []; this._resolved = true; this._loadFailure = err; return this; })); } dispose(): void { if (this._preview) { this._preview.dispose(); this._preview = undefined; } } } export class ReferencesModel implements IDisposable { private readonly _disposables: IDisposable[]; readonly groups: FileReferences[] = []; readonly references: OneReference[] = []; readonly _onDidChangeReferenceRange = new Emitter<OneReference>(); readonly onDidChangeReferenceRange: Event<OneReference> = this._onDidChangeReferenceRange.event; constructor(references: LocationLink[]) { this._disposables = []; // grouping and sorting references.sort(ReferencesModel._compareReferences); let current: FileReferences | undefined; for (let ref of references) { if (!current || current.uri.toString() !== ref.uri.toString()) { // new group current = new FileReferences(this, ref.uri); this.groups.push(current); } // append, check for equality first! if (current.children.length === 0 || !Range.equalsRange(ref.range, current.children[current.children.length - 1].range)) { let oneRef = new OneReference(current, ref.targetSelectionRange || ref.range); this._disposables.push(oneRef.onRefChanged((e) => this._onDidChangeReferenceRange.fire(e))); this.references.push(oneRef); current.children.push(oneRef); } } } get empty(): boolean { return this.groups.length === 0; } getAriaMessage(): string { if (this.empty) { return localize('aria.result.0', "No results found"); } else if (this.references.length === 1) { return localize('aria.result.1', "Found 1 symbol in {0}", this.references[0].uri.fsPath); } else if (this.groups.length === 1) { return localize('aria.result.n1', "Found {0} symbols in {1}", this.references.length, this.groups[0].uri.fsPath); } else { return localize('aria.result.nm', "Found {0} symbols in {1} files", this.references.length, this.groups.length); } } nextOrPreviousReference(reference: OneReference, next: boolean): OneReference { let { parent } = reference; let idx = parent.children.indexOf(reference); let childCount = parent.children.length; let groupCount = parent.parent.groups.length; if (groupCount === 1 || next && idx + 1 < childCount || !next && idx > 0) { // cycling within one file if (next) { idx = (idx + 1) % childCount; } else { idx = (idx + childCount - 1) % childCount; } return parent.children[idx]; } idx = parent.parent.groups.indexOf(parent); if (next) { idx = (idx + 1) % groupCount; return parent.parent.groups[idx].children[0]; } else { idx = (idx + groupCount - 1) % groupCount; return parent.parent.groups[idx].children[parent.parent.groups[idx].children.length - 1]; } } nearestReference(resource: URI, position: Position): OneReference | undefined { const nearest = this.references.map((ref, idx) => { return { idx, prefixLen: strings.commonPrefixLength(ref.uri.toString(), resource.toString()), offsetDist: Math.abs(ref.range.startLineNumber - position.lineNumber) * 100 + Math.abs(ref.range.startColumn - position.column) }; }).sort((a, b) => { if (a.prefixLen > b.prefixLen) { return -1; } else if (a.prefixLen < b.prefixLen) { return 1; } else if (a.offsetDist < b.offsetDist) { return -1; } else if (a.offsetDist > b.offsetDist) { return 1; } else { return 0; } })[0]; if (nearest) { return this.references[nearest.idx]; } return undefined; } dispose(): void { dispose(this.groups); dispose(this._disposables); this.groups.length = 0; this._disposables.length = 0; } private static _compareReferences(a: Location, b: Location): number { const auri = a.uri.toString(); const buri = b.uri.toString(); if (auri < buri) { return -1; } else if (auri > buri) { return 1; } else { return Range.compareRangesUsingStarts(a.range, b.range); } } }
{ "content_hash": "1994e63e257cc4155b418cb676fae910", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 131, "avg_line_length": 27.46315789473684, "alnum_prop": 0.6818704484476811, "repo_name": "cleidigh/vscode", "id": "da7677a01d54e9ff7cd68bd295a85ef6b6e802b6", "size": "8178", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/vs/editor/contrib/referenceSearch/referencesModel.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5385" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "488" }, { "name": "C++", "bytes": "1072" }, { "name": "CSS", "bytes": "478388" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "Dockerfile", "bytes": "425" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "652" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "42593" }, { "name": "Inno Setup", "bytes": "165483" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "856795" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "2080" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "PHP", "bytes": "998" }, { "name": "Perl", "bytes": "857" }, { "name": "Perl 6", "bytes": "1065" }, { "name": "PowerShell", "bytes": "4774" }, { "name": "Python", "bytes": "2405" }, { "name": "R", "bytes": "362" }, { "name": "Roff", "bytes": "351" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "532" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "16893" }, { "name": "Swift", "bytes": "284" }, { "name": "TypeScript", "bytes": "20083090" }, { "name": "Visual Basic", "bytes": "893" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- BSD 2-Clause License Copyright (c) 2016-2017, Jochen Seeber All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 HOLDER 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. --> <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd"> <module name="Checker"> <property name="severity" value="warning"/> <property name="charset" value="UTF-8"/> <property name="fileExtensions" value="java, properties, xml"/> <module name="SuppressionFilter"> <property name="file" value="${config_loc}/suppressions.xml"/> <property name="optional" value="true"/> </module> <module name="FileTabCharacter"> <property name="severity" value="error"/> <property name="eachLine" value="true"/> </module> <module name="TreeWalker"> <module name="LineLength"> <property name="severity" value="warning"/> <property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://|@see"/> <property name="max" value="120"/> </module> <module name="JavadocMethod"> <property name="severity" value="warning"/> <property name="allowMissingJavadoc" value="true"/> <property name="allowMissingParamTags" value="true"/> <property name="allowMissingPropertyJavadoc" value="true"/> <property name="allowMissingReturnTag" value="true"/> <property name="allowMissingThrowsTags" value="true"/> <property name="minLineCount" value="-1"/> <property name="suppressLoadErrors" value="false"/> </module> </module> </module>
{ "content_hash": "ee0dc620bd085fbbc3e251ca8f78ad8a", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 135, "avg_line_length": 68.09302325581395, "alnum_prop": 0.6977459016393442, "repo_name": "jochenseeber/gradle-project-config", "id": "349cf6ea05bd6b4d8983a64f929fc971911eef42", "size": "2928", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/main/resources/me/seeber/gradle/validation/checkstyle/checkstyle_test.xml", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Groovy", "bytes": "33199" }, { "name": "Java", "bytes": "319885" } ], "symlink_target": "" }
package com.streamsets.pipeline.stage.destination.kafka; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ConfigGroups; import com.streamsets.pipeline.api.FieldSelectorModel; import com.streamsets.pipeline.api.GenerateResourceBundle; import com.streamsets.pipeline.api.StageDef; import com.streamsets.pipeline.api.Target; import com.streamsets.pipeline.api.ValueChooserModel; import com.streamsets.pipeline.config.CharsetChooserValues; import com.streamsets.pipeline.config.CsvHeader; import com.streamsets.pipeline.config.CsvHeaderChooserValues; import com.streamsets.pipeline.config.CsvMode; import com.streamsets.pipeline.config.CsvModeChooserValues; import com.streamsets.pipeline.config.DataFormat; import com.streamsets.pipeline.config.JsonMode; import com.streamsets.pipeline.config.JsonModeChooserValues; import com.streamsets.pipeline.configurablestage.DTarget; import com.streamsets.pipeline.lib.el.RecordEL; import com.streamsets.pipeline.lib.el.StringEL; import java.util.Map; @StageDef( version = 1, label = "Kafka Producer", description = "Writes data to Kafka", icon = "kafka.png") @ConfigGroups(value = Groups.class) @GenerateResourceBundle public class KafkaDTarget extends DTarget { private static final String KAFKA_PRODUCER_OPTIONS_DEFAULT = "{" + " \"queue.buffering.max.ms\" : \"5000\", " + " \"message.send.max.retries\" : \"10\", " + " \"retry.backoff.ms\" : \"1000\" " + "}"; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "localhost:9092", label = "Broker URI", description = "Comma-separated list of URIs for brokers that write to the topic. Use the format " + "<HOST>:<PORT>. To ensure a connection, enter as many as possible.", displayPosition = 10, group = "KAFKA" ) public String metadataBrokerList; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "false", label = "Runtime Topic Resolution", description = "Select topic at runtime based on the field values in the record", displayPosition = 15, group = "KAFKA" ) public boolean runtimeTopicResolution; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "${record:value('/topic')}", label = "Topic Expression", description = "An expression that resolves to the name of the topic to use", displayPosition = 20, elDefs = {RecordEL.class}, group = "KAFKA", evaluation = ConfigDef.Evaluation.EXPLICIT, dependsOn = "runtimeTopicResolution", triggeredByValue = "true" ) public String topicExpression; @ConfigDef( required = true, type = ConfigDef.Type.TEXT, lines = 5, defaultValue = "*", label = "Topic White List", description = "A comma-separated list of valid topic names. " + "Records with invalid topic names are treated as error records. " + "'*' indicates that all topic names are allowed.", displayPosition = 23, group = "KAFKA", dependsOn = "runtimeTopicResolution", triggeredByValue = "true" ) public String topicWhiteList; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "topicName", label = "Topic", description = "", displayPosition = 25, group = "KAFKA", dependsOn = "runtimeTopicResolution", triggeredByValue = "false" ) public String topic; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "ROUND_ROBIN", label = "Partition Strategy", description = "Strategy to select a partition to write to", displayPosition = 30, group = "KAFKA" ) @ValueChooserModel(PartitionStrategyChooserValues.class) public PartitionStrategy partitionStrategy; @ConfigDef( required = false, type = ConfigDef.Type.STRING, defaultValue = "${0}", label = "Partition Expression", description = "Determines the partition key to use with default kafka partitioner class in case of 'Default Partition Strategy'. In case of 'Expression Partition Strategy' it determines the partition number", displayPosition = 40, group = "KAFKA", dependsOn = "partitionStrategy", triggeredByValue = {"EXPRESSION", "DEFAULT"}, elDefs = {RecordEL.class}, evaluation = ConfigDef.Evaluation.EXPLICIT ) public String partition; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "SDC_JSON", label = "Data Format", description = "", displayPosition = 50, group = "KAFKA" ) @ValueChooserModel(ProducerDataFormatChooserValues.class) public DataFormat dataFormat; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "UTF-8", label = "Messages Charset", displayPosition = 51, group = "KAFKA", dependsOn = "dataFormat", triggeredByValue = {"TEXT", "JSON", "DELIMITED", "XML", "LOG"} ) @ValueChooserModel(CharsetChooserValues.class) public String charset; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "false", label = "One Message per Batch", description = "Generates a single Kafka message with all records in the batch", displayPosition = 55, group = "KAFKA" ) public boolean singleMessagePerBatch; /******** For DELIMITED Content ***********/ @ConfigDef( required = false, type = ConfigDef.Type.MODEL, defaultValue = "CSV", label = "Delimiter Format", description = "", displayPosition = 100, group = "DELIMITED", dependsOn = "dataFormat", triggeredByValue = "DELIMITED" ) @ValueChooserModel(CsvModeChooserValues.class) public CsvMode csvFileFormat; @ConfigDef( required = false, type = ConfigDef.Type.MAP, defaultValue = KAFKA_PRODUCER_OPTIONS_DEFAULT, label = "Kafka Configuration", description = "Additional Kafka properties to pass to the underlying Kafka producer", displayPosition = 60, group = "KAFKA" ) public Map<String, String> kafkaProducerConfigs; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "NO_HEADER", label = "Header Line", description = "", displayPosition = 110, group = "DELIMITED", dependsOn = "dataFormat", triggeredByValue = "DELIMITED" ) @ValueChooserModel(CsvHeaderChooserValues.class) public CsvHeader csvHeader; @ConfigDef( required = false, type = ConfigDef.Type.BOOLEAN, defaultValue = "true", label = "Remove New Line Characters", description = "Replaces new lines characters with white spaces", displayPosition = 120, group = "DELIMITED", dependsOn = "dataFormat", triggeredByValue = "DELIMITED" ) public boolean csvReplaceNewLines; /******** For JSON *******/ @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "MULTIPLE_OBJECTS", label = "JSON Content", description = "", displayPosition = 200, group = "JSON", dependsOn = "dataFormat", triggeredByValue = "JSON" ) @ValueChooserModel(JsonModeChooserValues.class) public JsonMode jsonMode; /******** For TEXT Content ***********/ @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "/", label = "Text Field Path", description = "Field to write data to Kafka", displayPosition = 120, group = "TEXT", dependsOn = "dataFormat", triggeredByValue = "TEXT", elDefs = {StringEL.class} ) @FieldSelectorModel(singleValued = true) public String textFieldPath; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "false", label = "Empty Line If No Text", description = "", displayPosition = 310, group = "TEXT", dependsOn = "dataFormat", triggeredByValue = "TEXT" ) public boolean textEmptyLineIfNull; /******** For AVRO Content ***********/ @ConfigDef( required = true, type = ConfigDef.Type.TEXT, defaultValue = "", label = "Avro Schema", description = "Optionally use the runtime:loadResource function to use a schema stored in a file", displayPosition = 320, group = "AVRO", dependsOn = "dataFormat", triggeredByValue = {"AVRO"}, mode = ConfigDef.Mode.JSON ) public String avroSchema; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "true", label = "Include Schema", description = "Includes Avro schema in the kafka message", displayPosition = 330, group = "AVRO", dependsOn = "dataFormat", triggeredByValue = "AVRO" ) public boolean includeSchema; /******** For Binary Content ***********/ @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "/", label = "Binary Field Path", description = "Field to write data to Kafka", displayPosition = 120, group = "BINARY", dependsOn = "dataFormat", triggeredByValue = "BINARY", elDefs = {StringEL.class} ) @FieldSelectorModel(singleValued = true) public String binaryFieldPath; @Override protected Target createTarget() { return new KafkaTarget(metadataBrokerList, runtimeTopicResolution, topic, topicExpression, topicWhiteList, partitionStrategy, partition, dataFormat, charset, singleMessagePerBatch, kafkaProducerConfigs, csvFileFormat, csvHeader, csvReplaceNewLines, jsonMode, textFieldPath, textEmptyLineIfNull, avroSchema, includeSchema, binaryFieldPath); } }
{ "content_hash": "fc7cd59f8a6ca5ae4406a796980432c7", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 212, "avg_line_length": 29.771604938271604, "alnum_prop": 0.6743727970143064, "repo_name": "kiritbasu/datacollector", "id": "dc14b19e19f07952c97526144faa53c951875529", "size": "10452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kafka_target-protolib/src/main/java/com/streamsets/pipeline/stage/destination/kafka/KafkaDTarget.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "92442" }, { "name": "HTML", "bytes": "290548" }, { "name": "Java", "bytes": "7147264" }, { "name": "JavaScript", "bytes": "750105" }, { "name": "Python", "bytes": "28016" }, { "name": "Shell", "bytes": "37595" } ], "symlink_target": "" }
<?php if ('Γ‘' != "\xc3\xa1") { // the language files must be saved as UTF-8 (without BOM) throw new \Exception('The language file ' . __FILE__ . ' is damaged, it must be saved UTF-8 encoded!'); } return array( '%type% Import' => '%type% Import', '- delete field -' => '- Feld lΓΆschen -', '- new extra field -' => '- neues Zusatzfeld -', '- new group -' => '- neue Gruppe -', 'About' => '?', 'Account type' => 'Benutzerkonto, Typ', 'Activate the desired account role' => 'Das beantragte Benutzerrecht aktivieren', 'Add a image' => 'Ein Bild hinzufΓΌgen', 'Add a new group' => 'Eine neue Gruppe hinzufΓΌgen', 'Add a subscription' => 'Eine Anmeldung hinzufΓΌgen', 'Admin Status' => 'Administrator Status', 'At day x of month must be greater than zero and less than 28.' => 'Der Wert fΓΌr AusfΓΌhren am x. Tag des Monats muss grâßer als Null und kleiner als 28 sein.', 'At least we need one communication channel, so please tell us a email address, phone or a URL' => 'Wir benΓΆtigen mindestens einen Kommunikationsweg, bitte nennen Sie uns eine E-Mail Adresse, Telefonummer oder die URL der Homepage.', 'At the first' => 'Am ersten', 'At the first and third' => 'Am ersten und dritten', 'At the fourth' => 'Am vierten', 'At the last' => 'Am letzten', 'At the moment there are no proposed events' => 'Momentan liegen keine VeranstaltungsvorschlΓ€ge vor.', 'At the moment there are no subscriptions for your events' => 'Momentan liegen keine Anmeldungen zu Ihren Veranstaltungen vor.', 'At the second' => 'Am zweiten', 'At the second and fourth' => 'Am zweiten und vierten', 'At the second and last' => 'Am zweiten und letzten', 'At the third' => 'Am dritten', 'but not at %dates%.' => ', jedoch nicht am %dates%.', 'by copying from a existing event' => 'durch Kopieren einer existierenden Veranstaltung', 'by selecting a event group' => 'durch Auswahl einer Veranstaltungsgruppe', 'Canceled' => 'Wiederrufen', 'Change account rights' => 'Γ„nderung der Benutzerrechte', 'Change Event configuration' => 'Event Konfiguration Γ€ndern', 'Checking the GUID identifier' => 'ÜberprΓΌfung der GUID Kennung', 'CHOICE_ADMIN_ACCOUNT' => 'Ich mΓΆchte als Administrator alle Veranstaltungen bearbeiten kΓΆnnen', 'CHOICE_LOCATION_ACCOUNT' => 'Ich vertrete einen Veranstaltungsort und mΓΆchte Veranstaltungen bearbeiten kΓΆnnen, die dort stattfinden', 'CHOICE_ORGANIZER_ACCOUNT' => 'Ich vertrete einen Veranstalter, Verein oder eine Organisation und mΓΆchte deren Veranstaltungen bearbeiten kΓΆnnen', 'CHOICE_SUBMITTER_ACCOUNT' => 'Ich mΓΆchte Veranstaltungen bearbeiten kΓΆnnen, die ich ΓΌbermittelt habe', 'Click to subscribe' => 'Anklicken um sich zu dieser Veranstaltung anzumelden', 'closed' => 'geschlossen', 'Comments handling' => 'Kommentar Behandlung', 'company, institution or association' => 'Firma, Institution oder Verein', 'Confirmed' => 'BestΓ€tigt', 'Costs' => 'TeilnahmegebΓΌhr', 'Create a new category' => 'Eine neue Kategorie anlegen', 'Create a new event' => 'Eine neue Veranstaltung erstellen', 'Create a new extra field' => 'Ein neues Zusatzfeld anlegen', 'Create a new Location record' => 'Einen neuen Veranstaltungsort anlegen', 'Create a new Organizer record' => 'Eine neue Veranstalter Adresse anlegen', 'Create a new recurring event with the ID %event_id%' => 'Neue sich wiederholende Veranstaltung mit der ID %event_id% angelegt.', 'Create a new title' => 'Eine neue Schlagzeile anlegen', 'Create event' => 'Veranstaltung anlegen', 'Create or edit a event' => 'Veranstaltung anlegen oder bearbeiten', 'Created the tag %tag% in Contact.' => 'Das Schlagwort %tag% wurde in Contact angelegt.', 'Daily recurring' => 'TΓ€gliche Wiederholung', 'Date' => 'Datum', 'Date and Time' => 'Datum und Uhrzeit', 'Days' => 'Tage', 'Day sequence' => 'Alle x-Tage wiederholen', 'Day type' => 'Typ', 'Deadline' => 'Anmeldeschluß', 'Delete this image' => 'Dieses Bild lΓΆschen', 'Description long' => 'Beschreibung', 'Description short' => 'Zusammenfassung', 'Description title' => 'Titel', 'Detected a kitEvent installation (Release: %release%) with %count% active or locked events.' => 'Es wurde eine kitEvent Installation (Release: %release%) mit %count% Veranstaltungen gefunden, die importiert werden kΓΆnnen.', 'Do not know how to handle the recurring type <b>%type%</b>.' => 'Weiß nicht, wie der Wiederholungstyp <strong>%type%</strong> zu handhaben ist.', 'Do not publish the event' => 'Veranstaltung nicht verΓΆffentlichen', 'Don\'t know how to handle the month type %type%' => 'Unbekannter Monatstyp %type%', 'Don\'t know how to handle the recurring type %type%.' => 'Unbekannter Wiederholungstyp %type%.', 'Don\'t know how to handle the year type %type%' => 'Weiß nicht, wie ich den Jahrestyp %type% behandeln soll!', 'Edit event' => 'Veranstaltung bearbeiten', 'email usage' => 'Verwendung', 'event' => 'Veranstaltung', 'Event' => 'Veranstaltung', 'Event Administration - About' => 'Event Verwaltung - Über', 'Event Administration - Copy Event' => 'Event Administration - Veranstaltung kopieren', 'Event Administration - Create or edit event' => 'Event Administration - Veranstaltung erstellen oder bearbeiten', 'Event costs' => 'Eintrittspreis', 'Event date from' => 'Beginn der Veranstaltung', 'Event date to' => 'Ende der Veranstaltung', 'Event deadline' => 'Anmeldeschluß', 'Event group' => 'Gruppe', 'Event id' => 'Veranstaltung ID', 'Event ID' => 'ID', 'Event list' => 'Veranstaltungen, Übersicht', 'Event location' => 'Veranstaltungsort', 'Event management suite for freelancers and organizers' => 'Veranstaltungen, Konzerte, Seminare oder Vorlesungen verwalten und organisieren', 'Event participants confirmed' => 'Tln. best.', 'Event participants max' => 'max. Tln.', 'Event publish from' => 'VerΓΆffentlichen ab', 'Event publish to' => 'VerΓΆffentlichen bis', 'Event status' => 'Status', 'Event successfull updated' => 'Die Veranstaltung wurde aktualisiert', 'Event Title' => 'Titel der Veranstaltung', 'Event url' => 'Veranstaltungs URL', 'Exclude dates' => 'Daten ausschließen', 'Extra field' => 'Zusatzfeld', 'Float' => 'Dezimalzahl', 'free of charge' => 'kostenlos', 'Google Map' => 'Google Map', 'Group' => 'Gruppe', 'Group description' => 'Beschreibung', 'Group extra fields' => 'Zusatzfelder', 'Group id' => 'ID', 'Group location contact tags' => 'Veranstaltungsorte', 'Group name' => 'Gruppen Bezeichner', 'Group name (translated)' => 'Gruppen Bezeichner (ΓΌbersetzt)', 'Group organizer contact tags' => 'Veranstalter', 'Group participant contact tags' => 'Teilnehmer', 'Group status' => 'Status', 'Groups' => 'Gruppen', 'Hello %name%' => 'Hallo %name%', 'I accept the <a href="%url%" target="_blank">general terms and conditions</a>' => 'Ich akzeptiere die <a href="%url%" target="_blank">AGB</a>', 'I really don\'t know the Organizer' => 'Der Veranstalter ist mir leider nicht bekannt', 'If you are prompted to login, please use your username and password' => 'Wenn Sie aufgefordert werden sich anzumelden, verwenden Sie bitte Ihren Benutzernamen und Ihr Passwort', 'Ignore existing comments' => 'Existierende Kommentare werden nicht ΓΌbernommen', 'Import events from kitEvent' => 'Veranstaltungen aus kitEvent importieren', 'Information about the Event extension' => 'Informationen ΓΌber die Event Extension', 'Integer' => 'Ganzzahl', 'Invalid key => value pair in the set[] parameter!' => 'UngΓΌltiges SchlΓΌssel => Wert Paar fΓΌr den set[] Parameter!', 'Invalid login' => 'UngΓΌltiger Login, Benutzername oder Passwort falsch', 'Invalid submission, please try again' => 'UngΓΌltige Übermittlung, bitte versuchen Sie es erneut!', 'It is not allowed that the event start in the past!' => 'Der Veranstaltungsbeginn darf nicht in der Vergangenheit liegen!', 'List of actual submitted proposes for events' => 'Übersicht ΓΌber die aktuellen VorschlΓ€ge zu Veranstaltungen', 'List of all active events' => 'Übersicht ΓΌber alle aktiven Veranstaltungen', 'List of all available contacts (Organizer, Locations, Participants)' => 'Übersicht ΓΌber alle verfΓΌgbaren Kontakte (Veranstalter, Orte, Teilnehmer)', 'List of all available event groups' => 'Übersicht ΓΌber alle verfΓΌgbaren Veranstaltungsgruppen', 'List of all subscriptions for events' => 'Übersicht ΓΌber alle Anmeldungen zu Veranstaltungen', 'List single dates in format <b>%format%</b> separated by comma to exclude them from recurring' => 'Schließen Sie einzelne Daten im Format <b>%format%</b> durch ein Komma getrennt von der Sequenz aus.', 'Location' => 'Veranstaltungsort', 'Location ID' => 'Veranstaltungsort ID', 'Long description' => 'Langbeschreibung', 'Message from the kitFramework Event application' => 'Mitteilung von kitFramework Event', 'Migrate data of a kitEvent installation into Event' => 'Veranstaltungsdaten von einer kitEvent Installation in Event ΓΌbernehmen', 'Missing a valid Event ID!' => 'Vermisse eine gΓΌltige Veranstaltungs ID!', 'Month pattern day' => 'Tag', 'Month pattern day view' => 'Wochentag', 'Month pattern sequence' => 'Wiederholung', 'Month pattern type' => 'Typ', 'Month sequence day' => 'Tag', 'Month sequence day view' => 'Wochentag', 'Month sequence month' => 'Monat', 'Month type' => 'Typ', 'month_pattern_type' => 'Typ', 'Monthly recurring' => 'Monatliche Wiederholung', 'natural person' => 'NatΓΌrliche Person', 'New event id' => 'ID', 'New location' => 'Neuer Veranstaltungsort', 'New organizer' => 'Neuer Veranstalter', 'New password' => 'Neues Passwort', 'Next event dates' => 'Die nΓ€chsten Veranstaltungstermine', 'No image selected, nothing to do.' => 'Es wurde keine Abbildung ausgewΓ€hlt.', 'No recurring event' => 'Keinen Serientermin festlegen', 'No recurring event type selected' => 'Es wurde kein Serientermin Typ ausgewΓ€hlt.', 'No results for this filter!' => 'Dieser Filter lieferte kein Ergebnis!', 'Organizer' => 'Veranstalter', 'Organizer ID' => 'Veranstalter ID', 'out of' => 'von', 'Parent event id' => 'ID', 'Participant' => 'Teilnehmer', 'Participants canceled' => 'Teilnehmer, storniert', 'Participants confirmed' => 'Teilnehmer, bestΓ€tigt', 'Participants maximum' => 'Teilnehmer, max. Anzahl', 'Participants pending' => 'Teilnehmer, unbestΓ€tigt', 'Participants total' => 'Teilnehmer, angemeldet', 'Participants, maximum' => 'Teilnehmer, max.', 'Participants, total' => 'Teilnehmer, insgesamt', 'Pass comments from parent' => 'Kommentare werden aktiv von der ursprΓΌnglichen Veranstaltung vererbt', 'Permalink successfull changed' => 'Der Permanent Link wurde erfolgreich geΓ€ndert', 'personal email address' => 'persΓΆnliche E-Mail Adresse', 'Pictures' => 'Bilder', 'Please check the event data and use one of the following action links' => 'Bitte prΓΌfen Sie die Angaben zu der Veranstaltung und verwenden Sie anschließend einen der folgenden Aktions-Links', 'Please define a permanent link in config.event.json. Without this link Event can not create permanent links or respond to user requests.' => 'Bitte definieren Sie einen permanenten Link in der config.event.json. Ohne diesen Link kann Event keine Verweise auf Veranstaltungen erzeugen oder auf Anfragen von Veranstaltungsteilnehmern reagieren.', 'Please determine the handling for the comments.' => 'Bitte legen Sie die Handhabung fΓΌr die Kommentare fest.', 'Please feel free to order a account.' => 'Fordern Sie ein Benutzerkonto an', 'Please search for for a location or select the checkbox to create a new one.' => 'Bitte suchen Sie nach einem Veranstaltungsort oder haken Sie die Checkbox an um einen neuen Veranstaltungsort anzulegen.', 'Please search for for a organizer or select the checkbox to create a new one.' => 'Bitte suchen Sie nach einem Veranstalter oder haken Sie die Checkbox an um einen neuen Veranstalter anzulegen.', 'Please search for the contact you want to subscribe to an event or add a new contact, if you are shure that the person does not exists in Contacts.' => 'Bitte suchen Sie nach dem Kontakt, den Sie zu einer Veranstaltung anmelden mΓΆchten. FΓΌgen Sie einen neuen Kontakt hinzu, falls dieser noch nicht existiert.', 'Please search for the event you want to copy data from.' => 'Bitte suchen Sie nach der Veranstaltung, die Sie kopieren mΓΆchten.', 'Please select action' => 'Bitte wΓ€hlen Sie eine Aktion', 'Please select at least one weekday!' => 'Bitte wΓ€hlen Sie mindestens einen Wochentag aus!', 'Please select at minimum one tag for the %type%.' => 'Bitte legen Sie mindestens eine Markierung fΓΌr %type% fest!', 'Please select the event you want to copy into a new one' => 'WΓ€hlen Sie die Veranstaltung aus, deren Daten fΓΌr eine neue Veranstaltung ΓΌbernommen werden sollen.', 'Please type in a long description with %minimum% characters at minimum.' => 'Bitte geben Sie eine Langbeschreibung mit einer LΓ€nge von mindestens %minimum% Zeichen ein.', 'Please type in a short description with %minimum% characters at minimum.' => 'Bitte geben Sie eine Kurzbeschreibung mit einer LΓ€nge von mindestens %minimum% Zeichen ein.', 'Please type in a title with %minimum% characters at minimum.' => 'Bitte geben Sie einen Titel mit einer LΓ€nge von mindestens %minimum% Zeichen ein.', 'Please use the parameter set[] to set a configuration value.' => 'Bitte verwenden Sie den Paramter set[] um einen Konfigurationswert zu setzen!', 'Proposed event: %event%' => 'Vorgeschlagene Veranstaltung: %event%', 'Proposes' => 'VorschlΓ€ge', 'Publish' => 'VerΓΆffentlichen', 'Publish from' => 'VerΓΆffentlichen ab', 'Publish the event' => 'Veranstaltung verΓΆffentlichen', 'Publish to' => 'VerΓΆffentlichen bis', 'Received request' => 'Anfrage erhalten', 'Recurring date end' => 'Letzte Wiederholung', 'Recurring event' => 'Serientermin', 'Recurring id' => 'ID', 'Recurring type' => 'Typ', 'Redirect to the parent event ID!' => 'Umgeleitet auf die ursprΓΌngliche Veranstaltungs ID!', 'regular email address of a company, institution or association' => 'offizielle E-Mail Adresse einer Firma, Einrichtung oder eines Verein', 'Reject the desired account role' => 'Das gewΓΌnschte Benutzerrecht zurΓΌckweisen', 'Reject this event' => 'Veranstaltung ablehnen', 'Remark' => 'Bemerkung', 'Repeat at workdays' => 'An Werktagen wiederholen', 'Repeat each x-days' => 'Alle x-Tage wiederholen', 'Repeat x-month must be greater than zero and less then 13.' => 'Der Wert fΓΌr Wiederhole jeden x. Monat muß grâßer als Null und kleiner als 13 sein.', 'Rewrite the the recurring event' => 'Wiederholende Veranstaltung umschreiben', 'ROLE_EVENT_ADMIN' => 'Benutzerrecht: Veranstaltungen als Administrator bearbeiten', 'ROLE_EVENT_LOCATION' => 'Benutzerrecht: Veranstaltungen bearbeiten, die diesem Veranstaltungsort zugewiesen sind', 'ROLE_EVENT_ORGANIZER' => 'Benutzerrecht: Veranstaltungen bearbeiten, die von diesem Veranstalter zugewiesen sind', 'ROLE_EVENT_SUBMITTER' => 'Benutzerrecht: Veranstaltungen bearbeiten, die von diesem Benutzer vorgeschlagen wurden', 'Search event' => 'Veranstaltung suchen', 'Search Location' => 'Veranstaltungsort suchen', 'Search Organizer' => 'Veranstalter suchen', 'second' => 'zweiten', 'second_fourth' => 'zweiten und vierten', 'second_last' => 'zweiten und letzten', 'Select account type' => 'Kontotyp wΓ€hlen', 'Select event' => 'Veranstaltung auswΓ€hlen', 'Select event group' => 'Veranstaltungsgruppe auswΓ€hlen', 'Select group' => 'Gruppe wΓ€hlen', 'Select type' => 'Typ auswΓ€hlen', 'Settings' => 'Einstellungen', 'Short description' => 'Kurzbeschreibung', 'Show detailed information' => 'Detailierte Informationen anzeigen', 'Showing' => 'Zeige', 'Skipped kitEvent ID %event_id%: Can not determine the Event Group ID for the kitEvent Group ID %group_id%.' => 'kitEvent ID %event_id% ΓΌbersprungen: Kann die Veranstaltungs Gruppen ID fΓΌr die ID %group_id% nicht ermitteln!', 'Skipped kitEvent ID %event_id%: Can not find the contact ID for the KIT ID %kit_id%.' => 'kitEvent ID %event_id% ΓΌbersprungen: Konnte die zugehΓΆrige Contact ID fΓΌr die KIT ID %kit_id% nicht finden.', 'Skipped kitEvent ID %event_id%: Can not read the items for this event.' => 'kitEvent ID %event_id% ΓΌbersprungen: Kann die EintrΓ€ge zu dieser Veranstaltung nicht lesen.', 'Skipped kitEvent ID %event_id%: No valid value in %field%' => 'kitEvent ID <b>%event_id%</b> ΓΌbersprungen: UngΓΌltiger Wert in Feld %field%', 'Skipped kitEvent ID %event_id%: This entry exists already as Event ID %id%.' => 'kitEvent ID %event_id% ΓΌbersprungen: Dieser Eintrag existiert bereit als Event ID %id%', 'Start a new search' => 'Eine neue Suche starten', 'Start import from kitEvent' => 'Import aus kitEvent starten', 'Start search' => 'Suche starten', 'Submit subscription' => 'Anmeldung ΓΌbermitteln', 'Submitter ID' => 'Übermittler ID', 'Submitter Status' => 'Übermittler Status', 'Subscribe' => 'Anmelden', 'Subscribe to event' => 'Zu der Veranstaltung anmelden', 'Subscriber' => 'Anmeldender', 'Subscription id' => 'ID', 'Subscriptions' => 'Anmeldungen', 'subscriptions' => 'Anmeldungen', 'Successfull inserted a recurring event' => 'Es wurden erfolgreich sich wiederholende Veranstaltungen angelegt.', 'Text - 256 characters' => 'Text - max. 256 Zeichen', 'Text - HTML' => 'Text - HTML formatiert', 'Text - plain' => 'Text - unformatiert', 'Thank you for proposing the following event' => 'Vielen Dank fΓΌr Ihren Veranstaltungsvorschlag', 'Thank you for your subscription, we have send you a receipt at your email address.' => 'Vielen Dank fΓΌr Ihre Anmeldung, wir haben Ihnen eine BestΓ€tigung an Ihre E-Mail Adresse gesendet.', 'Thank you for your subscription. We have send you an email, please use the submitted confirmation link to confirm your email address and to activate your subscription!' => 'Vielen Dank fΓΌr Ihre Anmeldung. Wir haben Ihnen eine E-Mail geschickt, bitte benutzen Sie den enthaltenen BestΓ€tigungslink um Ihre E-Mail Adresse zu bestΓ€tigen und die Anmeldung zu aktivieren.', 'Thank you, %name%' => 'Vielen Dank, %name%', 'Thank you, one of the admins will approve your request and contact you.' => 'Vielen Dank, ein Administrator wird Ihre Anfrage prΓΌfen und sich mit Ihnen in Verbindung setzen.', 'The \'limit\' filter must be a integer value.' => 'Der Parameter <em>limit</em> muss eine Ganzzahl sein.', 'The action link was successfull executed' => 'Der Aktionslink wurde erfolgreich ausgefΓΌhrt', 'The change of your account rights is approved by admin' => 'Die Γ„nderung Ihrer Benutzerrechte wurde durch den Administrator genehmigt', 'The change of your account rights is rejected by admin' => 'Die Γ„nderung Ihrer Benutzerrechte wurde durch den Administrator abgelehnt', 'The contact record was successfull updated.' => 'Der Adressdatensatz wurde aktualisiert.', 'The daily sequence must be greater than zero!' => 'Die Sequenz der tΓ€glichen Wiederholung muss grâßer als Null sein!', 'The deadline ends after the event start date!' => 'Der Anmeldeschluß liegt nach dem Beginn der Veranstaltung!', 'The email address %email% is associated with a company contact record. At the moment you can only subscribe to a event with your personal email address!' => 'Die E-Mail Adresse %email% ist einer Firma oder Institution zugeordnet. Zur Zeit kΓΆnnen Sie sich jedoch nur mit einer persΓΆnlichen E-Mail Adresse zu einer Veranstaltung anmelden.', 'The email address %email% is not registered. We can only create a account for you if there was already a interaction, i.e. you have proposed a event. If you represent an organizer or a location and your public email address is not registered, please contact the administrator.' => 'Die E-Mail Adresse %email% ist nicht registriert. Wir kΓΆnnen nur dann ein Benutzerkonto fΓΌr Sie anlegen, wenn bereits eine Interaktion stattgefunden hat, z.B. in dem Sie bereits eine Veranstaltung vorgeschlagen haben. Falls Sie einen Veranstalter oder einen Veranstaltungsort vertreten und ihre <em>ΓΆffentliche</em> E-Mail Adresse noch nicht registriert ist, nehmen Sie bitte Kontakt mit dem Administrator auf.', 'The email field must be always set for the subscription form and always enabled and required! Please check the config.event.json!' => 'Das E-Mail Feld muss fΓΌr Anmeldeformulare immer gesetzt werden und es muss sichtbar und als <em>benΓΆtigt</em> gekennzeichnet sein! Bitte prΓΌfen Sie die <em>config.event.json</em>!', 'The event %title% was just published by the administrator' => 'Die Veranstaltung %title% wurde gerade durch den Administrator verΓΆffentlicht.', 'The event [%event_id%] will be repeated at %pattern_type% %pattern_day% of each %pattern_sequence%. month%exclude%' => 'Die Veranstaltung [%event_id%] wird am %pattern_type% %pattern_day% jedes %pattern_sequence%. Monat wiederholt%exclude%', 'The event [%event_id%] will be repeated at each workday%exclude%' => 'Die Veranstaltung [%event_id%] wird an jedem Werktag wiederholt%exclude%', 'The event [%event_id%] will be repeated at the %month_day%. day of each %month_sequence%. month%exclude%' => 'Die Veranstaltung [%event_id%] wird am %month_day%. Tag jedes %month_sequence%. Monat wiederholt%exclude%', 'The event [%event_id%] will be repeated each %day_sequence% day(s)%exclude%' => 'Die Veranstaltung [%event_id%] wird jeden %day_sequence%. Tag wiederholt%exclude%', 'The event [%event_id%] will be repeated each %week_sequence% week(s) at %week_day%%exclude%' => 'Die Veranstaltung [%event_id%] wird jede %week_sequence%. Woche am %week_day% wiederholt%exclude%', 'The event [%event_id%] will be repeated each %year_repeat%. year at %month_day%. %month_name%%exclude%' => 'Die Veranstaltung [%event_id%] wird jedes %year_repeat%. Jahr am %month_day%. %month_name% wiederholt%exclude%', 'The event [%event_id%] will be repeated each %year_repeat%. year at %pattern_type% %pattern_day% of %pattern_month%%exclude%' => 'Die Veranstaltung [%event_id%] wird jedes %year_repeat%. Jahr am %pattern_type% %pattern_day% im %pattern_month% wiederholt%exclude%', 'The event group with the name %group% does not exists!' => 'Die Veranstaltungs-Gruppe %group% existiert nicht!', 'The event list is empty, please create a event!' => 'Es existieren keine aktiven Veranstaltungen, legen Sie eine neue Versanstaltung an.', 'The event start date is behind the event end date!' => 'Das Anfangsdatum der Veranstaltung liegt nach dem Enddatum der Veranstaltung!', 'The event with the title %title% was published.' => 'Die Veranstaltung mit der Bezeichnung %title% wurde verΓΆffentlicht.', 'The event with the title %title% was rejected.' => 'Die Veranstaltung mit der Bezeichnung %title% wurde zurΓΌckgewiesen.', 'The field with the name %name% is not supported.' => 'Das Feld mit dem Bezeichner %name% wird nicht unterstΓΌtzt.', 'The filter \'actual\' must be numeric or contain the keyword \'current\' as first parameter.' => 'Der Filter <em>actual</em> muss eine Ganzzahl oder das SchlΓΌsselwort <em>current</em> als ersten Parameter enthalten.', 'The filter for <em>day</em> must be numeric or contain the keyword <em>current</em>' => 'Der Filter fΓΌr <em>day</em> muss eine Ganzzahl oder das SchlΓΌsselwort <em>current</em> enthalten.', 'The filter for <em>month</em> must be numeric or contain the keyword <em>current</em>' => 'Der Filter <em>month</em> muss eine Ganzzahl oder das SchlΓΌsselwort <em>current</em> enthalten.', 'The filter for <em>year</em> must be numeric or contain the keyword <em>current</em>' => 'Der Filter fΓΌr <em>year</em> muss eine Ganzzahl oder das SchlΓΌsselwort <em>current</em> enthalten.', 'The group list is empty, please define a group!' => 'Es existieren keine Gruppen, bitte legen Sie eine Gruppe an!', 'The identifier %identifier% already exists!' => 'Der Bezeichner %identifier% existiert bereits!', 'The image <b>%image%</b> has been added to the event.' => 'Der Veranstaltung wurde das Bild <b>%image%</b> hinzugefΓΌgt.', 'The image with the ID %image_id% was successfull deleted.' => 'Das Bild mit der ID %image_id% wurde erfolgreich gelΓΆscht.', 'The import from kitEvent was successfull finished.' => 'Der Import aus kitEvent wurde abgeschlossen.', 'The next recurring events' => 'Die nΓ€chsten Veranstaltungstermine', 'The publishing date ends before the event starts, this is not allowed!' => 'Der VerΓΆffentlichungszeitraum endet vor dem Beginn der Veranstaltung, dies ist nicht gewΓΌnscht!', 'The publishing of the event %title% was rejected by the administrator' => 'Die VerΓΆffentlichung der Veranstaltung %title% wurde vom Administrator zurΓΌckgewiesen.', 'The QR-Code file does not exists, please rebuild all QR-Code files.' => 'Die QR-Code Datei existiert nicht, bitte erzeugen Sie alle QR-Code Dateien neu.', 'The recurring event was not changed.' => 'Die wiederholende Veranstaltung wurde nicht geΓ€ndert.', 'The recurring events where successfull deleted.' => 'Die wiederholten Veranstaltungen wurden erfolgreich gelΓΆscht.', 'The repeat each x-year sequence must be greater than zero and less than 10!' => 'Der Wert fΓΌr die jΓ€hrliche Wiederholung muss grâßer als Null und kleiner als 10 sein!', 'The second parameter for the filter \'actual\' must be a positive integer value.' => 'Der zweite Parameter fΓΌr den Filter <em>actual</em> muss eine positive Ganzzahl sein.', 'The second parameter for the filter \'actual\' must be positive integer value.' => 'Der zweite Parameter fΓΌr den Filter <em>actual</em> muss eine positive Ganzzahl sein.', 'The status (%subscription_status%) of your subscription #%subscription_id% is ambiguous, the program can not confirm your subscription. Please contact the <a href="%email%">webmaster</a>.' => 'Der Status (%subscription_status%) Ihrer Anmeldung #%subscription_id% ist widersprΓΌchlich, das Programm kann Ihre Anmeldung leider nicht bestΓ€tigen. Bitte kontaktieren Sie den <a href="%email%">Webmaster</a>.', 'The status for the contact with the ID %contact_id% is ambiguous, the program can not activate the account. Please contact the <a href="%email%">webmaster</a>.' => 'Der Status fΓΌr den Kontaktdatensatz mit der ID %contact_id% ist nicht eindeutig, das Programm kann Ihr Benutzerkonto nicht aktivieren. Bitte kontaktieren Sie den <a href="%email%">webmaster</a>.', 'The status of your address record is actually %status%, so we can not accept your subscription. Please contact the <a href="mailto:%email%">webmaster</a>.' => 'Der Status Ihres Adressdatensatz ist zur Zeit auf %status% gesetzt, wir kΓΆnnen Ihre Anmeldung daher nicht entgegennehmen. Bitte nehmen Sie Kontakt mit dem <a href="mailto:%email%">Webmaster</a> auf, um die Situation zu klΓ€ren.', 'The submitted GUID %guid% does not exists.' => 'Die ΓΌbermittelte GUID %guid% existiert nicht!', 'The subscription was successfull inserted.' => 'Die Anmeldung wurde erfolgreich hinzugefΓΌgt.', 'The subscription was successfull updated' => 'Die Anmeldung wurde erfolgreich aktualisiert.', 'The Subscription with the ID %subscription_id% does not exists!' => 'Die Anmeldung mit der ID %subscription_id% existiert nicht!', 'The user %contact_name% with the ID %contact_id% and the email address %email% has proposed the following event' => 'Der Kontakt %contact_name% mit der der ID %contact_id% und der E-Mail Adresse %email% hat die folgende Veranstaltung vorgeschlagen', 'The user %user% does not exists!' => 'Der Benutzer %user% existiert nicht!', 'The user %user% has already proposed %count% events' => 'Der Kontakt %user% hat bereits %count% Veranstaltungen vorgeschlagen', 'The user %user% has never proposed a event' => 'Der Kontakt %user% hat noch nie eine Veranstaltung vorgeschlagen', 'The user %user% want to get the right' => 'Der Benutzer %user% mΓΆchte die Berechtigung erhalten', 'The value for \'order_direction\' can be \'ASC\' (ascending) or \'DESC\' (descending)' => 'Der Wert fΓΌr <em>order_direction</em> kann <em>ASC</em> (aufsteigend) oder <em>DESC</em> (absteigend) sein.', 'The weekly sequence must be greater than zero!' => 'Die Sequenz der wΓΆchentlichen Wiederholung muss grâßer als Null sein!', 'There exists no kitEvent installation at the parent CMS!' => 'Es wurde keine kitEvent Installation in dem ΓΌbergeordeneten Content Management System gefunden!', 'There exists no locations who fits to the search term %search%' => 'Es wurde kein Veranstaltungsort gefunden, der zu dem Suchbegriff <i>%search%</i> passt.', 'There exists no organizer who fits to the search term %search%' => 'Es wurde kein Veranstalter gefunden, der zu dem Suchbegriff <i>%search%</i> passt.', 'third' => 'dritten', 'This activation link was already used and is no longer valid!' => 'Dieser Aktivierungslink wurde bereits verwendet und ist nicht mehr gΓΌltig!', 'This event was copied from the event with the ID %id%. Be aware that you should change the dates before publishing to avoid duplicate events!' => 'Diese Veranstaltung ist eine Kopie der Veranstaltung mit der ID %id%. Bitte beachten Sie, daß Sie die Datumsangaben anpassen bevor Sie diese Veranstaltung verΓΆffentlichen - Sie erzeugen sonst doppelte EintrΓ€ge!', 'This extra field is used in the event group %group%. First remove the extra field from the event group.' => 'Dieses Zusatzfeld wird in der Veranstaltungs Gruppe %group% verwendet. Sie mΓΌssen das Zusatzfeld zunΓ€chst aus der Gruppe entfernen.', 'This user has a account but was never in contact in context with events' => 'Dieser Benutzer verfΓΌgt ΓΌber ein Benutzerkonto, war jedoch im Zusammenhang mit Veranstaltungen noch nie im Kontakt', 'This user has a contact record but was never in contact in context with events' => 'Dieser Benutzer verfΓΌgt ΓΌber einen Kontaktdatensatz, war jedoch im Zusammenhang mit Veranstaltungen noch nie im Kontakt', 'Type' => 'Typ', 'Unknown organizer' => 'Unbekannter Veranstalter', 'unlimited' => 'unbegrenzt', 'Using qrcode[] is not enabled in config.event.json!' => 'qrcode[] ist nicht in der config.event.json freigegeben!', 'Visit the event description' => 'Besuchen Sie die Veranstaltungsbeschreibung', 'We have send you a new password, please check your email account' => 'Wir haben Ihnen ein neues Passwort an Ihre E-Mail Adresse gesendet, bitte prΓΌfen Sie Ihren Posteingang', 'We send you a new password to your email address.' => 'Wir senden Ihnen ein neues Passwort an Ihre E-Mail Adresse.', 'Week day' => 'Wochentag', 'Week day view' => 'Wochentage', 'Week sequence' => 'WΓΆchentliche Wiederholung', 'Weekly recurring' => 'WΓΆchentliche Wiederholung', 'Year pattern day' => 'Tag', 'Year pattern day view' => 'Tag', 'Year pattern month' => 'Monat', 'Year pattern month view' => 'Monate', 'Year pattern type' => 'Typ', 'Year repeat' => 'JΓ€hrliche Wiederholung', 'Year sequence day' => 'Tag', 'Year sequence day view' => 'Tage', 'Year sequence month' => 'Monat', 'Year sequence month view' => 'Monate', 'Year type' => 'Typ', 'Yearly recurring' => 'JΓ€hrliche Wiederholung', 'You have already subscribed to this Event at %datetime%, you can not subscribe again.' => 'Sie haben sich am %datetime% bereits zu dieser Veranstaltung angemeldet und kΓΆnnen sich deshalb nicht erneut anmelden.', 'You have already the right to edit events (%role%). Please contact the administrator if you want to change or extend your account rights' => 'Sie verfΓΌgen bereits ΓΌber das Recht Veranstaltungen zu bearbeiten (%role%). Bitte wenden Sie sich an den Administrator, wenn Sie Ihre Rechte Γ€ndern oder erweitern mΓΆchten.', 'You have now the additional right to: "%role%' => 'Sie verfΓΌgen jetzt ΓΌber das zusΓ€tzliche Recht: "%role%', 'You have selected <i>Company, Institution or Association</i> as contact type, so please give us the name' => 'Sie haben <i>Firma, Institution oder Verein</i> als Kontakt Typ angegeben, bitte nennen Sie uns den Namen der Einrichtung.', 'You have selected <i>natural person</i> as contact type, so please give us the last name of the person.' => 'Sie haben <i>natΓΌrliche Person</i> als Kontakt Typ gewΓ€hlt, bitte nennen Sie uns den Nachnamen der Person.', 'You need a account if you want to edit events. In general we will give accounts to all event organizers, locations and persons which submit events frequently.' => 'Sie benΓΆtigen ein Benutzerkonto um Veranstaltungen Γ€ndern und ergΓ€nzen zu kΓΆnnen. Im Allgemeinen erhalten alle Veranstalter, Veranstaltungsorte sowie Personen, die regelmÀßig Veranstaltungen eintragen, einen Zugang von uns.', 'Your contact record is locked, so we can not perform any action. Please contact the administrator' => 'Ihr Kontakt Datensatz ist gesperrt, wir kΓΆnnen keine Aktion durchfΓΌhren. Bitte wenden Sie sich an den Administrator.', 'Your subscription for the event %event% is already confirmed.' => 'Ihre Anmeldung fΓΌr die Veranstaltung %event% wurde bereits bestΓ€tigt.', );
{ "content_hash": "f82450b9f1a16e489d9e2fff2658ae6f", "timestamp": "", "source": "github", "line_count": 701, "max_line_length": 420, "avg_line_length": 49.019971469329526, "alnum_prop": 0.7009574251375026, "repo_name": "phpManufakturHeirs/kfEvent", "id": "9058d8c2559f3faba58ce2df8ca9f8d1b526d909", "size": "34896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Data/Locale/de.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "21" }, { "name": "CSS", "bytes": "16016" }, { "name": "HTML", "bytes": "648698" }, { "name": "JavaScript", "bytes": "6363" }, { "name": "PHP", "bytes": "1455813" }, { "name": "Shell", "bytes": "25" } ], "symlink_target": "" }
package service.handler; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.net.DatagramPacket; import java.net.Socket; import java.security.SignatureException; import java.security.interfaces.RSAPublicKey; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import message.intuitive_bidding.*; import service.Config; import service.HashingChainTable; import service.Key; import service.KeyManager; import utility.Utils; /** * * @author Scott */ public class IntuitiveBiddingHandler extends ConnectionHandler { public static final File ATTESTATION; public static final Logger LOGGER; private static final Map<Integer, Integer> PRICE_TABLE; private static final HashingChainTable HASHING_CHAIN_TABLE; private static final ReentrantLock LOCK; static { ATTESTATION = new File(Config.ATTESTATION_DIR_PATH + "/service-provider/intuitive-bidding"); LOGGER = Logger.getLogger(BiddingHandler.class.getName()); PRICE_TABLE = new ConcurrentHashMap<>(); HASHING_CHAIN_TABLE = new HashingChainTable(); LOCK = new ReentrantLock(); } public IntuitiveBiddingHandler(DatagramPacket datagramPacket, Key key) { super(datagramPacket, key); } @Override protected void handle(DataOutputStream out, DataInputStream in) throws SignatureException, IllegalAccessException { throw new UnsupportedOperationException("Not supported yet."); } @Override protected void handle(DatagramPacket datagramPacket) throws SignatureException { KeyManager keyManager = KeyManager.getInstance(); RSAPublicKey clientPubKey = (RSAPublicKey) keyManager.getPublicKey(Key.CLIENT); byte[] reqBytes = Arrays.copyOf(datagramPacket.getData(), datagramPacket.getLength()); Request req = new Request(new String(reqBytes), clientPubKey); String chainHash = null; LOCK.lock(); try { String itemId = req.getItemId().toString(); System.out.format("received: itemId=%2d, userId=%s, price=%s\n", req.getItemId(), req.getUserId(), req.getPrice()); chainHash = HASHING_CHAIN_TABLE.getLastChainHash(itemId); HASHING_CHAIN_TABLE.chain(itemId, Utils.digest(req.toString())); } finally { LOCK.unlock(); } int currentPrice = PRICE_TABLE.getOrDefault(req.getItemId(), 0); int bidderPrice = Integer.decode(req.getPrice()); boolean bidSuccess = bidderPrice > currentPrice; if (bidSuccess) { PRICE_TABLE.put(req.getItemId(), bidderPrice); } System.out.format("decrypted price: %d, now highest price is %d\n", bidderPrice, Math.max(bidderPrice, currentPrice)); Acknowledgement ack = new Acknowledgement(chainHash, bidSuccess, req); ack.sign(keyPair, keyInfo); try (Socket s = new Socket(datagramPacket.getAddress(), req.getPort()); DataOutputStream out = new DataOutputStream(s.getOutputStream()); DataInputStream in = new DataInputStream(s.getInputStream())) { Utils.send(out, ack.toString()); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } }
{ "content_hash": "2c3c044a0f0717cfd36ee4d9b887a77b", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 100, "avg_line_length": 34.58252427184466, "alnum_prop": 0.6726558113419427, "repo_name": "CloudComLab/Online-Bidding-System", "id": "c83078b0c8f05f58a872625ad6dbb6765bab63f6", "size": "3562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/service/handler/IntuitiveBiddingHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "104232" } ], "symlink_target": "" }
/* global chrome */ /* eslint no-undef: "error" */ /* eslint func-names: ["error", "always"] */ /* eslint operator-linebreak: ["error", "before"] */ let enabled function onBrowserStart() { chrome.storage.sync.get({ enabled: true }, (items) => { enabled = items.enabled }) checkIcon() } onBrowserStart() chrome.extension.onMessage.addListener((request, sender, sendResponse) => { if (request === 'getState') { sendResponse(enabled) checkIcon(enabled) return } enabled = request === 'Activar' chrome.storage.sync.set({ enabled }) checkIcon(enabled) }) function checkIcon(state) { const path = state ? 'assets/mercado-libre_128.png' : 'assets/mercado-libre-disabled_128.png' chrome.browserAction.setIcon({ path }) }
{ "content_hash": "4507ce89c6e17e35c91038bec95d3bf2", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 95, "avg_line_length": 23.59375, "alnum_prop": 0.6675496688741722, "repo_name": "Fenwil/MercadoLibre-MasVendidos", "id": "b6bdd9465acf69e8d1d21539610f3c6a4649355f", "size": "755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/background.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1038" }, { "name": "JavaScript", "bytes": "3090" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ff783ce9a50b06f08ee1747b4eb5492f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "360cbd4da9570bc3a2c82ef1628acb3065b4bf80", "size": "168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Berberidaceae/Berberis/Berberis ferox/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package it.geosolutions.jaiext.warp; import it.geosolutions.jaiext.range.Range; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.IndexColorModel; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.util.Map; import javax.media.jai.BorderExtender; import javax.media.jai.ImageLayout; import javax.media.jai.Interpolation; import javax.media.jai.InterpolationTable; import javax.media.jai.PlanarImage; import javax.media.jai.ROI; import javax.media.jai.RasterAccessor; import javax.media.jai.Warp; import javax.media.jai.iterator.RandomIter; /** * An <code>OpImage</code> implementing the general "Warp" operation as described in <code>javax.media.jai.operator.WarpDescriptor</code>. It supports * the bicubic interpolation. * * <p> * The layout for the destination image may be specified via the <code>ImageLayout</code> parameter. However, only those settings suitable for this * operation will be used. The unsuitable settings will be replaced by default suitable values. An optional ROI object and a NoData Range can be used. * If a backward mapped pixel lies outside ROI or it is a NoData, then the destination pixel value is a background value. * * * @since EA2 * @see javax.media.jai.Warp * @see javax.media.jai.WarpOpImage * @see javax.media.jai.operator.WarpDescriptor * @see WarpRIF * */ @SuppressWarnings("unchecked") final class WarpBicubicOpImage extends WarpOpImage { /** Constant holding the bicubic kernel value */ private static final int KERNEL_LINE_DIM = 4; /** * Unsigned short Max Value */ protected static final int USHORT_MAX_VALUE = Short.MAX_VALUE - Short.MIN_VALUE; /** Color table representing source's IndexColorModel. */ private byte[][] ctable = null; /** LookupTable used for a faster NoData check */ private boolean[] booleanLookupTable; /** Integer coeffs for horizontal interpolation */ private int[] dataHi; /** Integer coeffs for vertical interpolation */ private int[] dataVi; /** Float coeffs for horizontal interpolation */ private float[] dataHf; /** Float coeffs for vertical interpolation */ private float[] dataVf; /** Double coeffs for horizontal interpolation */ private double[] dataHd; /** Double coeffs for vertical interpolation */ private double[] dataVd; /** Shift used in integer computations */ private int shift; /** Integer value used for rounding integer computations */ private int round; /** Precision bits used for expanding the integer interpolation */ private int precisionBits; /** * Constructs a WarpBilinearOpImage. * * @param source The source image. * @param extender A BorderExtender, or null. * @param config RenderingHints used in calculations. * @param layout The destination image layout. * @param warp An object defining the warp algorithm. * @param interp An object describing the interpolation method. * @param roi input ROI object used. * @param noData NoData Range object used for checking if NoData are present. */ public WarpBicubicOpImage(final RenderedImage source, final BorderExtender extender, final Map<?, ?> config, final ImageLayout layout, final Warp warp, final Interpolation interp, final ROI sourceROI, Range noData) { super(source, layout, config, false, extender, interp, warp, null, sourceROI, noData); /* * If the source has IndexColorModel, get the RGB color table. Note, in this case, the source should have an integral data type. And dest * always has data type byte. */ final ColorModel srcColorModel = source.getColorModel(); if (srcColorModel instanceof IndexColorModel) { final IndexColorModel icm = (IndexColorModel) srcColorModel; ctable = new byte[3][icm.getMapSize()]; icm.getReds(ctable[0]); icm.getGreens(ctable[1]); icm.getBlues(ctable[2]); } /* * Selection of a destinationNoData value for each datatype */ destinationNoDataDouble = backgroundValues[0]; SampleModel sm = source.getSampleModel(); // Source image data Type int srcDataType = sm.getDataType(); switch (srcDataType) { case DataBuffer.TYPE_BYTE: destinationNoDataByte = (byte) (((byte) destinationNoDataDouble) & 0xff); // Creation of a lookuptable containing the values to use for no data if (hasNoData) { booleanLookupTable = new boolean[256]; for (int i = 0; i < booleanLookupTable.length; i++) { byte value = (byte) i; booleanLookupTable[i] = noDataRange.contains(value); } } break; case DataBuffer.TYPE_USHORT: destinationNoDataShort = (short) (((short) destinationNoDataDouble) & 0xffff); break; case DataBuffer.TYPE_SHORT: destinationNoDataShort = (short) destinationNoDataDouble; break; case DataBuffer.TYPE_INT: destinationNoDataInt = (int) destinationNoDataDouble; break; case DataBuffer.TYPE_FLOAT: destinationNoDataFloat = (float) destinationNoDataDouble; break; case DataBuffer.TYPE_DOUBLE: break; default: throw new IllegalArgumentException("Wrong data Type"); } // Selection of the interpolation coefficients InterpolationTable interpCubic = (InterpolationTable) interp; switch (srcDataType) { case DataBuffer.TYPE_BYTE: case DataBuffer.TYPE_USHORT: case DataBuffer.TYPE_SHORT: case DataBuffer.TYPE_INT: dataHi = interpCubic.getHorizontalTableData(); dataVi = interpCubic.getVerticalTableData(); break; case DataBuffer.TYPE_FLOAT: dataHf = interpCubic.getHorizontalTableDataFloat(); dataVf = interpCubic.getVerticalTableDataFloat(); break; case DataBuffer.TYPE_DOUBLE: dataHd = interpCubic.getHorizontalTableDataDouble(); dataVd = interpCubic.getVerticalTableDataDouble(); break; default: throw new IllegalArgumentException("Wrong data Type"); } // Subsample bits used shift = 1 << interp.getSubsampleBitsH(); precisionBits = interpCubic.getPrecisionBits(); if (precisionBits > 0) { round = 1 << (precisionBits - 1); } // Definition of the padding leftPad = 1; rightPad = 2; topPad = 1; bottomPad = 2; } protected void computeRectByte(final PlanarImage src, final RasterAccessor dst, final RandomIter roiIter, boolean roiContainsTile) { // Random Iterator initialization, taking into account the presence of the borderExtender RandomIter iterSource; final int minX, maxX, minY, maxY; if (extended) { // Creation of an iterator on the image extended by the padding factors iterSource = getRandomIterator(src, leftPad, rightPad, topPad, bottomPad, extender); // Definition of the image bounds minX = src.getMinX(); maxX = src.getMaxX(); minY = src.getMinY(); maxY = src.getMaxY(); } else { // Creation of an iterator on the image iterSource = getRandomIterator(src, null); // Definition of the image bounds minX = src.getMinX() + leftPad; // Left padding maxX = src.getMaxX() - rightPad; // Right padding minY = src.getMinY() + topPad; // Top padding maxY = src.getMaxY() - bottomPad; // Bottom padding } final int dstWidth = dst.getWidth(); final int dstHeight = dst.getHeight(); final int dstBands = dst.getNumBands(); final int lineStride = dst.getScanlineStride(); final int pixelStride = dst.getPixelStride(); final int[] bandOffsets = dst.getBandOffsets(); final byte[][] data = dst.getByteDataArrays(); final float[] warpData = new float[2 * dstWidth]; int lineOffset = 0; // Creation of an iterator for the ROI Image if(hasROI && !roiContainsTile && roiIter == null){ throw new IllegalArgumentException("Error on creating the ROI iterator"); } if (ctable == null) { // source does not have IndexColorModel // ONLY VALID DATA if (caseA || (caseB && roiContainsTile)) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NO ROI // for (int b = 0; b < dstBands; b++) { // Interpolation long result = (bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null)); // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ONLY ROI } else if (caseB) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { for (int b = 0; b < dstBands; b++) { // Interpolation long result = (bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null)); // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // ONLY NODATA } else if (caseC || (hasROI && hasNoData && roiContainsTile)) { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b) & 0xFF; pixelKernel[j][i] = sample; if (booleanLookupTable[sample]) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // BOTH ROI AND NODATA } else { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b) & 0xFF; pixelKernel[j][i] = sample; if (booleanLookupTable[sample]) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP } } else {// source has IndexColorModel // ONLY VALID DATA if (caseA || (caseB && roiContainsTile)) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NO ROI // for (int b = 0; b < dstBands; b++) { final byte[] t = ctable[b]; // Interpolation long result = (bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, t)); // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ONLY ROI } else if (caseB) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { for (int b = 0; b < dstBands; b++) { final byte[] t = ctable[b]; // Interpolation long result = (bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, t)); // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // ONLY NODATA } else if (caseC || (hasROI && hasNoData && roiContainsTile)) { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { final byte[] t = ctable[b]; // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = t[iterSource.getSample(xint + (i - 1), yint + (j - 1), 0) & 0xFF] & 0xFF; pixelKernel[j][i] = sample; if (booleanLookupTable[sample]) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // BOTH ROI AND NODATA } else { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { final byte[] t = ctable[b]; // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = t[iterSource.getSample(xint + (i - 1), yint + (j - 1), 0) & 0xFF] & 0xFF; pixelKernel[j][i] = sample; if (booleanLookupTable[sample]) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > 255) { result = 255; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (byte) (result & 0xff); } } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataByte; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP } } iterSource.done(); } protected void computeRectUShort(final PlanarImage src, final RasterAccessor dst, final RandomIter roiIter, boolean roiContainsTile) { // Random Iterator initialization, taking into account the presence of the borderExtender RandomIter iterSource; final int minX, maxX, minY, maxY; if (extended) { // Creation of an iterator on the image extended by the padding factors iterSource = getRandomIterator(src, leftPad, rightPad, topPad, bottomPad, extender); // Definition of the image bounds minX = src.getMinX(); maxX = src.getMaxX(); minY = src.getMinY(); maxY = src.getMaxY(); } else { // Creation of an iterator on the image iterSource = getRandomIterator(src, null); // Definition of the image bounds minX = src.getMinX() + leftPad; // Left padding maxX = src.getMaxX() - rightPad; // Right padding minY = src.getMinY() + topPad; // Top padding maxY = src.getMaxY() - bottomPad; // Bottom padding } final int dstWidth = dst.getWidth(); final int dstHeight = dst.getHeight(); final int dstBands = dst.getNumBands(); final int lineStride = dst.getScanlineStride(); final int pixelStride = dst.getPixelStride(); final int[] bandOffsets = dst.getBandOffsets(); final short[][] data = dst.getShortDataArrays(); final float[] warpData = new float[2 * dstWidth]; int lineOffset = 0; // Creation of an iterator for the ROI Image if(hasROI && !roiContainsTile && roiIter == null){ throw new IllegalArgumentException("Error on creating the ROI iterator"); } // source does not have IndexColorModel // ONLY VALID DATA if (caseA || (caseB && roiContainsTile)) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NO ROI // for (int b = 0; b < dstBands; b++) { // Interpolation long result = (bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null)); // Clamp if (result > USHORT_MAX_VALUE) { result = USHORT_MAX_VALUE; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (short) (result & 0xFFFF); } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ONLY ROI } else if (caseB) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { for (int b = 0; b < dstBands; b++) { // Interpolation long result = (bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null)); // Clamp if (result > USHORT_MAX_VALUE) { result = USHORT_MAX_VALUE; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (short) (result & 0xFFFF); } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // ONLY NODATA } else if (caseC || (hasROI && hasNoData && roiContainsTile)) { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b) & 0xFFFF; pixelKernel[j][i] = sample; if (noDataRange.contains((short) sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > USHORT_MAX_VALUE) { result = USHORT_MAX_VALUE; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (short) (result & 0xFFFF); } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // BOTH ROI AND NODATA } else { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b) & 0xFFFF; pixelKernel[j][i] = sample; if (noDataRange.contains((short) sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > USHORT_MAX_VALUE) { result = USHORT_MAX_VALUE; } else if (result < 0) { result = 0; } data[b][pixelOffset + bandOffsets[b]] = (short) (result & 0xFFFF); } } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP } iterSource.done(); } protected void computeRectShort(final PlanarImage src, final RasterAccessor dst, final RandomIter roiIter, boolean roiContainsTile) { // Random Iterator initialization, taking into account the presence of the borderExtender RandomIter iterSource; final int minX, maxX, minY, maxY; if (extended) { // Creation of an iterator on the image extended by the padding factors iterSource = getRandomIterator(src, leftPad, rightPad, topPad, bottomPad, extender); // Definition of the image bounds minX = src.getMinX(); maxX = src.getMaxX(); minY = src.getMinY(); maxY = src.getMaxY(); } else { // Creation of an iterator on the image iterSource = getRandomIterator(src, null); // Definition of the image bounds minX = src.getMinX() + leftPad; // Left padding maxX = src.getMaxX() - rightPad; // Right padding minY = src.getMinY() + topPad; // Top padding maxY = src.getMaxY() - bottomPad; // Bottom padding } final int dstWidth = dst.getWidth(); final int dstHeight = dst.getHeight(); final int dstBands = dst.getNumBands(); final int lineStride = dst.getScanlineStride(); final int pixelStride = dst.getPixelStride(); final int[] bandOffsets = dst.getBandOffsets(); final short[][] data = dst.getShortDataArrays(); final float[] warpData = new float[2 * dstWidth]; int lineOffset = 0; // Creation of an iterator for the ROI Image if(hasROI && !roiContainsTile && roiIter == null){ throw new IllegalArgumentException("Error on creating the ROI iterator"); } // source does not have IndexColorModel // ONLY VALID DATA if (caseA || (caseB && roiContainsTile)) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NO ROI // for (int b = 0; b < dstBands; b++) { // Interpolation long result = bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null); // Clamp if (result > Short.MAX_VALUE) { result = Short.MAX_VALUE; } else if (result < Short.MIN_VALUE) { result = Short.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (short) (result); } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ONLY ROI } else if (caseB) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { for (int b = 0; b < dstBands; b++) { // Interpolation long result = bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null); // Clamp if (result > Short.MAX_VALUE) { result = Short.MAX_VALUE; } else if (result < Short.MIN_VALUE) { result = Short.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (short) (result); } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // ONLY NODATA } else if (caseC || (hasROI && hasNoData && roiContainsTile)) { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains((short) sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > Short.MAX_VALUE) { result = Short.MAX_VALUE; } else if (result < Short.MIN_VALUE) { result = Short.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (short) (result); } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // BOTH ROI AND NODATA } else { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains((short) sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > Short.MAX_VALUE) { result = Short.MAX_VALUE; } else if (result < Short.MIN_VALUE) { result = Short.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (short) (result); } } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataShort; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP } iterSource.done(); } protected void computeRectInt(final PlanarImage src, final RasterAccessor dst, final RandomIter roiIter, boolean roiContainsTile) { // Random Iterator initialization, taking into account the presence of the borderExtender RandomIter iterSource; final int minX, maxX, minY, maxY; if (extended) { // Creation of an iterator on the image extended by the padding factors iterSource = getRandomIterator(src, leftPad, rightPad, topPad, bottomPad, extender); // Definition of the image bounds minX = src.getMinX(); maxX = src.getMaxX(); minY = src.getMinY(); maxY = src.getMaxY(); } else { // Creation of an iterator on the image iterSource = getRandomIterator(src, null); // Definition of the image bounds minX = src.getMinX() + leftPad; // Left padding maxX = src.getMaxX() - rightPad; // Right padding minY = src.getMinY() + topPad; // Top padding maxY = src.getMaxY() - bottomPad; // Bottom padding } final int dstWidth = dst.getWidth(); final int dstHeight = dst.getHeight(); final int dstBands = dst.getNumBands(); final int lineStride = dst.getScanlineStride(); final int pixelStride = dst.getPixelStride(); final int[] bandOffsets = dst.getBandOffsets(); final int[][] data = dst.getIntDataArrays(); final float[] warpData = new float[2 * dstWidth]; int lineOffset = 0; // Creation of an iterator for the ROI Image if(hasROI && !roiContainsTile && roiIter == null){ throw new IllegalArgumentException("Error on creating the ROI iterator"); } // source does not have IndexColorModel // ONLY VALID DATA if (caseA || (caseB && roiContainsTile)) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NO ROI // for (int b = 0; b < dstBands; b++) { // Interpolation long result = bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null); // Clamp if (result > Integer.MAX_VALUE) { result = Integer.MAX_VALUE; } else if (result < Integer.MIN_VALUE) { result = Integer.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (int) (result); } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ONLY ROI } else if (caseB) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { for (int b = 0; b < dstBands; b++) { // Interpolation long result = bicubicCalculationInt(b, iterSource, xint, yint, offsetX, offsetY, null); // Clamp if (result > Integer.MAX_VALUE) { result = Integer.MAX_VALUE; } else if (result < Integer.MIN_VALUE) { result = Integer.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (int) (result); } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // ONLY NODATA } else if (caseC || (hasROI && hasNoData && roiContainsTile)) { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains(sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > Integer.MAX_VALUE) { result = Integer.MAX_VALUE; } else if (result < Integer.MIN_VALUE) { result = Integer.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (int) (result); } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // BOTH ROI AND NODATA } else { // Array used during calculations final long[][] pixelKernel = new long[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; long[] sumArray = new long[KERNEL_LINE_DIM]; long[] emptyArray = new long[KERNEL_LINE_DIM]; long[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization long tempSum = 0; long sum = 0; // final result initialization long result = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int sample = iterSource.getSample(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains(sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpainting(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHi[offsetX] + tempData[1] * dataHi[offsetX + 1] + tempData[2] * dataHi[offsetX + 2] + tempData[3] * dataHi[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = ((tempSum + round) >> precisionBits); } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } else { tempData = bicubicInpainting(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVi[offsetY] + tempData[1] * dataVi[offsetY + 1] + tempData[2] * dataVi[offsetY + 2] + tempData[3] * dataVi[offsetY + 3]; // Interpolation result = ((sum + round) >> precisionBits); weight = 0; weightVert = 0; sum = 0; // Clamp if (result > Integer.MAX_VALUE) { result = Integer.MAX_VALUE; } else if (result < Integer.MIN_VALUE) { result = Integer.MIN_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (int) (result); } } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataInt; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP } iterSource.done(); } protected void computeRectFloat(final PlanarImage src, final RasterAccessor dst, final RandomIter roiIter, boolean roiContainsTile) { // Random Iterator initialization, taking into account the presence of the borderExtender RandomIter iterSource; final int minX, maxX, minY, maxY; if (extended) { // Creation of an iterator on the image extended by the padding factors iterSource = getRandomIterator(src, leftPad, rightPad, topPad, bottomPad, extender); // Definition of the image bounds minX = src.getMinX(); maxX = src.getMaxX(); minY = src.getMinY(); maxY = src.getMaxY(); } else { // Creation of an iterator on the image iterSource = getRandomIterator(src, null); // Definition of the image bounds minX = src.getMinX() + leftPad; // Left padding maxX = src.getMaxX() - rightPad; // Right padding minY = src.getMinY() + topPad; // Top padding maxY = src.getMaxY() - bottomPad; // Bottom padding } final int dstWidth = dst.getWidth(); final int dstHeight = dst.getHeight(); final int dstBands = dst.getNumBands(); final int lineStride = dst.getScanlineStride(); final int pixelStride = dst.getPixelStride(); final int[] bandOffsets = dst.getBandOffsets(); final float[][] data = dst.getFloatDataArrays(); final float[] warpData = new float[2 * dstWidth]; int lineOffset = 0; // Creation of an iterator for the ROI Image if(hasROI && !roiContainsTile && roiIter == null){ throw new IllegalArgumentException("Error on creating the ROI iterator"); } // source does not have IndexColorModel // ONLY VALID DATA if (caseA || (caseB && roiContainsTile)) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NO ROI // for (int b = 0; b < dstBands; b++) { // Interpolation double result = bicubicCalculationFloat(b, iterSource, xint, yint, offsetX, offsetY); // Clamp if (result > Float.MAX_VALUE) { result = Float.MAX_VALUE; } else if (result < -Float.MAX_VALUE) { result = -Float.MAX_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (float) (result); } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ONLY ROI } else if (caseB) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { for (int b = 0; b < dstBands; b++) { // Interpolation double result = bicubicCalculationFloat(b, iterSource, xint, yint, offsetX, offsetY); // Clamp if (result > Float.MAX_VALUE) { result = Float.MAX_VALUE; } else if (result < -Float.MAX_VALUE) { result = -Float.MAX_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (float) (result); } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // ONLY NODATA } else if (caseC || (hasROI && hasNoData && roiContainsTile)) { // Array used during calculations final double[][] pixelKernel = new double[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; double[] sumArray = new double[KERNEL_LINE_DIM]; double[] emptyArray = new double[KERNEL_LINE_DIM]; double[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization double tempSum = 0; double sum = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel float sample = iterSource.getSampleFloat(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains(sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpaintingDouble(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHf[offsetX] + tempData[1] * dataHf[offsetX + 1] + tempData[2] * dataHf[offsetX + 2] + tempData[3] * dataHf[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = tempSum; } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } else { tempData = bicubicInpaintingDouble(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVf[offsetY] + tempData[1] * dataVf[offsetY + 1] + tempData[2] * dataVf[offsetY + 2] + tempData[3] * dataVf[offsetY + 3]; // Interpolation weight = 0; weightVert = 0; // Clamp if (sum > Float.MAX_VALUE) { sum = Float.MAX_VALUE; } else if (sum < -Float.MAX_VALUE) { sum = -Float.MAX_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (float) sum; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // BOTH ROI AND NODATA } else { // Array used during calculations final double[][] pixelKernel = new double[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; double[] sumArray = new double[KERNEL_LINE_DIM]; double[] emptyArray = new double[KERNEL_LINE_DIM]; double[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization double tempSum = 0; double sum = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel float sample = iterSource.getSampleFloat(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains(sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpaintingDouble(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHf[offsetX] + tempData[1] * dataHf[offsetX + 1] + tempData[2] * dataHf[offsetX + 2] + tempData[3] * dataHf[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = tempSum; } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } else { tempData = bicubicInpaintingDouble(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVf[offsetY] + tempData[1] * dataVf[offsetY + 1] + tempData[2] * dataVf[offsetY + 2] + tempData[3] * dataVf[offsetY + 3]; // Interpolation weight = 0; weightVert = 0; // Clamp if (sum > Float.MAX_VALUE) { sum = Float.MAX_VALUE; } else if (sum < -Float.MAX_VALUE) { sum = -Float.MAX_VALUE; } data[b][pixelOffset + bandOffsets[b]] = (float) sum; } } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataFloat; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP } iterSource.done(); } protected void computeRectDouble(final PlanarImage src, final RasterAccessor dst, final RandomIter roiIter, boolean roiContainsTile) { // Random Iterator initialization, taking into account the presence of the borderExtender RandomIter iterSource; final int minX, maxX, minY, maxY; if (extended) { // Creation of an iterator on the image extended by the padding factors iterSource = getRandomIterator(src, leftPad, rightPad, topPad, bottomPad, extender); // Definition of the image bounds minX = src.getMinX(); maxX = src.getMaxX(); minY = src.getMinY(); maxY = src.getMaxY(); } else { // Creation of an iterator on the image iterSource = getRandomIterator(src, null); // Definition of the image bounds minX = src.getMinX() + leftPad; // Left padding maxX = src.getMaxX() - rightPad; // Right padding minY = src.getMinY() + topPad; // Top padding maxY = src.getMaxY() - bottomPad; // Bottom padding } final int dstWidth = dst.getWidth(); final int dstHeight = dst.getHeight(); final int dstBands = dst.getNumBands(); final int lineStride = dst.getScanlineStride(); final int pixelStride = dst.getPixelStride(); final int[] bandOffsets = dst.getBandOffsets(); final double[][] data = dst.getDoubleDataArrays(); final float[] warpData = new float[2 * dstWidth]; int lineOffset = 0; // Creation of an iterator for the ROI Image if(hasROI && !roiContainsTile && roiIter == null){ throw new IllegalArgumentException("Error on creating the ROI iterator"); } // source does not have IndexColorModel // ONLY VALID DATA if (caseA || (caseB && roiContainsTile)) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NO ROI // for (int b = 0; b < dstBands; b++) { // Interpolation data[b][pixelOffset + bandOffsets[b]] = bicubicCalculationDouble(b, iterSource, xint, yint, offsetX, offsetY); } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ONLY ROI } else if (caseB) { for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { for (int b = 0; b < dstBands; b++) { // Interpolation data[b][pixelOffset + bandOffsets[b]] = bicubicCalculationDouble(b, iterSource, xint, yint, offsetX, offsetY); } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // ONLY NODATA } else if (caseC || (hasROI && hasNoData && roiContainsTile)) { // Array used during calculations final double[][] pixelKernel = new double[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; double[] sumArray = new double[KERNEL_LINE_DIM]; double[] emptyArray = new double[KERNEL_LINE_DIM]; double[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization double tempSum = 0; double sum = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel double sample = iterSource.getSampleDouble(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains(sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpaintingDouble(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHd[offsetX] + tempData[1] * dataHd[offsetX + 1] + tempData[2] * dataHd[offsetX + 2] + tempData[3] * dataHd[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = tempSum; } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } else { tempData = bicubicInpaintingDouble(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVd[offsetY] + tempData[1] * dataVd[offsetY + 1] + tempData[2] * dataVd[offsetY + 2] + tempData[3] * dataVd[offsetY + 3]; // Interpolation weight = 0; weightVert = 0; data[b][pixelOffset + bandOffsets[b]] = (float) sum; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP // BOTH ROI AND NODATA } else { // Array used during calculations final double[][] pixelKernel = new double[KERNEL_LINE_DIM][KERNEL_LINE_DIM]; double[] sumArray = new double[KERNEL_LINE_DIM]; double[] emptyArray = new double[KERNEL_LINE_DIM]; double[] tempData; // Value used in calculations short weight = 0; byte weightVert = 0; byte temp = 0; // Row temporary sum initialization double tempSum = 0; double sum = 0; for (int h = 0; h < dstHeight; h++) { int pixelOffset = lineOffset; lineOffset += lineStride; warp.warpRect(dst.getX(), dst.getY() + h, dstWidth, 1, warpData); int count = 0; for (int w = 0; w < dstWidth; w++) { final float sx = warpData[count++]; final float sy = warpData[count++]; final int xint = floor(sx); final int yint = floor(sy); final float xfrac = sx - xint; final float yfrac = sy - yint; if (xint < minX || xint >= maxX || yint < minY || yint >= maxY) { /* Fill with a background color. */ if (setBackground) { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } } } else { // X and Y offset initialization final int offsetX = KERNEL_LINE_DIM * (int) (shift * xfrac); final int offsetY = KERNEL_LINE_DIM * (int) (shift * yfrac); // // ROI // // checks with roi // Initialization of the flag indicating that at least one kernel pixels is inside the ROI boolean inRoi = false; for (int j = 0; j < KERNEL_LINE_DIM && !inRoi; j++) { for (int i = 0; i < KERNEL_LINE_DIM && !inRoi; i++) { int x = xint + (i - 1); int y = yint + (j - 1); if (roiBounds.contains(x, y)) { inRoi |= roiIter.getSample(x, y, 0) > 0; } } } if (inRoi) { // // NODATA // // checks with nodata for (int b = 0; b < dstBands; b++) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value // and check if every kernel pixel is a No Data for (int j = 0; j < KERNEL_LINE_DIM; j++) { for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel double sample = iterSource.getSampleDouble(xint + (i - 1), yint + (j - 1), b); pixelKernel[j][i] = sample; if (noDataRange.contains(sample)) { weight &= (0xffff - (1 << KERNEL_LINE_DIM * j + i)); // weigjtArray[j][z] = 0; } else { // weigjtArray[j][z] = 1; weight |= (1 << (KERNEL_LINE_DIM * j + i)); } } // Data elaboration for each line temp = (byte) ((weight >> KERNEL_LINE_DIM * j) & 0x0F); tempData = bicubicInpaintingDouble(pixelKernel[j], temp, emptyArray); tempSum = tempData[0] * dataHd[offsetX] + tempData[1] * dataHd[offsetX + 1] + tempData[2] * dataHd[offsetX + 2] + tempData[3] * dataHd[offsetX + 3]; if (temp > 0) { weightVert |= (1 << j); // weigjtArrayVertical[j] = 1; } else { weightVert &= (0x0F - (1 << j)); // weigjtArrayVertical[j] = 0; } sumArray[j] = tempSum; } // Control if the 16 pixel are all No Data if (weight == 0) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } else { tempData = bicubicInpaintingDouble(sumArray, weightVert, emptyArray); // Vertical sum update sum = tempData[0] * dataVd[offsetY] + tempData[1] * dataVd[offsetY + 1] + tempData[2] * dataVd[offsetY + 2] + tempData[3] * dataVd[offsetY + 3]; // Interpolation weight = 0; weightVert = 0; data[b][pixelOffset + bandOffsets[b]] = sum; } } } else { for (int b = 0; b < dstBands; b++) { data[b][pixelOffset + bandOffsets[b]] = destinationNoDataDouble; } } } // next desination pixel pixelOffset += pixelStride; } // COLS LOOP } // ROWS LOOP } iterSource.done(); } /** * Bicubic calculation for integer data * * @param b band * @param iterSource source image iterator * @param xint source pixel X position * @param yint source pixel Y position * @param offsetX X fractional offset * @param offsetY Y fractional offset * @param t optional color table * @return */ private long bicubicCalculationInt(int b, RandomIter iterSource, int xint, int yint, int offsetX, int offsetY, byte[] t) { // Temporary sum initialization long sum = 0; if (t == null) { // Cycle through all the 16 kernel pixel and calculation of the interpolated value for (int j = 0; j < KERNEL_LINE_DIM; j++) { // Row temporary sum initialization long temp = 0; for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int pixelValue = iterSource.getSample(xint + (i - 1), yint + (j - 1), b); // Update of the temporary sum temp += (pixelValue * dataHi[offsetX + i]); } // Vertical sum update sum += ((temp + round) >> precisionBits) * dataVi[offsetY + j]; } } else { // Cycle through all the 16 kernel pixel and calculation of the interpolated value for (int j = 0; j < KERNEL_LINE_DIM; j++) { // Row temporary sum initialization long temp = 0; for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel int pixelValue = t[iterSource.getSample(xint + (i - 1), yint + (j - 1), 0) & 0xFF] & 0xFF; // Update of the temporary sum temp += (pixelValue * dataHi[offsetX + i]); } // Vertical sum update sum += ((temp + round) >> precisionBits) * dataVi[offsetY + j]; } } // Interpolation return ((sum + round) >> precisionBits); } /** * Bicubic calculation for Float data * * @param b band * @param iterSource source image iterator * @param xint source pixel X position * @param yint source pixel Y position * @param offsetX X fractional offset * @param offsetY Y fractional offset * @return */ private double bicubicCalculationFloat(int b, RandomIter iterSource, int xint, int yint, int offsetX, int offsetY) { // Temporary sum initialization double sum = 0; // Cycle through all the 16 kernel pixel and calculation of the interpolated value for (int j = 0; j < KERNEL_LINE_DIM; j++) { // Row temporary sum initialization double temp = 0; for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel float pixelValue = iterSource.getSampleFloat(xint + (i - 1), yint + (j - 1), b); // Update of the temporary sum temp += (pixelValue * dataHf[offsetX + i]); } // Vertical sum update sum += temp * dataVf[offsetY + j]; } // Interpolation return sum; } /** * Bicubic calculation for Double data * * @param b band * @param iterSource source image iterator * @param xint source pixel X position * @param yint source pixel Y position * @param offsetX X fractional offset * @param offsetY Y fractional offset * @return */ private double bicubicCalculationDouble(int b, RandomIter iterSource, int xint, int yint, int offsetX, int offsetY) { // Temporary sum initialization double sum = 0; // Cycle through all the 16 kernel pixel and calculation of the interpolated value for (int j = 0; j < KERNEL_LINE_DIM; j++) { // Row temporary sum initialization double temp = 0; for (int i = 0; i < KERNEL_LINE_DIM; i++) { // Selection of one pixel double pixelValue = iterSource.getSampleDouble(xint + (i - 1), yint + (j - 1), b); // Update of the temporary sum temp += (pixelValue * dataHd[offsetX + i]); } // Vertical sum update sum += temp * dataVd[offsetY + j]; } // Interpolation return sum; } /** * Private method for extracting valid values from the input pixel no data values on a 4-pixel line This method is used for filling the no data * values inside the interpolation kernel with the values of the adjacent pixels * * @param array pixel array * @param weightSum value indicating how and where no data pixels are * @param emptyArray empty array to return in output * @return */ private static long[] bicubicInpainting(long[] array, short weightSum, long[] emptyArray) { // Absence of No Data, the pixels are returned. if (weightSum == 15) { return array; } long s_ = array[0]; long s0 = array[1]; long s1 = array[2]; long s2 = array[3]; emptyArray[0] = 0; emptyArray[1] = 0; emptyArray[2] = 0; emptyArray[3] = 0; // s2 s1 s0 s_ // 0/x 0/x 0/x 0/x switch (weightSum) { case 0: // 0 0 0 0 break; case 1: // 0 0 0 x emptyArray[0] = s_; emptyArray[1] = s_; emptyArray[2] = s_; emptyArray[3] = s_; break; case 2: // 0 0 x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = s0; emptyArray[3] = s0; break; case 3: // 0 0 x x emptyArray[0] = s_; emptyArray[1] = s0; emptyArray[2] = s0; emptyArray[3] = s0; break; case 4: // 0 x 0 0 emptyArray[0] = s1; emptyArray[1] = s1; emptyArray[2] = s1; emptyArray[3] = s1; break; case 5: // 0 x 0 x emptyArray[0] = s_; emptyArray[1] = (s_ + s1) / 2; emptyArray[2] = s1; emptyArray[3] = s1; break; case 6: // 0 x x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = s1; emptyArray[3] = s1; break; case 7: // 0 x x x emptyArray[0] = s_; emptyArray[1] = s0; emptyArray[2] = s1; emptyArray[3] = s1; break; case 8: // x 0 0 0 emptyArray[0] = s2; emptyArray[1] = s2; emptyArray[2] = s2; emptyArray[3] = s2; break; case 9: // x 0 0 x emptyArray[0] = s_; emptyArray[1] = (s_ + s2) / 2; emptyArray[2] = (s_ + s2) / 2; emptyArray[3] = s2; break; case 10: // x 0 x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = (s0 + s2) / 2; emptyArray[3] = s2; break; case 11: // x 0 x x emptyArray[0] = s_; emptyArray[1] = s0; emptyArray[2] = (s0 + s2) / 2; emptyArray[3] = s2; break; case 12: // x x 0 0 emptyArray[0] = s1; emptyArray[1] = s1; emptyArray[2] = s1; emptyArray[3] = s2; break; case 13: // x x 0 x emptyArray[0] = s_; emptyArray[1] = (s_ + s1) / 2; emptyArray[2] = s1; emptyArray[3] = s2; break; case 14: // x x x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = s1; emptyArray[3] = s2; break; default: throw new IllegalArgumentException("Array cannot be composed from more than 4 elements"); } return emptyArray; } /** * Private method for extracting valid values from the input pixel no data values on a 4-pixel line This method is used for filling the no data * values inside the interpolation kernel with the values of the adjacent pixels * * @param array pixel array * @param weightSum value indicating how and where no data pixels are * @param emptyArray empty array to return in output * @return */ private static double[] bicubicInpaintingDouble(double[] array, short weightSum, double[] emptyArray) { // Absence of No Data, the pixels are returned. if (weightSum == 15) { return array; } double s_ = array[0]; double s0 = array[1]; double s1 = array[2]; double s2 = array[3]; emptyArray[0] = 0; emptyArray[1] = 0; emptyArray[2] = 0; emptyArray[3] = 0; switch (weightSum) { case 0: // 0 0 0 0 break; case 1: // 0 0 0 x emptyArray[0] = s_; emptyArray[1] = s_; emptyArray[2] = s_; emptyArray[3] = s_; break; case 2: // 0 0 x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = s0; emptyArray[3] = s0; break; case 3: // 0 0 x x emptyArray[0] = s_; emptyArray[1] = s0; emptyArray[2] = s0; emptyArray[3] = s0; break; case 4: // 0 x 0 0 emptyArray[0] = s1; emptyArray[1] = s1; emptyArray[2] = s1; emptyArray[3] = s1; break; case 5: // 0 x 0 x emptyArray[0] = s_; emptyArray[1] = (s_ + s1) / 2; emptyArray[2] = s1; emptyArray[3] = s1; break; case 6: // 0 x x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = s1; emptyArray[3] = s1; break; case 7: // 0 x x x emptyArray[0] = s_; emptyArray[1] = s0; emptyArray[2] = s1; emptyArray[3] = s1; break; case 8: // x 0 0 0 emptyArray[0] = s2; emptyArray[1] = s2; emptyArray[2] = s2; emptyArray[3] = s2; break; case 9: // x 0 0 x emptyArray[0] = s_; emptyArray[1] = (s_ + s2) / 2; emptyArray[2] = (s_ + s2) / 2; emptyArray[3] = s2; break; case 10: // x 0 x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = (s0 + s2) / 2; emptyArray[3] = s2; break; case 11: // x 0 x x emptyArray[0] = s_; emptyArray[1] = s0; emptyArray[2] = (s0 + s2) / 2; emptyArray[3] = s2; break; case 12: // x x 0 0 emptyArray[0] = s1; emptyArray[1] = s1; emptyArray[2] = s1; emptyArray[3] = s2; break; case 13: // x x 0 x emptyArray[0] = s_; emptyArray[1] = (s_ + s1) / 2; emptyArray[2] = s1; emptyArray[3] = s2; break; case 14: // x x x 0 emptyArray[0] = s0; emptyArray[1] = s0; emptyArray[2] = s1; emptyArray[3] = s2; break; default: throw new IllegalArgumentException("Array cannot be composed from more than 4 elements"); } return emptyArray; } }
{ "content_hash": "cac5e61e575d609210b63cc794bbd913", "timestamp": "", "source": "github", "line_count": 3485, "max_line_length": 150, "avg_line_length": 46.551219512195125, "alnum_prop": 0.3739359308640149, "repo_name": "simboss/jai-ext", "id": "f60ee8cb4e2028f01d168498dd894783eebb1f5f", "size": "162903", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jt-warp/src/main/java/it/geosolutions/jaiext/warp/WarpBicubicOpImage.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.pico.hashids package object syntax { implicit class HashidsLongOps(x: Long) { def hashid(implicit hashids: Hashids): String = hashids.encode(x) } implicit class HashidsSeqLongOps(val self: Seq[Long]) { def hashid(implicit hashids: Hashids): String = hashids.encode(self: _*) } implicit class HashidsArrayLongOps(val self: Array[Long]) { def encodeHashid(implicit hashids: Hashids): String = hashids.encode(self: _*) } implicit class HashidsStringOps(x: String) { def unhashid(implicit hashids: Hashids): Seq[Long] = hashids.decode(x) def hashidHex(implicit hashids: Hashids): String = hashids.encodeHex(x) def unhashidHex(implicit hashids: Hashids): String = hashids.decodeHex(x) } }
{ "content_hash": "55762a27f77a7ce517a59fd391a7f107", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 82, "avg_line_length": 32.26086956521739, "alnum_prop": 0.7210242587601078, "repo_name": "pico-works/pico-hashids", "id": "0f31414a2333288ed3fdd964017a34de345babb8", "size": "742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pico-hashids/src/main/scala/org/pico/hashids/syntax/package.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "20543" }, { "name": "Shell", "bytes": "983" } ], "symlink_target": "" }
<?php namespace Llama\Modules\Commands; use Illuminate\Console\Command; use Llama\Modules\Exceptions\FileAlreadyExistException; use Llama\Modules\Generators\FileGenerator; abstract class BaseCommand extends Command { /** * The name of 'name' argument. * * @var string */ protected $argumentName = ''; /** * Get template contents. * * @return string */ abstract protected function getTemplateContents(); /** * Get the destination file path. * * @return string */ abstract protected function getDestinationFilePath(); /** * Execute the console command. */ public function fire() { $path = str_replace('\\', '/', $this->getDestinationFilePath()); if (! $this->laravel['files']->isDirectory($dir = dirname($path))) { $this->laravel['files']->makeDirectory($dir, 0777, true); } try { with(new FileGenerator($path, $this->getTemplateContents()))->generate(); $this->info("Created : {$path}"); } catch (FileAlreadyExistException $e) { $this->error("File : {$path} already exists."); } } /** * Get class name. * * @return string */ public function getClass() { return class_basename($this->argument($this->argumentName)); } /** * Get default namespace. * * @return string */ public function getDefaultNamespace() { return ''; } /** * Get class namespace. * * @param \Llama\Modules\Module $module * * @return string */ public function getClassNamespace($module) { $extra = str_replace($this->getClass(), '', $this->argument($this->argumentName)); $namespace = $this->laravel['modules']->getNamespace(); $namespace .= '\\' . $module->getStudlyName(); $namespace .= '\\' . $this->getDefaultNamespace(); $namespace .= '\\' . $extra; return trim(str_replace('/', '\\', $namespace), '\\'); } }
{ "content_hash": "35c356595bd28175c5108d4c820d642b", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 90, "avg_line_length": 24.09090909090909, "alnum_prop": 0.5438679245283019, "repo_name": "xuanhoa88/laravel-modules", "id": "adc7a2836fe017505f480f9abf5efa5ce4f3d50d", "size": "2120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Commands/BaseCommand.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "131719" } ], "symlink_target": "" }
#ifndef itkDemonsImageToImageMetricv4_h #define itkDemonsImageToImageMetricv4_h #include "itkImageToImageMetricv4.h" #include "itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.h" namespace itk { /** \class DemonsImageToImageMetricv4 * * \brief Class implementing demons metric. * * The implementation is taken from itkDemonsRegistrationFunction. * * The metric derivative can be calculated using image derivatives * either from the fixed or moving images. The default is to use fixed-image * gradients. See ObjectToObjectMetric::SetGradientSource to change * this behavior. * * An intensity threshold is used, below which image pixels are considered * equal for the purpose of derivative calculation. The threshold can be * changed by calling SetIntensityDifferenceThreshold. * * \note This metric supports only moving transforms with local support and * with a number of local parameters that matches the moving image dimension. * In particular, it's meant to be used with itkDisplacementFieldTransform and * derived classes. * * See DemonsImageToImageMetricv4GetValueAndDerivativeThreader::ProcessPoint * for algorithm implementation. * * \sa itkImageToImageMetricv4 * \ingroup ITKMetricsv4 */ template <typename TFixedImage, typename TMovingImage, typename TVirtualImage = TFixedImage, typename TInternalComputationValueType = double, typename TMetricTraits = DefaultImageToImageMetricTraitsv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputationValueType>> class ITK_TEMPLATE_EXPORT DemonsImageToImageMetricv4 : public ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputationValueType, TMetricTraits> { public: ITK_DISALLOW_COPY_AND_MOVE(DemonsImageToImageMetricv4); /** Standard class type aliases. */ using Self = DemonsImageToImageMetricv4; using Superclass = ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputationValueType, TMetricTraits>; using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(DemonsImageToImageMetricv4, ImageToImageMetricv4); /** Superclass types */ using MeasureType = typename Superclass::MeasureType; using DerivativeType = typename Superclass::DerivativeType; using FixedImagePointType = typename Superclass::FixedImagePointType; using FixedImagePixelType = typename Superclass::FixedImagePixelType; using FixedImageGradientType = typename Superclass::FixedImageGradientType; using MovingImagePointType = typename Superclass::MovingImagePointType; using MovingImagePixelType = typename Superclass::MovingImagePixelType; using MovingImageGradientType = typename Superclass::MovingImageGradientType; using MovingTransformType = typename Superclass::MovingTransformType; using JacobianType = typename Superclass::JacobianType; using VirtualImageType = typename Superclass::VirtualImageType; using VirtualIndexType = typename Superclass::VirtualIndexType; using VirtualPointType = typename Superclass::VirtualPointType; using VirtualSPointSetType = typename Superclass::VirtualPointSetType; using NumberOfParametersType = typename Superclass::NumberOfParametersType; /** It should be possible to derive the internal computation type from the class object. */ using InternalComputationValueType = TInternalComputationValueType; using ImageDimensionType = typename Superclass::ImageDimensionType; /* Image dimension accessors */ static constexpr ImageDimensionType VirtualImageDimension = TVirtualImage::ImageDimension; static constexpr ImageDimensionType FixedImageDimension = TFixedImage::ImageDimension; static constexpr ImageDimensionType MovingImageDimension = TMovingImage::ImageDimension; void Initialize() override; /** Accessors for the image intensity difference threshold use * in derivative calculation */ itkGetConstMacro(IntensityDifferenceThreshold, TInternalComputationValueType); itkSetMacro(IntensityDifferenceThreshold, TInternalComputationValueType); /** Get the denominator threshold used in derivative calculation. */ itkGetConstMacro(DenominatorThreshold, TInternalComputationValueType); protected: itkGetConstMacro(Normalizer, TInternalComputationValueType); DemonsImageToImageMetricv4(); ~DemonsImageToImageMetricv4() override = default; friend class DemonsImageToImageMetricv4GetValueAndDerivativeThreader< ThreadedImageRegionPartitioner<Superclass::VirtualImageDimension>, Superclass, Self>; friend class DemonsImageToImageMetricv4GetValueAndDerivativeThreader<ThreadedIndexedContainerPartitioner, Superclass, Self>; using DemonsDenseGetValueAndDerivativeThreaderType = DemonsImageToImageMetricv4GetValueAndDerivativeThreader< ThreadedImageRegionPartitioner<Superclass::VirtualImageDimension>, Superclass, Self>; using DemonsSparseGetValueAndDerivativeThreaderType = DemonsImageToImageMetricv4GetValueAndDerivativeThreader<ThreadedIndexedContainerPartitioner, Superclass, Self>; void PrintSelf(std::ostream & os, Indent indent) const override; private: /** Threshold below which the denominator term is considered zero. * Fixed programmatically in constructor. */ TInternalComputationValueType m_DenominatorThreshold; /** Threshold below which two intensity value are assumed to match. */ TInternalComputationValueType m_IntensityDifferenceThreshold; /* Used to normalize derivative calculation. Automatically calculated */ TInternalComputationValueType m_Normalizer; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION # include "itkDemonsImageToImageMetricv4.hxx" #endif #endif
{ "content_hash": "624948c44dd48c538b5692f7056c27af", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 119, "avg_line_length": 41.39310344827586, "alnum_prop": 0.7910696434521826, "repo_name": "LucasGandel/ITK", "id": "815a1dfdb8e12953baadc2db30c1b894e444fe7c", "size": "6758", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "306" }, { "name": "C", "bytes": "29710189" }, { "name": "C++", "bytes": "46556252" }, { "name": "CMake", "bytes": "1998251" }, { "name": "CSS", "bytes": "24960" }, { "name": "DIGITAL Command Language", "bytes": "709" }, { "name": "FORTRAN", "bytes": "2241251" }, { "name": "HTML", "bytes": "208088" }, { "name": "Io", "bytes": "1833" }, { "name": "Java", "bytes": "28598" }, { "name": "Lex", "bytes": "6877" }, { "name": "Makefile", "bytes": "13192" }, { "name": "Objective-C", "bytes": "49378" }, { "name": "Objective-C++", "bytes": "6591" }, { "name": "OpenEdge ABL", "bytes": "85139" }, { "name": "Perl", "bytes": "19692" }, { "name": "Prolog", "bytes": "4406" }, { "name": "Python", "bytes": "808900" }, { "name": "Ruby", "bytes": "296" }, { "name": "Shell", "bytes": "130535" }, { "name": "Tcl", "bytes": "74786" }, { "name": "XSLT", "bytes": "195448" }, { "name": "Yacc", "bytes": "20428" } ], "symlink_target": "" }
const settingsMock = { views: { appheaderbar: { logo: { name: 'Talend', onClick: 'menu:home', }, brand: { label: 'Data Preparation', onClick: 'menu:home', }, search: { onToggle: 'search:toggle', onBlur: 'search:toggle', onChange: 'search:all', onSelect: { preparation: 'menu:playground:preparation', dataset: 'dataset:open', folder: 'menu:folders', documentation: 'external:documentation', }, onKeyDown: 'search:focus', debounceTimeout: 300, }, userMenu: 'user:menu', help: 'external:help', products: 'products:menu', }, 'appheaderbar:playground': { logo: { name: 'Talend', onClick: 'menu:home', }, brand: { label: 'Data Preparation', onClick: 'menu:home', }, search: { onToggle: 'search:toggle', onBlur: 'search:toggle', onChange: 'search:all', onSelect: { preparation: 'menu:playground:preparation', dataset: 'dataset:open', folder: 'menu:folders', documentation: 'external:documentation', }, onKeyDown: 'search:focus', debounceTimeout: 300, }, userMenu: 'user:menu', help: 'external:help', products: 'products:menu', }, breadcrumb: { maxItems: 5, onItemClick: 'menu:folders', }, sidepanel: { onToggleDock: 'sidepanel:toggle', actions: ['menu:preparations', 'menu:datasets'], }, 'listview:folders': { list: { titleProps: { onClick: 'menu:folders', }, }, }, 'listview:preparations': { didMountActionCreator: 'preparations:fetch', list: { columns: [ { key: 'name', label: 'Name' }, { key: 'author', label: 'Author' }, { key: 'creationDate', label: 'Created' }, { key: 'lastModificationDate', label: 'Last change' }, { key: 'datasetName', label: 'Dataset' }, { key: 'nbSteps', label: 'Nb steps' }, ], items: [], itemProps: { classNameKey: 'className', }, titleProps: { displayModeKey: 'displayMode', iconKey: 'icon', key: 'name', onClick: 'menu:playground:preparation', onEditCancel: 'inventory:cancel-edit', onEditSubmit: 'preparation:submit-edit', }, sort: { field: 'name', isDescending: false, onChange: 'preparation:sort', }, }, toolbar: { sort: { options: [ { id: 'name', name: 'Name' }, { id: 'date', name: 'Creation Date' }, ], onChange: 'preparation:sort', }, display: { displayModes: [ 'table', 'large', ], onChange: 'preparation:display-mode', }, actionBar: { actions: { left: ['preparation:create', 'preparation:folder:create'], }, }, searchLabel: 'Find a preparation', }, }, 'listview:datasets': { didMountActionCreator: 'datasets:fetch', list: { columns: [ { key: 'name', label: 'Name' }, { key: 'statusActions', label: 'Actions', hideHeader: true, type: 'actions' }, { key: 'author', label: 'Author' }, { key: 'creationDate', label: 'Created' }, { key: 'nbRecords', label: 'Rows' }, ], items: [], itemProps: { classNameKey: 'className', }, titleProps: { displayModeKey: 'displayMode', iconKey: 'icon', key: 'name', onClick: 'dataset:open', onEditCancel: 'inventory:cancel-edit', onEditSubmit: 'dataset:submit-edit', }, sort: { field: 'name', isDescending: false, onChange: 'dataset:sort', }, }, toolbar: { sort: { options: [ { id: 'name', name: 'Name' }, { id: 'date', name: 'Creation Date' }, ], onChange: 'dataset:sort', }, display: { displayModes: [ 'table', 'large', ], onChange: 'preparation:display-mode', }, actionBar: { actions: { left: ['dataset:create'], }, }, searchLabel: 'Find a dataset', }, }, }, actions: { 'menu:preparations': { id: 'menu:preparations', name: 'Preparations', icon: 'talend-dataprep', type: '@@router/GO_CURRENT_FOLDER', payload: { method: 'go', args: ['home.preparations'], }, }, 'menu:datasets': { id: 'menu:datasets', name: 'Datasets', icon: 'talend-datastore', type: '@@router/GO', payload: { method: 'go', args: ['home.datasets'], }, }, 'menu:folders': { id: 'menu:folders', name: 'Folders', icon: 'talend-folder', type: '@@router/GO_FOLDER', payload: { method: 'go', args: ['home.preparations'], }, }, 'menu:playground:preparation': { id: 'menu:playground:preparation', name: 'Open Preparation', icon: 'talend-dataprep', type: '@@router/GO_PREPARATION', payload: { method: 'go', args: ['playground.preparation'], }, }, 'list:dataset:preparations': { id: 'list:dataset:preparations', name: 'Open preparation', icon: 'talend-dataprep', displayMode: 'dropdown', items: 'preparations', dynamicAction: 'menu:playground:preparation', staticActions: ['dataset:open'], }, 'sidepanel:toggle': { id: 'sidepanel:toggle', name: 'Click here to toggle the side panel', icon: '', type: '@@sidepanel/TOGGLE', payload: { method: 'toggleHomeSidepanel', args: [], }, }, 'onboarding:preparation': { id: 'onboarding:preparation', name: 'Click here to discover the application', icon: 'talend-board', type: '@@onboarding/START_TOUR', payload: { method: 'startTour', args: [ 'preparation', ], }, }, 'modal:feedback': { id: 'modal:feedback', name: 'Send feedback to Talend', icon: 'talend-bubbles', type: '@@modal/SHOW', payload: { method: 'showFeedback', }, }, 'external:help': { id: 'external:help', name: 'Open Online Help', icon: 'talend-question-circle', type: '@@external/OPEN_WINDOW', payload: { method: 'open', args: [ 'https://help.talend.com/#/search/all?filters=EnrichPlatform%253D%2522Talend+Data+Preparation%2522%2526EnrichVersion%253D%25222.1%2522&utm_medium=dpdesktop&utm_source=header', ], }, }, 'user:logout': { id: 'user:logout', name: 'Logout', icon: 'icon-logout', type: '@@user/logout', payload: { method: 'logout', }, }, 'product:producta': { displayMode: 'ActionSettings', id: 'product:producta', name: 'Product A', icon: 'talend-logo-a', type: '@@external/OPEN_WINDOW', payload: { args: ['https://producta.tlnd'], method: 'open', }, }, 'product:productb': { displayMode: 'ActionSettings', id: 'product:productb', name: 'Product B', icon: 'talend-logo-b', type: '@@external/OPEN_WINDOW', payload: { args: ['https://productb.tlnd'], method: 'open', }, }, 'product:productc': { displayMode: 'ActionSettings', id: 'product:productc', name: 'Product C', icon: 'talend-logo-c', type: '@@external/OPEN_WINDOW', payload: { args: ['https://productc.tlnd'], method: 'open', }, }, 'products:menu': { displayMode: 'dropdown', id: 'products:menu', name: 'Apps', icon: 'talend-launcher', staticActions: [ 'product:producta', 'product:productb', 'product:productc', ], }, 'dataset:open': { id: 'dataset:open', name: 'Open dataset', icon: '', type: '@@dataset/OPEN', }, 'dataset:display-mode': { id: 'dataset:display-mode', name: 'Change dataset display mode', icon: '', type: '@@inventory/DISPLAY_MODE', payload: { method: 'setDatasetsDisplayMode', args: [], }, }, 'dataset:sort': { id: 'dataset:sort', name: 'Change dataset sort', icon: '', type: '@@dataset/SORT', }, 'dataset:submit-edit': { id: 'dataset:submit-edit', name: 'Submit name edition', icon: 'talend-check', type: '@@dataset/SUBMIT_EDIT', }, 'dataset:remove': { id: 'dataset:remove', name: 'Remove dataset', icon: 'talend-trash', type: '@@dataset/REMOVE', payload: { method: 'remove', args: [], }, }, 'dataset:clone': { id: 'dataset:clone', name: 'Copy dataset', icon: 'talend-files-o', type: '@@dataset/CLONE', payload: { method: 'clone', args: [], }, }, 'dataset:favorite': { id: 'dataset:favorite', name: 'Add dataset in your favorite list', icon: 'talend-star', type: '@@dataset/FAVORITE', payload: { method: 'toggleFavorite', args: [], }, }, 'dataset:update': { id: 'dataset:update', name: 'Update dataset ', icon: 'talend-file-move', type: '@@dataset/UPDATE', payload: { method: '', args: [], }, }, 'dataset:create': { id: 'dataset:create', name: 'Add Dataset', icon: 'talend-plus', type: '@@dataset/CREATE', bsStyle: 'primary', displayMode: 'splitDropdown', items: [], }, 'datasets:fetch': { id: 'datasets:fetch', name: 'Fetch all datasets', icon: 'talend-dataprep', type: '@@dataset/DATASET_FETCH', payload: { method: 'init', args: [], }, }, divider: { id: 'divider', divider: true, }, 'preparation:display-mode': { id: 'preparation:display-mode', name: 'Change preparation display mode', icon: '', type: '@@inventory/DISPLAY_MODE', payload: { method: 'setPreparationsDisplayMode', args: [], }, }, 'preparation:sort': { id: 'preparation:sort', name: 'Change preparation sort', icon: '', type: '@@preparation/SORT', payload: { method: 'setPreparationsSortFromIds', args: [], }, }, 'preparation:create': { id: 'preparation:create', name: 'Create preparation', icon: 'talend-plus', type: '@@preparation/CREATE', payload: { method: 'togglePreparationCreator', args: [], }, }, 'preparation:folder:create': { id: 'preparation:folder:create', name: 'Create folder', icon: 'talend-folder', type: '@@preparation/CREATE', payload: { method: 'toggleFolderCreator', args: [], }, }, 'preparations:fetch': { id: 'preparations:fetch', name: 'Fetch preparations from current folder', icon: 'talend-dataprep', type: '@@preparation/FETCH', payload: { method: 'init', args: [], }, }, 'preparation:copy-move': { id: 'preparation:copy-move', name: 'Copy/Move preparation', icon: 'talend-copy_dataset', type: '@@preparation/COPY_MOVE', payload: { method: 'copyMove', args: [], }, }, 'inventory:edit': { id: 'inventory:edit', name: 'Edit name', icon: 'talend-pencil', type: '@@inventory/EDIT', payload: { method: 'enableInventoryEdit', args: [], }, }, 'inventory:cancel-edit': { id: 'inventory:cancel-edit', name: 'Cancel name edition', icon: 'talend-crossbig', type: '@@inventory/CANCEL_EDIT', payload: { method: 'disableInventoryEdit', args: [], }, }, 'preparation:submit-edit': { id: 'preparation:submit-edit', name: 'Submit name edition', icon: 'talend-check', type: '@@preparation/VALIDATE_EDIT', payload: { method: '', args: [], }, }, 'preparation:remove': { id: 'preparation:remove', name: 'Remove preparation', icon: 'talend-delete', type: '@@preparation/REMOVE', payload: { method: 'remove', args: [], }, }, 'preparation:folder:remove': { id: 'preparation:folder:remove', name: 'Remove folder', icon: 'talend-trash', type: '@@preparation/FOLDER_REMOVE', payload: { method: 'removeFolder', args: [], }, }, 'search:toggle': { id: 'search:toggle', icon: 'talend-search', type: '@@search/TOGGLE', }, 'search:all': { id: 'search:all', type: '@@search/ALL', }, 'search:focus': { id: 'search:focus', type: '@@search/FOCUS', }, 'external:documentation': { id: 'external:documentation', type: '@@external/OPEN_WINDOW', icon: 'talend-question-circle', name: 'Documentation', payload: { method: 'open', }, }, 'user:menu': { id: 'user:menu', name: 'anonymousUser', icon: 'talend-user-circle', displayMode: 'dropdown', staticActions: [ 'modal:about', 'onboarding:preparation', 'divider', 'modal:feedback', 'divider', 'user:logout', ], }, 'version:toggle': { displayMode: 'ActionSettings', id: 'version:toggle', name: 'Toggle version', type: '@@version/VERSION_TOGGLE', payload: { method: 'toggleVersion', }, }, 'version:select': { displayMode: 'ActionSettings', id: 'version:select', name: 'Select version', type: '@@router/GO_PREPARATION_READ_ONLY', payload: { args: 'version', method: 'go', }, }, 'modal:about': { displayMode: 'ActionSettings', id: 'modal:about', name: 'About Data Preparation', icon: 'talend-info-circle', type: '@@modal/SHOW', payload: { method: 'toggleAbout', }, }, }, uris: { api: '/api', apiAggregate: '/api/aggregate', apiDatasets: '/api/datasets', apiUploadDatasets: '/api/datasets', apiExport: '/api/export', apiFolders: '/api/folders', apiMail: '/api/mail', apiPreparations: '/api/preparations', apiPreparationsPreview: '/api/preparations/preview', apiSearch: '/api/search', apiSettings: '/api/settings', apiTcomp: '/api/tcomp', apiTransform: '/api/transform', apiTypes: '/api/types', apiUpgradeCheck: '/api/upgrade/check', apiVersion: '/api/version', }, help: { versionFacet: 'HELP_VERSION_FACET', languageFacet: 'HELP_LANGUAGE_FACET', searchUrl: 'HELP_SEARCH_URL', fuzzyUrl: 'HELP_FUZZY_URL', exactUrl: 'HELP_EXACT_URL', }, context: {}, }; export default settingsMock;
{ "content_hash": "063e88d94007dac0465589bfec6ecea4", "timestamp": "", "source": "github", "line_count": 617, "max_line_length": 180, "avg_line_length": 22.12155591572123, "alnum_prop": 0.5762326910396366, "repo_name": "Talend/data-prep", "id": "15a0f884d31f0958f15fa7fa5b14668390826446", "size": "14123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dataprep-webapp/src/mocks/Settings.mock.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "256666" }, { "name": "Gherkin", "bytes": "67129" }, { "name": "HTML", "bytes": "192328" }, { "name": "Java", "bytes": "3666524" }, { "name": "JavaScript", "bytes": "3478993" } ], "symlink_target": "" }
using StructureMap.Interceptors; using StructureMap.Pipeline; namespace TryCatchFail.LearnStructureMap.Lesson1.Utils { public class DecoratorHelper<TTarget> { private readonly SmartInstance<TTarget> _instance; public DecoratorHelper(SmartInstance<TTarget> instance) { _instance = instance; } public DecoratedInstance<TTarget> With<TDecorator>() { ContextEnrichmentHandler<TTarget> decorator = (ctx, t) => { var pluginType = ctx.BuildStack.Current.RequestedType; ctx.RegisterDefault(pluginType, t); return ctx.GetInstance<TDecorator>(); }; _instance.EnrichWith(decorator); return new DecoratedInstance<TTarget>(_instance, decorator); } } }
{ "content_hash": "1bcd8a9951e31782381bc4ab168265df", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 105, "avg_line_length": 30.870967741935484, "alnum_prop": 0.5381400208986415, "repo_name": "MattHoneycutt/Presentations", "id": "cde3b30f17c2ee8dbe2ebe0a1939e236a105667a", "size": "957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "StructureMappingYourWayToBetterSoftware/TryCatchFail.LearnStructureMap/TryCatchFail.LearnStructureMap.Lesson1/Utils/DecoratorHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "19553" }, { "name": "C#", "bytes": "65942" }, { "name": "JavaScript", "bytes": "469362" }, { "name": "PowerShell", "bytes": "106503" }, { "name": "Puppet", "bytes": "2040" } ], "symlink_target": "" }