text
stringlengths
2
1.04M
meta
dict
<!-- Generated by pkgdown: do not edit by hand --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Definition of an Optiwells well field configuration — owConfigure • kwb.wtaq</title> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha384-nrOSfDHtoPMzJHjVTdCopGqIqeYETSXhZDFyniQ8ZHcVy08QesyHcnOUpMpqnmWq" crossorigin="anonymous"></script> <!-- Bootstrap --> <link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cerulean/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Font Awesome icons --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous"> <!-- clipboard.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js" integrity="sha384-cV+rhyOuRHc9Ub/91rihWcGmMmCXDeksTtCihMupQHSsi8GIIRDG0ThDc3HGQFJ3" crossorigin="anonymous"></script> <!-- sticky kit --> <script src="https://cdnjs.cloudflare.com/ajax/libs/sticky-kit/1.1.3/sticky-kit.min.js" integrity="sha256-c4Rlo1ZozqTPE2RLuvbusY3+SU1pQaJC0TjuhygMipw=" crossorigin="anonymous"></script> <!-- pkgdown --> <link href="../pkgdown.css" rel="stylesheet"> <script src="../pkgdown.js"></script> <!-- docsearch --> <script src="../docsearch.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css" /> <link href="../docsearch.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin="anonymous"></script> <meta property="og:title" content="Definition of an Optiwells well field configuration — owConfigure" /> <meta property="og:description" content="Returns a user-defined Optiwells configuration on which e.g. owGetDrawdowns can be run." /> <meta name="twitter:card" content="summary" /> <!-- mathjax --> <script src='https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container template-reference-topic"> <header> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <span class="navbar-brand"> <a class="navbar-link" href="../index.html">kwb.wtaq</a> <span class="label label-default" data-toggle="tooltip" data-placement="bottom" title="Released package">0.2.1</span> </span> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li> <a href="../index.html">Home</a> </li> <li> <a href="../tutorial/index.html">Workflow</a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> Articles <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li> <a href="../articles/kwbwtaq_Tutorial.html">Workflow Short</a> </li> <li> <a href="../articles/kwbwtaq_ParameterTable.html">Parameter Table</a> </li> </ul> </li> <li> <a href="../reference/index.html">Reference</a> </li> <li> <a href="../news/index.html">News</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li> <a href="https://github.com/KWB-R/kwb.wtaq"> <span class="fa fa-github fa-lg"></span> </a> </li> </ul> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="search" class="form-control" name="search-input" id="search-input" placeholder="Search..." aria-label="Search for..." autocomplete="off"> </div> </form> </div><!--/.nav-collapse --> </div><!--/.container --> </div><!--/.navbar --> </header> <div class="row"> <div class="col-md-9 contents"> <div class="page-header"> <h1>Definition of an Optiwells well field configuration</h1> <div class="hidden name"><code>owConfigure.Rd</code></div> </div> <div class="ref-description"> <p>Returns a user-defined Optiwells configuration on which e.g. <code><a href='owGetDrawdowns.html'>owGetDrawdowns</a></code> can be run.</p> </div> <pre class="usage"><span class='fu'>owConfigure</span>(<span class='kw'>wellfield</span> <span class='kw'>=</span> <span class='kw'>NULL</span>, <span class='kw'>aquifer</span> <span class='kw'>=</span> <span class='kw'>NULL</span>, <span class='kw'>drainage</span> <span class='kw'>=</span> <span class='kw'>NULL</span>)</pre> <h2 class="hasAnchor" id="arguments"><a class="anchor" href="#arguments"></a>Arguments</h2> <table class="ref-arguments"> <colgroup><col class="name" /><col class="desc" /></colgroup> <tr> <th>wellfield</th> <td><p>Optiwells wellfield configuration. Data frame</p></td> </tr> <tr> <th>aquifer</th> <td><p>WTAQ aquifer configuration as returned by <code><a href='wtConfigureAquifer.html'>wtConfigureAquifer</a></code></p></td> </tr> <tr> <th>drainage</th> <td><p>WTAQ drainage configuration as returned by <code><a href='wtConfigureDrainage.html'>wtConfigureDrainage</a></code></p></td> </tr> </table> <h2 class="hasAnchor" id="value"><a class="anchor" href="#value"></a>Value</h2> <p>list with elements <em>wellfield</em> (configuration of well characteristics), <em>aquifer</em> (WTAQ aquifer configuration) and <em>drainage</em> (WTAQ drainage configuration).</p> <h2 class="hasAnchor" id="see-also"><a class="anchor" href="#see-also"></a>See also</h2> <div class='dont-index'><p><code><a href='owRandomConfiguration.html'>owRandomConfiguration</a></code></p></div> </div> <div class="col-md-3 hidden-xs hidden-sm" id="sidebar"> <h2>Contents</h2> <ul class="nav nav-pills nav-stacked"> <li><a href="#arguments">Arguments</a></li> <li><a href="#value">Value</a></li> <li><a href="#see-also">See also</a></li> </ul> <h2>Author</h2> Hauke Sonnenberg </div> </div> <footer> <div class="copyright"> <p>Developed by Hauke Sonnenberg.</p> </div> <div class="pkgdown"> <p>Site built with <a href="http://pkgdown.r-lib.org/">pkgdown</a>.</p> </div> </footer> </div> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"></script> <script> docsearch({ apiKey: '90c7003e99a08c7c2db10f5bb0d17a79', indexName: 'kwb_wtaq', inputSelector: 'input#search-input.form-control', transformData: function(hits) { return hits.map(function (hit) { hit.url = updateHitURL(hit); return hit; }); } }); </script> </body> </html>
{ "content_hash": "65cd388136272b28522ecf359dbc4ffe", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 331, "avg_line_length": 34.63513513513514, "alnum_prop": 0.6506697880088438, "repo_name": "KWB-R/kwb.wtaq", "id": "6cccdaf5c5f8fd83a030dcb9eaa4d17265413c1c", "size": "7695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/reference/owConfigure.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3084" }, { "name": "Fortran", "bytes": "420199" }, { "name": "R", "bytes": "164369" }, { "name": "Shell", "bytes": "473" }, { "name": "TeX", "bytes": "3307" } ], "symlink_target": "" }
namespace RfxCom.Messages { public class InterfaceControlSubType : Field<InterfaceControlSubType> { public static InterfaceControlSubType ModeCommand = new InterfaceControlSubType(0x00, "Mode Command"); internal InterfaceControlSubType(byte value, string description) : base(value, description) { } } }
{ "content_hash": "91a0bab7c26c349d5134a9a6e5ca0269", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 110, "avg_line_length": 26.142857142857142, "alnum_prop": 0.680327868852459, "repo_name": "nicholasham/RfxCom", "id": "997ecdee11ff84790ebd538c40d4a797d3a9211b", "size": "368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/RfxCom/Messages/InterfaceControlSubType.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "62352" }, { "name": "JavaScript", "bytes": "4627" }, { "name": "Shell", "bytes": "66" } ], "symlink_target": "" }
/* */ "format cjs"; "use strict"; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var isBoolean = _interopRequire(require("lodash/lang/isBoolean")); var each = _interopRequire(require("lodash/collection/each")); var map = _interopRequire(require("lodash/collection/map")); var t = _interopRequireWildcard(require("../../types")); function crawl(node) { var state = arguments[1] === undefined ? {} : arguments[1]; if (t.isMemberExpression(node)) { crawl(node.object, state); if (node.computed) crawl(node.property, state); } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { crawl(node.left, state); crawl(node.right, state); } else if (t.isCallExpression(node)) { state.hasCall = true; crawl(node.callee, state); } else if (t.isFunction(node)) { state.hasFunction = true; } else if (t.isIdentifier(node)) { var _state = state; if (!_state.hasHelper) _state.hasHelper = isHelper(node.callee); } return state; } function isHelper(node) { if (t.isMemberExpression(node)) { return isHelper(node.object) || isHelper(node.property); } else if (t.isIdentifier(node)) { return node.name === "require" || node.name[0] === "_"; } else if (t.isCallExpression(node)) { return isHelper(node.callee); } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { return false; } } function isType(node) { return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); } exports.nodes = { AssignmentExpression: function AssignmentExpression(node) { var state = crawl(node.right); if (state.hasCall && state.hasHelper || state.hasFunction) { return { before: state.hasFunction, after: true }; } }, SwitchCase: function SwitchCase(node, parent) { return { before: node.consequent.length || parent.cases[0] === node }; }, LogicalExpression: function LogicalExpression(node) { if (t.isFunction(node.left) || t.isFunction(node.right)) { return { after: true }; } }, Literal: function Literal(node) { if (node.value === "use strict") { return { after: true }; } }, CallExpression: function CallExpression(node) { if (t.isFunction(node.callee) || isHelper(node)) { return { before: true, after: true }; } }, VariableDeclaration: function VariableDeclaration(node) { for (var i = 0; i < node.declarations.length; i++) { var declar = node.declarations[i]; var enabled = isHelper(declar.id) && !isType(declar.init); if (!enabled) { var state = crawl(declar.init); enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; } if (enabled) { return { before: true, after: true }; } } }, IfStatement: function IfStatement(node) { if (t.isBlockStatement(node.consequent)) { return { before: true, after: true }; } } }; exports.nodes.Property = exports.nodes.SpreadProperty = function (node, parent) { if (parent.properties[0] === node) { return { before: true }; } }; exports.list = { VariableDeclaration: function VariableDeclaration(node) { return map(node.declarations, "init"); }, ArrayExpression: function ArrayExpression(node) { return node.elements; }, ObjectExpression: function ObjectExpression(node) { return node.properties; } }; each({ Function: true, Class: true, Loop: true, LabeledStatement: true, SwitchStatement: true, TryStatement: true }, function (amounts, type) { if (isBoolean(amounts)) { amounts = { after: amounts, before: amounts }; } each([type].concat(t.FLIPPED_ALIAS_KEYS[type] || []), function (type) { exports.nodes[type] = function () { return amounts; }; }); });
{ "content_hash": "417cfe588f96f25a97845f4e6a35158d", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 140, "avg_line_length": 25.221556886227546, "alnum_prop": 0.622269705603039, "repo_name": "zartata/aurelia-reporter", "id": "2ca17440a04820410131b2e4e40f5b044baa1620", "size": "4212", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "jspm_packages/npm/babel-core@5.1.13/lib/babel/generation/node/whitespace.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "130" }, { "name": "CSS", "bytes": "126639" }, { "name": "CoffeeScript", "bytes": "2294" }, { "name": "HTML", "bytes": "23342" }, { "name": "JavaScript", "bytes": "3221299" }, { "name": "LiveScript", "bytes": "5446" }, { "name": "Makefile", "bytes": "880" }, { "name": "Shell", "bytes": "3398" } ], "symlink_target": "" }
Measure the frequency of a digital input on the BeagleBone Black ## Motivation I have a vehicle that didn't come with an RPM gauge, so I'm using a BBB board to implement one (among other things). ## Implementation The processor on the BBB has two built in PRUs (Programmable Runtime Units). These run independently of the linux operating system at a fixed clock frequency of 200Mhz, making them useful for operations requiring precise and reliable timing. I'm using a simple program written in PRU assembly to measure the time between rising edges on one of the PRU's input pins. Simultaneously, a python script runs on the main core and reads the measured value from the PRU's RAM. The [pypruss](https://bitbucket.org/intelligentagent/pypruss) library is used to greatly simplify usage of the pru. ## Usage Ensure the TI PRU assembler (pasm) is installed and that this project's Makefile points to it. Also make sure the uio_pruss kernel module is avialable (this depends on yout kernel version). Finally, multiplex the relevant pin as a pru input. On my system I do this: # config-pin P8.15 pruin Assemble and run the pru code: # make # python rpm.py Run readmem.py to continuously read the values saved in the PRU memory and convert them to seconds. # sudo python readmem.py
{ "content_hash": "5da9810d4cf9eabf344dbd149ad32efc", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 265, "avg_line_length": 52.64, "alnum_prop": 0.7667173252279635, "repo_name": "sv3/freq", "id": "a3bb993e01ebc4911cce1e57c8748e79f9ca3d7b", "size": "1323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3578" }, { "name": "Makefile", "bytes": "143" }, { "name": "Python", "bytes": "1491" } ], "symlink_target": "" }
package org.geogit.geotools.porcelain; import java.util.Arrays; import jline.UnsupportedTerminal; import jline.console.ConsoleReader; import org.geogit.api.porcelain.CommitOp; import org.geogit.cli.GeogitCLI; import org.geogit.test.integration.RepositoryTestCase; import org.geotools.data.AbstractDataStoreFactory; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class PGExportTest extends RepositoryTestCase { @Rule public ExpectedException exception = ExpectedException.none(); private GeogitCLI cli; private static AbstractDataStoreFactory factory; @BeforeClass public static void oneTimeSetup() throws Exception { factory = TestHelper.createTestFactory(); } @Override public void setUpInternal() throws Exception { ConsoleReader consoleReader = new ConsoleReader(System.in, System.out, new UnsupportedTerminal()); cli = new GeogitCLI(consoleReader); cli.setGeogit(geogit); // Add points insertAndAdd(points1); insertAndAdd(points2); insertAndAdd(points3); geogit.command(CommitOp.class).call(); // Add lines insertAndAdd(lines1); insertAndAdd(lines2); insertAndAdd(lines3); geogit.command(CommitOp.class).call(); } @Override public void tearDownInternal() throws Exception { cli.close(); } @Test public void testExport() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("Points", "Points"); exportCommand.dataStoreFactory = factory; exportCommand.run(cli); } @Test public void testNullDataStore() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("Points", "Points"); exportCommand.dataStoreFactory = TestHelper.createNullTestFactory(); exportCommand.run(cli); } @Test public void testNoArgs() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList(); exportCommand.dataStoreFactory = TestHelper.createNullTestFactory(); exportCommand.run(cli); } @Test public void testExportToTableThatExists() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("Points", "table1"); exportCommand.dataStoreFactory = factory; exportCommand.run(cli); } @Test public void testExportToTableThatExistsWithOverwrite() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("WORK_HEAD:Points", "testTable"); exportCommand.dataStoreFactory = factory; exportCommand.run(cli); exportCommand.args = Arrays.asList("Lines", "testTable"); exportCommand.overwrite = true; exportCommand.run(cli); } @Test public void testExportWithNonexistentFeatureTypeTree() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("invalidType", "invalidTable"); exportCommand.dataStoreFactory = factory; exception.expect(IllegalArgumentException.class); exportCommand.run(cli); } @Test public void testExportWithNullTable() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("Points", null); exportCommand.dataStoreFactory = factory; exception.expect(IllegalArgumentException.class); exportCommand.run(cli); } @Test public void testExportWithNullFeatureType() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList(null, "invalidTable"); exportCommand.dataStoreFactory = factory; exception.expect(IllegalArgumentException.class); exportCommand.run(cli); } @Test public void testExportWithEmptyStringForFeatureType() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("", "invalidTable"); exportCommand.dataStoreFactory = factory; exception.expect(IllegalArgumentException.class); exportCommand.run(cli); } @Test public void testExportWithEmptyStringForTable() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("Points", ""); exportCommand.dataStoreFactory = factory; exception.expect(IllegalArgumentException.class); exportCommand.run(cli); } @Test public void testExportWithFeatureNameInsteadOfType() throws Exception { PGExport exportCommand = new PGExport(); exportCommand.args = Arrays.asList("Points/Points.1", "invalidTable"); exportCommand.dataStoreFactory = factory; exception.expect(IllegalArgumentException.class); exportCommand.run(cli); } }
{ "content_hash": "1fa413c96a4a6b36002d02b86d061ca4", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 78, "avg_line_length": 32.40127388535032, "alnum_prop": 0.6864556713190486, "repo_name": "rouault/GeoGit", "id": "212a51c9e66fefe68cbeaef1e53157522b5a28f4", "size": "5087", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/geotools/src/test/java/org/geogit/geotools/porcelain/PGExportTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "2837662" }, { "name": "JavaScript", "bytes": "38442" }, { "name": "Python", "bytes": "18719" }, { "name": "Shell", "bytes": "6363" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using TeamCityBuildChanges.ExternalApi.Rally; using TeamCityBuildChanges.ExternalApi.TeamCity; namespace TeamCityBuildChanges.IssueDetailResolvers { public class RallyIssueResolver : IExternalIssueResolver { private readonly IRallyApi _rallyApi; private readonly Regex _defectIssueRegex; private readonly Regex _userStoryIssueRegex; public RallyIssueResolver(IRallyApi rallyApi) { _rallyApi = rallyApi; _defectIssueRegex = new Regex(@"(^|\W)(?<Id>DE[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); _userStoryIssueRegex = new Regex(@"(^|\W)(?<Id>US[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); } public IEnumerable<ExternalIssueDetails> GetDetails(IEnumerable<Issue> issues) { var artifacts = new List<ExternalApi.Rally.Artifact>(); foreach (var issue in issues) { if (_defectIssueRegex.IsMatch(issue.Id)) artifacts.Add(_rallyApi.GetRallyDefect(issue.Id)); if (_userStoryIssueRegex.IsMatch(issue.Id)) artifacts.Add(_rallyApi.GetRallyUserStory(issue.Id)); } var result = artifacts.Where(a => a != null).Select(a => new ExternalIssueDetails { Id = a.FormattedId, Created = a.Created.ToString("yyyy-MM-dd"), Type = a.GetType().Name, Status = a.State, Summary = a.Name, Description = a.Description, Url = a.Url }).ToArray(); return result; } public IEnumerable<Issue> GetIssues(IEnumerable<ChangeDetail> changeDetails) { var issues = new List<Issue>(); foreach (var change in changeDetails) { var defectIssues = _defectIssueRegex.Matches(change.Comment) .Cast<Match>() .Select(x => new Issue { Id = x.Groups["Id"].Value }) .ToList(); issues.AddRange(defectIssues); } var distinct = issues.Distinct(new IssueEqualityComparer()); return distinct; } } }
{ "content_hash": "56b504ad65f7528057577cd279fe840d", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 120, "avg_line_length": 36.96923076923077, "alnum_prop": 0.5659592176446109, "repo_name": "BenPhegan/TeamCityBuildChanges", "id": "420bcfd2003b60d2a76ed9581fc63151703157e5", "size": "2403", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "TeamCityBuildChanges/IssueDetailResolvers/RallyIssueResolver.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "163448" } ], "symlink_target": "" }
/*globals cordova */ "use strict"; var Adapter = require('./adapter'); var utils = require('./utils'); var TaskQueue = require('./taskqueue'); var Promise = utils.Promise; function defaultCallback(err) { if (err && global.debug) { console.error(err); } } utils.inherits(PouchDB, Adapter); function PouchDB(name, opts, callback) { if (!(this instanceof PouchDB)) { return new PouchDB(name, opts, callback); } var self = this; if (typeof opts === 'function' || typeof opts === 'undefined') { callback = opts; opts = {}; } if (name && typeof name === 'object') { opts = name; name = undefined; } if (typeof callback === 'undefined') { callback = defaultCallback; } opts = opts || {}; this.__opts = opts; var oldCB = callback; self.auto_compaction = opts.auto_compaction; self.prefix = PouchDB.prefix; Adapter.call(self); self.taskqueue = new TaskQueue(); var promise = new Promise(function (fulfill, reject) { callback = function (err, resp) { if (err) { return reject(err); } delete resp.then; fulfill(resp); }; opts = utils.clone(opts); var originalName = opts.name || name; var backend, error; (function () { try { if (typeof originalName !== 'string') { error = new Error('Missing/invalid DB name'); error.code = 400; throw error; } backend = PouchDB.parseAdapter(originalName, opts); opts.originalName = originalName; opts.name = backend.name; if (opts.prefix && backend.adapter !== 'http' && backend.adapter !== 'https') { opts.name = opts.prefix + opts.name; } opts.adapter = opts.adapter || backend.adapter; self._adapter = opts.adapter; self._db_name = originalName; if (!PouchDB.adapters[opts.adapter]) { error = new Error('Adapter is missing'); error.code = 404; throw error; } if (!PouchDB.adapters[opts.adapter].valid()) { error = new Error('Invalid Adapter'); error.code = 404; throw error; } } catch (err) { self.taskqueue.fail(err); self.changes = utils.toPromise(function (opts) { if (opts.complete) { opts.complete(err); } }); } }()); if (error) { return reject(error); // constructor error, see above } self.adapter = opts.adapter; // needs access to PouchDB; self.replicate = {}; self.replicate.from = function (url, opts, callback) { return self.constructor.replicate(url, self, opts, callback); }; self.replicate.to = function (url, opts, callback) { return self.constructor.replicate(self, url, opts, callback); }; self.sync = function (dbName, opts, callback) { return self.constructor.sync(self, dbName, opts, callback); }; self.replicate.sync = self.sync; self.destroy = utils.adapterFun('destroy', function (callback) { var self = this; var opts = this.__opts || {}; self.info(function (err, info) { if (err) { return callback(err); } opts.internal = true; self.constructor.destroy(info.db_name, opts, callback); }); }); PouchDB.adapters[opts.adapter].call(self, opts, function (err) { if (err) { if (callback) { self.taskqueue.fail(err); callback(err); } return; } function destructionListener(event) { if (event === 'destroyed') { self.emit('destroyed'); PouchDB.removeListener(originalName, destructionListener); } } PouchDB.on(originalName, destructionListener); self.emit('created', self); PouchDB.emit('created', opts.originalName); self.taskqueue.ready(self); callback(null, self); }); if (opts.skipSetup) { self.taskqueue.ready(self); process.nextTick(function () { callback(null, self); }); } if (utils.isCordova()) { //to inform websql adapter that we can use api cordova.fireWindowEvent(opts.name + "_pouch", {}); } }); promise.then(function (resp) { oldCB(null, resp); }, oldCB); self.then = promise.then.bind(promise); self.catch = promise.catch.bind(promise); } PouchDB.debug = require('debug'); module.exports = PouchDB;
{ "content_hash": "427c4d717556a9288fd2decdacc7bdbe", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 68, "avg_line_length": 26.45562130177515, "alnum_prop": 0.5732498322522925, "repo_name": "kvngyr/kevin-dg", "id": "28cfc51c00bf1bce204a28d8c6f1add5852bb5fc", "size": "4471", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "www/lib/pouchdb/lib/constructor.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "513398" }, { "name": "HTML", "bytes": "105456" }, { "name": "JavaScript", "bytes": "4822058" }, { "name": "Ruby", "bytes": "317" }, { "name": "Shell", "bytes": "10474" } ], "symlink_target": "" }
package de.yadrone.apps.controlcenter; import java.util.Date; public class DroneDataSample { private int batteryPercentage; private int altitude; private float pitch; private float roll; private Date timestamp; public DroneDataSample() { timestamp = new Date(); } public int getBatteryPercentage() { return batteryPercentage; } public void setBatteryPercentage(int batteryPercentage) { this.batteryPercentage = batteryPercentage; } public int getAltitude() { return altitude; } public void setAltitude(int altitude) { this.altitude = altitude; } public float getPitch() { return pitch; } public void setPitch(float pitch) { this.pitch = pitch; } public float getRoll() { return roll; } public void setRoll(float roll) { this.roll = roll; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } }
{ "content_hash": "640d82adf1ce01f936410c0274e14359", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 58, "avg_line_length": 16.571428571428573, "alnum_prop": 0.7219827586206896, "repo_name": "villeingman/yadrone-vaadindrone", "id": "6ccec13a6b00ea8cd23b358cb638f2269e9d85f4", "size": "928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/yadrone/apps/controlcenter/DroneDataSample.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "420300" } ], "symlink_target": "" }
===================== Cygnite Framework it's just a small footprint to give you the creative experience of developing a web application. Cygnite Framework is under active development, also we are continuously upgrading the core features to make your job simple and better. You will find several eye catching features into Cygnite Framework. ###Core features - ================= 1. Cygnite Framework redesigned and powered by Composer. 2. Zero configuration. 3. Object oriented programming with MVC architecture. It's User friendly structures helps you painless development. 4. Cygnite Framework follows lazy loading concept which gives you expressive performance, it also provides inbuilt caching libraries. 5. Use plain php or elegant Twig template engine for your awesome application. 6. Cygnite Framework gives you flexibility for both beginners as well as advance PHP programmers to develop dynamic applications. 7. Cygnite has a great user guide which allows you to adapt as quick as possible. 8. Generating crud is much simple than you think, just single line of code will generate you basic crud operations, Cygnite Framework cli build on Symfony console component. 9. Form Builder has elegant syntax and also make your job easier. Use Cygnite CLI to build your form. 10. Use dynamic finders and model events. Inbuilt library allows you to write secure application. 11. REST-full router allow you to call controller directly. Which leads you to create powerful api. 12. Building database schema and Migration is very easy with Cygnite Cli. 13. Connect and use multiple Databases on the fly. Cygnite follows active record style resembles with Ruby on Rails Active Record. 14. Email library has expressive syntax which built on popular swiftmailer library. Authx, thumnbnail components make your job easy. 15. Cygnite powerful IoC container and StaticResolver allow you write amusing application, and there are more. Feel free to open an issue if you require anything. ###Contributing To Cygnite Framework ================================= Contribute on the development or its documentation, learn, get help and help others, find, report bugs, send us your feedback, send your wishlist for new features, write and send us patches for Cygnite Framework. You can contribute into cygnite development different ways. Read more in official website- http://www.cygniteframework.com/
{ "content_hash": "af9178773c1fb3b4f0453c561f9c277b", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 212, "avg_line_length": 66.44444444444444, "alnum_prop": 0.7876254180602007, "repo_name": "sanjoydesk/wallscript", "id": "7213a4558d3626370fcfca414a964e7d47888e86", "size": "2416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/cygnite/framework/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6896" }, { "name": "JavaScript", "bytes": "15966" }, { "name": "PHP", "bytes": "81775" } ], "symlink_target": "" }
import uuid from architect.commands import partition from django.db import migrations, models def add_partitions(apps, schema_editor): partition.run({'module': 'casexml.apps.phone.models'}) class Migration(migrations.Migration): dependencies = [ ('phone', '0001_initial'), ] operations = [ migrations.CreateModel( name='SyncLogSQL', fields=[ ('synclog_id', models.UUIDField(unique=True, primary_key=True, default=uuid.uuid1().hex)), ('domain', models.CharField(db_index=True, null=True, blank=True, default=None, max_length=255)), ('user_id', models.CharField(db_index=True, default=None, max_length=255)), ('date', models.DateTimeField(db_index=True, null=True, blank=True)), ('previous_synclog_id', models.UUIDField(blank=True, default=None, max_length=255, null=True)), ('doc', models.JSONField()), ('log_format', models.CharField( choices=[('legacy', 'legacy'), ('simplified', 'simplified'), ('livequery', 'livequery')], default='legacy', max_length=10)), ('build_id', models.CharField(max_length=255, null=True, blank=True)), ('duration', models.PositiveIntegerField(null=True, blank=True)), ('last_submitted', models.DateTimeField(db_index=True, null=True, blank=True)), ('had_state_error', models.BooleanField(default=False)), ('error_date', models.DateTimeField(db_index=True, null=True, blank=True)), ('error_hash', models.CharField(max_length=255, null=True, blank=True)), ], ), migrations.RunPython(add_partitions), ]
{ "content_hash": "e239634b8b3e89b75d02cb679e3924ba", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 113, "avg_line_length": 45.43589743589744, "alnum_prop": 0.59255079006772, "repo_name": "dimagi/commcare-hq", "id": "5d20b11f8a96abbfb702f3d6cf2714870f856915", "size": "1822", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corehq/ex-submodules/casexml/apps/phone/migrations/0002_synclogsql.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "82928" }, { "name": "Dockerfile", "bytes": "2341" }, { "name": "HTML", "bytes": "2589268" }, { "name": "JavaScript", "bytes": "5889543" }, { "name": "Jinja", "bytes": "3693" }, { "name": "Less", "bytes": "176180" }, { "name": "Makefile", "bytes": "1622" }, { "name": "PHP", "bytes": "2232" }, { "name": "PLpgSQL", "bytes": "66704" }, { "name": "Python", "bytes": "21779773" }, { "name": "Roff", "bytes": "150" }, { "name": "Shell", "bytes": "67473" } ], "symlink_target": "" }
using System.Linq; using Harvester.Core.Filters; using Xunit; namespace Harvester.Core.Tests.Filters.UsingCompositeFilter { public class WhenOrElseFilter { [Fact] public void AlwaysCompositeExpression() { var filter = new OrElseFilter(new FakeExtendedProperties(), Enumerable.Empty<ICreateFilterExpressions>()); Assert.True(filter.CompositeExpression); } [Fact] public void ReturnTrueIfNoChildFilters() { var e = new SystemEvent(); var extendedProperties = new FakeExtendedProperties { { "property", "Level" }, { "value", "Warning" } }; var filter = new OrElseFilter(extendedProperties, Enumerable.Empty<ICreateFilterExpressions>()); Assert.True(Filter.Compile(filter).Invoke(e)); } [Fact] public void ReturnTrueIfSingleChildFilterTrue() { var e = new SystemEvent { Level = SystemEventLevel.Warning }; var extendedProperties = new FakeExtendedProperties { { "property", "Level" }, { "value", "Warning" } }; var filter = new OrElseFilter(new FakeExtendedProperties(), new[] { new EqualFilter(extendedProperties, Enumerable.Empty<ICreateFilterExpressions>()) }); Assert.True(Filter.Compile(filter).Invoke(e)); } [Fact] public void ReturnFalseIfSingleChildFilterFalse() { var e = new SystemEvent { Level = SystemEventLevel.Error }; var extendedProperties = new FakeExtendedProperties { { "property", "Level" }, { "value", "Warning" } }; var filter = new OrElseFilter(new FakeExtendedProperties(), new[] { new EqualFilter(extendedProperties, Enumerable.Empty<ICreateFilterExpressions>()) }); Assert.False(Filter.Compile(filter).Invoke(e)); } [Fact] public void ReturnTrueIfAnyChildFilterTrue() { var e = new SystemEvent { Level = SystemEventLevel.Warning, ProcessId = 1234, Thread = "Main" }; var filter = new OrElseFilter( new FakeExtendedProperties(), new[] { new EqualFilter(new FakeExtendedProperties { { "property", "ProcessId" }, { "value", "1234" } }, Enumerable.Empty<ICreateFilterExpressions>()), new EqualFilter(new FakeExtendedProperties { { "property", "Thread" }, { "value", "Unknown" } }, Enumerable.Empty<ICreateFilterExpressions>()), new EqualFilter(new FakeExtendedProperties { { "property", "Level" }, { "value", "Error" } }, Enumerable.Empty<ICreateFilterExpressions>()) }); Assert.True(Filter.Compile(filter).Invoke(e)); } [Fact] public void ReturnFalseIfAllChildFiltersFalse() { var e = new SystemEvent { Level = SystemEventLevel.Error, ProcessId = 123, Thread = "Unknown" }; var filter = new OrElseFilter( new FakeExtendedProperties(), new[] { new EqualFilter(new FakeExtendedProperties { { "property", "ProcessId" }, { "value", "1234" } }, Enumerable.Empty<ICreateFilterExpressions>()), new EqualFilter(new FakeExtendedProperties { { "property", "Thread" }, { "value", "Main" } }, Enumerable.Empty<ICreateFilterExpressions>()), new EqualFilter(new FakeExtendedProperties { { "property", "Level" }, { "value", "Warning" } }, Enumerable.Empty<ICreateFilterExpressions>()) }); Assert.False(Filter.Compile(filter).Invoke(e)); } } }
{ "content_hash": "633a0f4fe95b4ac45eb09318503c6691", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 180, "avg_line_length": 47.851851851851855, "alnum_prop": 0.5699174406604747, "repo_name": "cbaxter/Harvester", "id": "a7966bbc389b1767519e75ee8aefc9890564403c", "size": "4979", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/Core.Tests/Filters/UsingCompositeFilter/WhenOrElseFilter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1002" }, { "name": "C#", "bytes": "538927" } ], "symlink_target": "" }
package com.dieselpoint.flood; import java.util.List; public class NodeState { String nodeId; long timestamp; // state as of this timestamp long highestCommittedSeqNum; // includes all pending, plus one or more committed List<LogEntry> entries; }
{ "content_hash": "1b77e185dd67c63abe2fa00646c11154", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 52, "avg_line_length": 21.5, "alnum_prop": 0.7596899224806202, "repo_name": "dieselpoint/diesel.cluster", "id": "2191eede6a7187778049bb3fb8bb79476a4b71e0", "size": "258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "diesel.cluster.flood/src/main/java/com/dieselpoint/flood/NodeState.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "182364" } ], "symlink_target": "" }
/*global $ */ $(document).ready(function () { "use strict"; $(".post-video").fitVids(); });
{ "content_hash": "18fa03a82d42664e8e5564d888397666", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 31, "avg_line_length": 19.8, "alnum_prop": 0.5252525252525253, "repo_name": "project-store/theme", "id": "5b8ae908776de89ba7930bab2bfcffca993a58d8", "size": "99", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "backend/Curo/assets/js/profile-demo.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "27940912" }, { "name": "CoffeeScript", "bytes": "16726" }, { "name": "HTML", "bytes": "231766282" }, { "name": "JavaScript", "bytes": "81504306" }, { "name": "PHP", "bytes": "417111" }, { "name": "Ruby", "bytes": "902" }, { "name": "Shell", "bytes": "616" } ], "symlink_target": "" }
using System.Diagnostics.CodeAnalysis; using System.Linq; using NUnit.Framework; using VkNet.Categories; using VkNet.Enums.SafetyEnums; using VkNet.Model.RequestParams; namespace VkNet.Tests.Categories { [TestFixture] [SuppressMessage(category: "ReSharper", checkId: "PublicMembersMustHaveComments")] public class LikesCategoryTest : BaseTest { private LikesCategory GetMockedLikesCategory(string url, string json) { Json = json; Url = url; return new LikesCategory(vk: Api); } [Test] public void Add_NormalCase() { const string url = "https://api.vk.com/method/likes.add"; const string json = @"{ response: { likes: 5 } }"; var likesCategory = GetMockedLikesCategory(url: url, json: json); var like = likesCategory.Add(@params: new LikesAddParams { Type = LikeObjectType.Post , ItemId = 701 }); Assert.That(actual: like, expression: Is.EqualTo(expected: 5)); } [Test] public void Delete_NormalCase() { const string url = "https://api.vk.com/method/likes.delete"; const string json = @"{ response: { likes: 4 } }"; var likesCategory = GetMockedLikesCategory(url: url, json: json); var like = likesCategory.Delete(type: LikeObjectType.Post, itemId: 701); Assert.That(actual: like, expression: Is.EqualTo(expected: 4)); } [Test] public void GetList_NormalCase() { const string url = "https://api.vk.com/method/likes.getList"; const string json = @"{ response: { count: 5, items: [32190123, 221634238, 229027572, 210894192, 201173701] } }"; var likesCategory = GetMockedLikesCategory(url: url, json: json); var like = likesCategory.GetList(@params: new LikesGetListParams { ItemId = 701 }); Assert.That(actual: like.Count, expression: Is.EqualTo(expected: 5)); } [Test] public void GetListEx_NormalCase() { const string url = "https://api.vk.com/method/likes.getList"; const string json = @"{ response: { count: 5, items: [{ type: 'profile', id: 32190123, first_name: 'Максим', last_name: 'Инютин' }, { type: 'profile', id: 221634238, first_name: 'Александр', last_name: 'Инютин' }, { type: 'profile', id: 229027572, first_name: 'Настя', last_name: 'Зубова' }, { type: 'profile', id: 210894192, first_name: 'Елизавета', last_name: 'Емельянова' }, { type: 'profile', id: 201173701, first_name: 'Даниил', last_name: 'Богданов' }] } }"; var likesCategory = GetMockedLikesCategory(url: url, json: json); var like = likesCategory.GetListEx(@params: new LikesGetListParams { ItemId = 701 }); Assert.That(actual: like.Users.Count, expression: Is.EqualTo(expected: 5)); Assert.That(actual: like.Users.First().Id, expression: Is.EqualTo(expected: 32190123)); Assert.That(actual: like.Users.First().FirstName, expression: Is.EqualTo(expected: "Максим")); Assert.That(actual: like.Users.First().LastName, expression: Is.EqualTo(expected: "Инютин")); Assert.That(actual: like.Groups.Count, expression: Is.EqualTo(expected: 0)); } [Test] public void IsLiked_NormalCase() { const string url = "https://api.vk.com/method/likes.isLiked"; const string json = @"{ response: { liked: 1, copied: 0 } }"; var likesCategory = GetMockedLikesCategory(url: url, json: json); bool copied; var like = likesCategory.IsLiked(copied: out copied, type: LikeObjectType.Post, itemId: 701); Assert.That(actual: like, expression: Is.EqualTo(expected: true)); Assert.That(actual: copied, expression: Is.EqualTo(expected: false)); } } }
{ "content_hash": "6132b6ce0795d5a2942c2b9302edeaac", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 97, "avg_line_length": 24.50955414012739, "alnum_prop": 0.6281185031185031, "repo_name": "Soniclev/vk", "id": "c9f23d6f73a4fa1723958f931a7a87a238c318f4", "size": "3933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VkNet.Tests/Categories/LikesCategoryTest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4244252" } ], "symlink_target": "" }
package com.me.diankun.firstcode; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.me.diankun.firstcode.service.LongTimeService; /** * Created by diankun on 2016/3/1. */ public class LongTimeActivity extends AppCompatActivity implements View.OnClickListener { private Button btn_start_longtime, btn_stop_longtime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_long_time); initView(); } private void initView() { btn_start_longtime = (Button) findViewById(R.id.btn_start_longtime); btn_stop_longtime = (Button) findViewById(R.id.btn_stop_longtime); btn_start_longtime.setOnClickListener(this); btn_stop_longtime.setOnClickListener(this); } @Override public void onClick(View view) { Intent i = new Intent(LongTimeActivity.this, LongTimeService.class); switch (view.getId()) { case R.id.btn_start_longtime: startService(i); break; case R.id.btn_stop_longtime: stopService(i); break; } } }
{ "content_hash": "5df7652cc698720b01713b2bd7b6feac", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 89, "avg_line_length": 29.52173913043478, "alnum_prop": 0.6413843888070693, "repo_name": "qdiankun/firstcode", "id": "121eab54fd4e82aa6108c2119eda0a106cd8a9ba", "size": "1358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "firstcode/chapter9_service/src/main/java/com/me/diankun/firstcode/LongTimeActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "218718" } ], "symlink_target": "" }
<!-- Credits to: Thiago Bordini thiago (at) bordini (dot) net --> <!doctype html> <html lang=''> <head> <meta charset='utf-8'> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="assets/stylesheets/styles.css"> <!--<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>--> <!--<script src="script.js"></script>--> <title>Evilwatcher</title> <style type="text/css"> body { background-color: #000; } </style> </head> <body> <div id='cssmenu'> <ul> <li class='active'><a href='dash.php' target='dash'><span>Home</span></a></li> <li><a href='hosts.php' target='dash'><span>Manage Hosts</span></a></li> <li><a href='view_paused_hosts.php' target='dash'><span>Manage Hosts Paused</span></a></li> <li><a href='view_paused_checks.php' target='dash'><span>Manage Checks Paused</span></a></li> <li><a href='dash_expired.php' target='dash'><span>Manage Hosts Expired</span></a></li> <li><a href='ports.php' target='dash'><span>Manage Ports</span></a></li> <li><a href='global_stats.php' target='dash'><span>Global Stats</span></a></li> <li class='last'><a href='about.php' target='dash'><span>About</span></a></li> </ul> </div> </body> </html>
{ "content_hash": "194ed090d2b5c83b28214c4dc1cc4d3a", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 101, "avg_line_length": 41.38235294117647, "alnum_prop": 0.5991471215351812, "repo_name": "tbordini/evilwatcher", "id": "a9c5f1a4b7fda3652189c136800bec10d13d9aef", "size": "1407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "up.php", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "31264" }, { "name": "CSS", "bytes": "5838" }, { "name": "PHP", "bytes": "168045" } ], "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_151) on Wed Jan 16 10:54:24 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface org.wildfly.swarm.config.ResourceAdaptersSupplier (BOM: * : All 2.3.0.Final-SNAPSHOT API)</title> <meta name="date" content="2019-01-16"> <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 Interface org.wildfly.swarm.config.ResourceAdaptersSupplier (BOM: * : All 2.3.0.Final-SNAPSHOT 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="../../../../../org/wildfly/swarm/config/ResourceAdaptersSupplier.html" title="interface in org.wildfly.swarm.config">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-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 class="aboutLanguage">Thorntail API, 2.3.0.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/ResourceAdaptersSupplier.html" target="_top">Frames</a></li> <li><a href="ResourceAdaptersSupplier.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 Interface org.wildfly.swarm.config.ResourceAdaptersSupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.ResourceAdaptersSupplier</h2> </div> <div class="classUseContainer">No usage of org.wildfly.swarm.config.ResourceAdaptersSupplier</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/wildfly/swarm/config/ResourceAdaptersSupplier.html" title="interface in org.wildfly.swarm.config">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-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 class="aboutLanguage">Thorntail API, 2.3.0.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/ResourceAdaptersSupplier.html" target="_top">Frames</a></li> <li><a href="ResourceAdaptersSupplier.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; 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "c5756b637611f9675bf9d2df69a29548", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 169, "avg_line_length": 38.859375, "alnum_prop": 0.6270607157217531, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "11a8e327c5ad8fae9a9c4c6fe4a656832cdbc7c6", "size": "4974", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2.3.0.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/class-use/ResourceAdaptersSupplier.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.framgia.android.emulator"> <application android:allowBackup="true" android:label="@string/app_name" android:supportsRtl="true"> </application> </manifest>
{ "content_hash": "af9bcd9ca5d15e8b24bdf1cde5d21380", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 76, "avg_line_length": 28.88888888888889, "alnum_prop": 0.7115384615384616, "repo_name": "KaKaVip/android-emulator-detector", "id": "10ff27bc8e4981203bbb874512572bc9c77438a4", "size": "260", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "library/src/main/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "16241" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- Copyright 2010-2012 The myBatis Team 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. --> <!-- version: $Id$ --> <configuration> <settings> <!-- changes from the defaults for testing --> <setting name="cacheEnabled" value="false" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <mappers> <mapper resource="org/mybatis/spring/TestMapper.xml" /> </mappers> </configuration>
{ "content_hash": "93b5e544d1085cf3e7f70301ddda27eb", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 76, "avg_line_length": 32.108108108108105, "alnum_prop": 0.6759259259259259, "repo_name": "gdarmont/mybatis-spring", "id": "ccff2de46f6dacc8daa400011d9f8bbd91ae6e57", "size": "1188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/mybatis/spring/mybatis-config.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "243575" } ], "symlink_target": "" }
package com.example.android.popularmovies.sync; import android.app.Service; import android.content.Intent; import android.os.IBinder; /** * Created by Elorri on 04/11/2015. */ public class MoviesAuthenticatorService extends Service { // Instance field that stores the authenticator object private MoviesAuthenticator mAuthenticator; @Override public void onCreate() { // Create a new authenticator object mAuthenticator = new MoviesAuthenticator(this); } /* * When the system binds to this Service to make the RPC call * return the authenticator's IBinder. */ @Override public IBinder onBind(Intent intent) { return mAuthenticator.getIBinder(); } }
{ "content_hash": "9483c86019aac4ba00091c56ddfab564", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 65, "avg_line_length": 26.071428571428573, "alnum_prop": 0.7041095890410959, "repo_name": "Elorri/PopularMovies", "id": "b36b72c41217d8d1de90b6c376f811bef1d49939", "size": "730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/example/android/popularmovies/sync/MoviesAuthenticatorService.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "168439" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_view_friend_requests" 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="com.example.moodmobile.ViewFriendRequests"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/SendRequest" android:layout_centerHorizontal="true" android:layout_marginTop="42dp" android:id="@+id/RequestsList" /> <TextView android:text="You have 0 pending follow requests" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/FollowRequestsCount" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> </RelativeLayout>
{ "content_hash": "e0de069300d4512d8fb8b978578e735c", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 74, "avg_line_length": 42.892857142857146, "alnum_prop": 0.7052456286427977, "repo_name": "CMPUT301W17T05/MoodMobile", "id": "ea7c4aa65900dca54a96198f27b62dffdf0c02d7", "size": "1201", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/res/layout-land/activity_view_friend_requests.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12842" }, { "name": "HTML", "bytes": "908876" }, { "name": "Java", "bytes": "152348" }, { "name": "JavaScript", "bytes": "827" } ], "symlink_target": "" }
package org.cyclops.integrateddynamics.core.evaluate.variable; import net.minecraft.nbt.LongArrayTag; import net.minecraft.nbt.Tag; import net.minecraft.resources.ResourceLocation; import org.cyclops.integrateddynamics.Reference; import java.util.Optional; /** * An NBT int array wrapper */ public class ValueTypeListProxyNbtValueListLong extends ValueTypeListProxyNbtValueListGeneric<LongArrayTag, ValueTypeLong, ValueTypeLong.ValueLong> { public ValueTypeListProxyNbtValueListLong(String key, Optional<Tag> tag) { super(ValueTypeListProxyFactories.NBT_VALUE_LIST_LONG.getName(), ValueTypes.LONG, key, tag); } @Override protected int getLength(LongArrayTag tag) { return tag.getAsLongArray().length; } @Override protected ValueTypeLong.ValueLong get(LongArrayTag tag, int index) { return ValueTypeLong.ValueLong.of(tag.getAsLongArray()[index]); } public static class Factory extends ValueTypeListProxyNbtValueListGeneric.Factory<ValueTypeListProxyNbtValueListLong, LongArrayTag, ValueTypeLong, ValueTypeLong.ValueLong> { @Override public ResourceLocation getName() { return new ResourceLocation(Reference.MOD_ID, "nbt.list_value_long"); } @Override protected ValueTypeListProxyNbtValueListLong create(String key, Optional<Tag> tag) { return new ValueTypeListProxyNbtValueListLong(key, tag); } } }
{ "content_hash": "4406931d721ce54ed2fce6d8d145c106", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 177, "avg_line_length": 35.24390243902439, "alnum_prop": 0.7480968858131488, "repo_name": "CyclopsMC/IntegratedDynamics", "id": "4b2a87f1d35914ec141ae805c68bb5d6854de62b", "size": "1445", "binary": false, "copies": "1", "ref": "refs/heads/master-1.19", "path": "src/main/java/org/cyclops/integrateddynamics/core/evaluate/variable/ValueTypeListProxyNbtValueListLong.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "3437058" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>pi-agm: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.2 / pi-agm - 1.1.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> pi-agm <small> 1.1.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-17 22:59:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-17 22:59:49 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-pi-agm&quot; version: &quot;1.1.0&quot; maintainer: &quot;yves.bertot@inria.fr&quot; homepage: &quot;http://www-sop.inria.fr/members/Yves.Bertot/&quot; bug-reports: &quot;yves.bertot@inria.fr&quot; license: &quot;CeCILL-B&quot; build: [[&quot;coq_makefile&quot; &quot;-f&quot; &quot;_CoqProject&quot; &quot;-o&quot; &quot;Makefile&quot; ] [ make &quot;-j&quot; &quot;%{jobs}%&quot; ]] install: [ make &quot;install&quot; &quot;DEST=&#39;%{lib}%/coq/user-contrib/pi_agm&#39;&quot; ] remove: [ &quot;sh&quot; &quot;-c&quot; &quot;rm -rf &#39;%{lib}%/coq/user-contrib/pi_agm&#39;&quot; ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.7~&quot;} &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.6.0&quot; &amp; &lt;= &quot;1.6.1&quot;} &quot;coq-coquelicot&quot; {&gt; &quot;2.1.1&quot; &amp; &lt;= &quot;2.1.2&quot;} &quot;coq-interval&quot; {= &quot;3.1.1&quot;} ] tags: [ &quot;keyword:real analysis&quot; &quot;keyword:pi&quot; &quot;category:Mathematics/Real Calculus and Topology&quot; ] authors: [ &quot;Yves Bertot &lt;yves.bertot@inria.fr&gt;&quot; ] synopsis: &quot;Computing thousands or millions of digits of PI with arithmetic-geometric means&quot; description: &quot;&quot;&quot; This is a proof of correctness for two algorithms to compute PI to high precision using arithmetic-geometric means. A first file contains the calculus-based proofs for an abstract view of the algorithm, where all numbers are real numbers. A second file describes how to approximate all computations using large integers. Other files describe the second algorithm which is close to the one used in mpfr, for instance. The whole development can be used to produce mathematically proved and formally verified approximations of PI.&quot;&quot;&quot; url { src: &quot;https://github.com/ybertot/pi-agm/archive/submitted-article-version-8-6.zip&quot; checksum: &quot;md5=4004421ecb7c185e3d269fb7ef944bdd&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-pi-agm.1.1.0 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-pi-agm -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-pi-agm.1.1.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "8ed79efd1c05a0dae502e10fd0c88069", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 159, "avg_line_length": 43.50282485875706, "alnum_prop": 0.5577922077922078, "repo_name": "coq-bench/coq-bench.github.io", "id": "cf56aed0fd28202e72730486a41644869786509f", "size": "7725", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.11.2/pi-agm/1.1.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.jboss.modules; import static org.jboss.modules.Utils.MODULES_DIR; import static org.jboss.modules.Utils.MODULE_FILE; import java.io.IOException; import java.io.InputStream; import org.jboss.modules.xml.ModuleXmlParser; /** * A module loader which loads modules which are stored inside the {@code modules} directory of a single JAR or JAR-like * root. */ public final class ResourceLoaderModuleFinder implements ModuleFinder { private final ResourceLoader resourceLoader; private final String modulesDirectory; private final NestedResourceRootFactory factory; /** * Construct a new instance. The given resource loader should support the nested {@link ResourceLoader#createSubloader(String, String)} * operation if {@code &lt;resource-root&gt;} elements are to be supported in {@code module.xml} files found within * the loader. * * @param resourceLoader the base resource loader to use (must not be {@code null}) * @param modulesDirectory the modules directory to use (must not be {@code null}) */ public ResourceLoaderModuleFinder(final ResourceLoader resourceLoader, final String modulesDirectory) { factory = new NestedResourceRootFactory(resourceLoader); this.resourceLoader = resourceLoader; this.modulesDirectory = modulesDirectory; } /** * Construct a new instance. The given resource loader should support the nested {@link ResourceLoader#createSubloader(String, String)} * operation if {@code &lt;resource-root&gt;} elements are to be supported in {@code module.xml} files found within * the loader. * * @param resourceLoader the base resource loader to use (must not be {@code null}) */ public ResourceLoaderModuleFinder(final ResourceLoader resourceLoader) { this(resourceLoader, MODULES_DIR); } public ModuleSpec findModule(final String name, final ModuleLoader delegateLoader) throws ModuleLoadException { final ResourceLoader resourceLoader = this.resourceLoader; final String path = PathUtils.basicModuleNameToPath(name); if (path == null) { return null; // not valid, so not found } String basePath = modulesDirectory + "/" + path; Resource moduleXmlResource = resourceLoader.getResource(basePath + "/" + MODULE_FILE); if (moduleXmlResource == null) { return null; } ModuleSpec moduleSpec; try { try (final InputStream inputStream = moduleXmlResource.openStream()) { moduleSpec = ModuleXmlParser.parseModuleXml(factory, basePath, inputStream, moduleXmlResource.getName(), delegateLoader, name); } } catch (IOException e) { throw new ModuleLoadException("Failed to read " + MODULE_FILE + " file", e); } return moduleSpec; } static class NestedResourceRootFactory implements ModuleXmlParser.ResourceRootFactory { private final ResourceLoader resourceLoader; NestedResourceRootFactory(final ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public ResourceLoader createResourceLoader(final String rootPath, final String loaderPath, final String loaderName) throws IOException { final ResourceLoader subloader = resourceLoader.createSubloader(rootPath + "/" + loaderPath, loaderName); if (subloader == null) { throw new IllegalArgumentException("Nested resource loaders not supported by " + resourceLoader); } return subloader; } } }
{ "content_hash": "9b48a5e545b0b9b952eeb97e8d84eb81", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 144, "avg_line_length": 43.357142857142854, "alnum_prop": 0.6965952773201538, "repo_name": "jboss-modules/jboss-modules", "id": "612ef92a3b17fc5c347f5ea77167156fedec95a4", "size": "4348", "binary": false, "copies": "1", "ref": "refs/heads/2.x", "path": "src/main/java/org/jboss/modules/ResourceLoaderModuleFinder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1310089" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <elements> <element name="$UI/system/components/bootstrap/navs/navs(bootstrap)" tag-type="rich" tag-name="ul" icon="navs.png" text="导航条" binding-component="$UI/system/components/bootstrap/navs/navs" display-property="xid" validator="ViewValidator" design-view="web-designer" > <properties> <property name="xid" text="编号" required="false" editor-discriptor-ref=""/> <property name="class" text="class" editor-ref="classSelector"> <editor-parameter><![CDATA[ { "0base": { label: "基础样式", value: "nav" }, "2type": { label: "样式", value: "nav-tabs|nav-pills", }, "3other": { label: "可选", value: "nav-stacked,nav-justified", require: false } } ]]></editor-parameter> </property> <property name="style" text="样式" editor-ref="styleDialog" /> <include path="$UI/system/components/designerCommon/commonConfig.xml#//common-properties/group[@name='bind']"/> </properties> <events> <event name="onClick" type="event" text="click" parameters="event" is-script="true"/> <include path="$UI/system/components/designerCommon/commonConfig.xml#//html-evens/*"/> </events> <toolbar> <item text="添加tab" method="addTab"/> </toolbar> <templates> <template name="default"><![CDATA[ <ul component="$UI/system/components/bootstrap/navs/navs" class="nav nav-tabs"> <li role="presentation" class="active"><a >Item</a></li> </ul> ]]></template> </templates> </element> <!-- <element name="$UI/system/components/bootstrap/navs/item" tag-type="rich" tag-name="li" icon="navs.png" text="导航项" discriminate-condition="executeXpath(parent::node()/@component='$UI/system/components/bootstrap/navs/navs')" display-property="xid" validator="ViewValidator" design-view="web-designer"> <properties> <property name="xid" text="编号" required="false" editor-discriptor-ref=""/> <property name="label" text="标签"/> <property name="class" text="class" editor-ref="classSelector"> <editor-parameter><![CDATA[ { "0base": { label: "基础样式", value: "x-navs-item" } } ]]></editor-parameter> </property> <property name="style" text="样式" editor-ref="styleDialog" /> <include path="$UI/system/components/designerCommon/commonConfig.xml#//common-properties/group[@name='bind']"/> </properties> <events> <include path="$UI/system/components/designerCommon/commonConfig.xml#//html-evens/*"/> </events> <templates> <template name="default"><![CDATA[ <li><a >Item</a></li> ]]></template> </templates> </element> --> </elements>
{ "content_hash": "0f781bc7cc1742a16453f0f98b41bb79", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 128, "avg_line_length": 35.90909090909091, "alnum_prop": 0.6162748643761302, "repo_name": "wengyulin/WeX5", "id": "a783ebba8899a9d1212f1417cf1b27de03f201b0", "size": "2827", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "UI2/system/components/bootstrap/navs/designer/navs.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AppleScript", "bytes": "1208" }, { "name": "Batchfile", "bytes": "11305" }, { "name": "C", "bytes": "2335555" }, { "name": "C#", "bytes": "418354" }, { "name": "C++", "bytes": "1075715" }, { "name": "CSS", "bytes": "3334480" }, { "name": "HTML", "bytes": "182541" }, { "name": "Java", "bytes": "4466548" }, { "name": "JavaScript", "bytes": "11023461" }, { "name": "Objective-C", "bytes": "1401370" }, { "name": "Objective-C++", "bytes": "36131" }, { "name": "QML", "bytes": "14604" }, { "name": "Shell", "bytes": "29370" } ], "symlink_target": "" }
class Tracker < ActiveRecord::Base def self.current Tracker.find(:first, :conditions => {:active => true, :environment => Rails.env}) end end
{ "content_hash": "9087aaaea39068a9d9a16286c4374978", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 85, "avg_line_length": 30, "alnum_prop": 0.6866666666666666, "repo_name": "rovetz/spree_theme_envirashop", "id": "536dc0f46cb6b709b6460d67f9997d8d63f9e1ab", "size": "150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/tracker.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "98401" }, { "name": "Ruby", "bytes": "3827" } ], "symlink_target": "" }
layout: post title: "Julep Free 8-pc Gift Set for New Subscribers ($150 Value)!" description: "" headline: "Julep Free 8-pc Gift Set for New Subscribers!" categories: - Coupons tags: [Julep, Coupons] comments: true mathjax: null published: true featured: false type: photo imagefeature: "Julep-Free-8-Piece-Gift-With-Subscription-August-2016.jpg" date: 2016-08-18 11:11:39 -08:00 --- <br> <center><a href="http://shareasale.com/r.cfm?b=898326&u=1115177&m=49325&urllink=&afftrack=" target="_blank"><img src="/images/Julep-Free-8-Piece-Gift-With-Subscription-August-2016-Coupon.png" border="0" style="border:none;max-width:100%;" /> </a></center> <p>Amazing Julep promo starting today!! Now when you <a href="http://shareasale.com/r.cfm?b=898326&u=1115177&m=49325&urllink=&afftrack=" target="_blank">sign up</a>, you get a FREE 8 piece Beauty Set filled with $150 worth of bestselling beauty and polish!</p> <p>To get this $150 beauty gift for FREE, <a href="http://shareasale.com/r.cfm?b=898326&u=1115177&m=49325&urllink=&afftrack=" target="_blank">join Julep Beauty Box</a> and add the FREE 8 piece Beauty Set to your cart and use code COLOR8 at checkout.</p> <br> <center><a href="http://shareasale.com/r.cfm?b=898326&u=1115177&m=49325&urllink=&afftrack=" target="_blank"><img src="/images/Julep-Free-8-Piece-Gift-With-Subscription-August-2016.jpg" border="0" style="border:none;max-width:100%;" /> </a></center> <p>After you <a href="http://shareasale.com/r.cfm?b=898326&u=1115177&m=49325&urllink=&afftrack=" target="_blank">join Julep</a>, you'll get a box of gorgeous and good-for-you beauty, nail, or skincare products delivered to your door every month. Julep offers the only full-size and fully-customizable beauty box out there, so you get what you want every month!</p> <br> <p>And don't forget to use <a href="http://www.ebates.com/rf.do?referrerid=nFbj2DqrCN%2BpB5AWKzmAFQ%3D%3D&eeid=30337" target="_blank">EBATES</a> to get 5% cashback on your purchases at Julep, I always use them and get money back!</p> <a href='https://www.ebates.com/r/LORETT1403?eeid=28585' target='_blank' rel='nofollow'><img src='https://www.ebates.com/referral/2012/global_files/images/ebates_logo.png' alt='Ebates Coupons and Cash Back' height='31' width='171' border='0'/></a> <br> <center><a href="http://refer.julep.com/v2/share/6232653664775881338" target="_blank"><img src="/images/JulepLogo.jpg" border="0" style="border:none;max-width:100%;" /> </a></center> # What's Julep? <p>For those of you who are not familiar with Julep, they're an innovative and health conscious makeup company that specializes in beauty products including cosmetics, nail color, and skincare. They also have a wildly popular Julep Maven subscription program, the first fully customizable monthly beauty box!</p> <p>If you haven't subscribed to <a href="http://refer.julep.com/v2/share/6232653664775881338" target="_blank">Julep Maven</a>, here's a little info of what it is:</p> <p><b>Subscription:</b> <a href="http://refer.julep.com/v2/share/6232653664775881338" target="_blank">Julep Maven</a></p> <p><b>Cost:</b> $24.99 / month plus Free Shipping</p> <p><b>What's in the box:</b> An assortment of nail polish and other beauty products such as mascara, lipstick or skincare by Julep. You can customize your monthly box during their Maven Reveal period (20th-24th of every month). You can also send it to a friend instead or skip the month all through your online account.</p> <p><b>Coupon:</b> <a href="http://shareasale.com/r.cfm?b=898326&u=1115177&m=49325&urllink=&afftrack=" target="_blank">Join Julep Maven through this link</a> and use Coupon Code <a href="http://shareasale.com/r.cfm?b=898326&u=1115177&m=49325&urllink=&afftrack=" target="_blank">COLOR8</a> to get a FREE 8 piece Beauty Set filled with $150 worth of bestselling beauty and polish!</p>
{ "content_hash": "c27d339172c9a71e1640c72e87858306", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 381, "avg_line_length": 70.0909090909091, "alnum_prop": 0.7356679636835279, "repo_name": "whatsupmailbox/whatsupmailbox.github.io", "id": "860f2924d6e795f162103ed31745b5b458c42e0f", "size": "3859", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-08-18-Julep-Free-8-Piece-Gift-Set-New-Subscribers-GWS-GWP.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "149392" }, { "name": "HTML", "bytes": "124514" }, { "name": "JavaScript", "bytes": "52954" } ], "symlink_target": "" }
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Parses CSS before it is cached. * * This function can make alterations and replace patterns within the CSS. * * @param string $css The CSS * @param theme_config $theme The theme config object. * @return string The parsed CSS The parsed CSS. */ function theme_clean_process_css($css, $theme) { // Set the background image for the logo. $logo = $theme->setting_file_url('logo', 'logo'); $css = theme_clean_set_logo($css, $logo); // Set custom CSS. if (!empty($theme->settings->customcss)) { $customcss = $theme->settings->customcss; } else { $customcss = null; } $css = theme_clean_set_customcss($css, $customcss); return $css; } /** * Adds the logo to CSS. * * @param string $css The CSS. * @param string $logo The URL of the logo. * @return string The parsed CSS */ function theme_clean_set_logo($css, $logo) { $tag = '[[setting:logo]]'; $replacement = $logo; if (is_null($replacement)) { $replacement = ''; } $css = str_replace($tag, $replacement, $css); return $css; } /** * Serves any files associated with the theme settings. * * @param stdClass $course * @param stdClass $cm * @param context $context * @param string $filearea * @param array $args * @param bool $forcedownload * @param array $options * @return bool */ function theme_clean_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) { if ($context->contextlevel == CONTEXT_SYSTEM and ($filearea === 'logo' || $filearea === 'smalllogo')) { $theme = theme_config::load('clean'); // By default, theme files must be cache-able by both browsers and proxies. if (!array_key_exists('cacheability', $options)) { $options['cacheability'] = 'public'; } return $theme->setting_file_serve($filearea, $args, $forcedownload, $options); } else { send_file_not_found(); } } /** * Adds any custom CSS to the CSS before it is cached. * * @param string $css The original CSS. * @param string $customcss The custom CSS to add. * @return string The CSS which now contains our custom CSS. */ function theme_clean_set_customcss($css, $customcss) { $tag = '[[setting:customcss]]'; $replacement = $customcss; if (is_null($replacement)) { $replacement = ''; } $css = str_replace($tag, $replacement, $css); return $css; } /** * Returns an object containing HTML for the areas affected by settings. * * Do not add Clean specific logic in here, child themes should be able to * rely on that function just by declaring settings with similar names. * * @param renderer_base $output Pass in $OUTPUT. * @param moodle_page $page Pass in $PAGE. * @return stdClass An object with the following properties: * - navbarclass A CSS class to use on the navbar. By default ''. * - heading HTML to use for the heading. A logo if one is selected or the default heading. * - footnote HTML to use as a footnote. By default ''. */ function theme_clean_get_html_for_settings(renderer_base $output, moodle_page $page) { global $CFG; $return = new stdClass; $return->navbarclass = ''; if (!empty($page->theme->settings->invert)) { $return->navbarclass .= ' navbar-inverse'; } // Only display the logo on the front page and login page, if one is defined. if (!empty($page->theme->settings->logo) && ($page->pagelayout == 'frontpage' || $page->pagelayout == 'login')) { $return->heading = html_writer::tag('div', '', array('class' => 'logo')); } else { $return->heading = $output->page_heading(); } $return->footnote = ''; if (!empty($page->theme->settings->footnote)) { $return->footnote = '<div class="footnote text-center">'.format_text($page->theme->settings->footnote).'</div>'; } return $return; } /** * All theme functions should start with theme_clean_ * @deprecated since 2.5.1 */ function clean_process_css() { throw new coding_exception('Please call theme_'.__FUNCTION__.' instead of '.__FUNCTION__); } /** * All theme functions should start with theme_clean_ * @deprecated since 2.5.1 */ function clean_set_logo() { throw new coding_exception('Please call theme_'.__FUNCTION__.' instead of '.__FUNCTION__); } /** * All theme functions should start with theme_clean_ * @deprecated since 2.5.1 */ function clean_set_customcss() { throw new coding_exception('Please call theme_'.__FUNCTION__.' instead of '.__FUNCTION__); }
{ "content_hash": "5358571ea4c698b2394d2086e1277544", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 120, "avg_line_length": 31.351190476190474, "alnum_prop": 0.6468577938105183, "repo_name": "tesler/cspt-moodle", "id": "889c9aea064a33ad5e296b29aadee897c6f84575", "size": "5678", "binary": false, "copies": "61", "ref": "refs/heads/master", "path": "moodle/theme/clean/lib.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1317422" }, { "name": "Cucumber", "bytes": "2339764" }, { "name": "HTML", "bytes": "667655" }, { "name": "Java", "bytes": "14870" }, { "name": "JavaScript", "bytes": "12844512" }, { "name": "PHP", "bytes": "76536211" }, { "name": "PLSQL", "bytes": "4867" }, { "name": "Perl", "bytes": "20769" }, { "name": "Shell", "bytes": "6937" }, { "name": "XSLT", "bytes": "33489" } ], "symlink_target": "" }
<?php namespace ODataProducer\Writers\Metadata; use ODataProducer\Common\Messages; use ODataProducer\Common\InvalidOperationException; use ODataProducer\Providers\Metadata\ResourceTypeKind; use ODataProducer\Providers\Metadata\ResourceAssociationTypeEnd; use ODataProducer\Providers\MetadataQueryProviderWrapper; use ODataProducer\Providers\Metadata\ResourceAssociationType; use ODataProducer\Providers\Metadata\ResourceAssociationSet; use ODataProducer\Providers\Metadata\ResourceAssociationSetEnd; use ODataProducer\Providers\Metadata\ResourceType; use ODataProducer\Providers\Metadata\ResourceProperty; use ODataProducer\Providers\Metadata\ResourceSetWrapper; require_once 'ODataProducer/Writers/Metadata/MetadataBase.php'; /** * This class validates all AssociationSet defined for the service and creates * AssociationType for each AssociationSet from the given provider. * * Iterate over all resource (entity) types belongs to visible resource (entity) sets * for each entity type retrieve its derived and base resource types. For each * navigation property in these types (base types, type, derived types) cache the * association set and build and group 'ResourceAssociationType' instances based on * namespace. * (will use the namespace of the resource type in the assocation type instance) * * @category ODataPHPProd * @package ODataProducer_Writers_Metadata * @author Microsoft Open Technologies, Inc. <msopentech@microsoft.com> * @copyright Microsoft Open Technologies, Inc. * @license New BSD license, (http://www.opensource.org/licenses/bsd-license.php) * @version GIT: 1.2 * @link https://github.com/MSOpenTech/odataphpprod */ class MetadataAssociationTypeSet extends MetadataBase { /** * Array of namespace along with the resource association types in that namespace * Namespace will be the key and value will be array of * 'ResourceAssociationType' in that namespace * (as key: association_type_lookup_key, value:ResourceAssociationType)) * array(namespace_name, * array(association_type_lookup_key, ResourceAssociationType) * ) * Note1: This array will holds one entry per direction, * so for a bidirectional relationship * same AssociationType will appear twice * * @var array(string, array(string, ResourceAssociationType)) */ private $_resourceAssociationTypes = array(); /** * Array of unique 'ResourceAssociationType' * array(namespace_name, array(association_type_name, ResourceAssociationType)) * * @var array(string, array(string, ResourceAssociationType)) */ private $_uniqueResourceAssociationTypes = null; /** * Array of 'ResourceAssociationSet' * Note1: All resource sets belongs to the container namespace * Note2: This array will holds one entry per direction, * so for a bidirectional relationship same AssociationSet will appear twice, * so use the function 'getAssociationSets' to get the unique instance from * this array. * * @var array(string, ResourceAssociationSet) */ private $_resourceAssociationSets = array(); /** * Array of unique 'ResourceAssociationSet' * array(association_set_name, ResourceAssociationType) * * @var array(string, ResourceAssociationSet) */ private $_uniqueResourceAssociationSets = null; /** * Construct new instance of MetadataAssociationTypeSet, this constructor * creates and caches resource association set and association type for * all resource (entity) sets. * * @param MetadataQueryProviderWrapper $provider Reference to the * service metadata and query provider wrapper */ public function __construct(MetadataQueryProviderWrapper $provider) { parent::__construct($provider); foreach ($this->metadataQueryproviderWrapper->getResourceSets() as $resourceSetWrapper) { $this->_populateAssociationForSet($resourceSetWrapper); } } /** * Gets collection of association set * * @return array(string, ResourceAssociationSet) */ public function getAssociationSets() { if (is_null($this->_uniqueResourceAssociationSets)) { $this->_uniqueResourceAssociationSets = array(); foreach ($this->_resourceAssociationSets as $lookupName => $resourceAssociationSet) { $resourceAssociationSetName = $resourceAssociationSet->getName(); if (!array_key_exists($resourceAssociationSetName, $this->_uniqueResourceAssociationSets)) { $this->_uniqueResourceAssociationSets[$resourceAssociationSetName] = $resourceAssociationSet; } } } return $this->_uniqueResourceAssociationSets; } /** * Gets collection of association types belongs to the given namespace, * creates a collection for the namespace if its not already there, * This array of association types in a namespace will contains * one entry per direction, so for a bidirectional relationship * same AssociationType (having same association type name) * will appear twice with different cache (lookup) key. * * @param string $namespace The namespace name to get * the association types belongs to * * @return array(string, ResourceAssociationType) */ public function &getResourceAssociationTypesForNamespace($namespace) { if (!array_key_exists($namespace, $this->_resourceAssociationTypes)) { $this->_resourceAssociationTypes[$namespace] = array(); } return $this->_resourceAssociationTypes[$namespace]; } /** * Gets unique collection of association type for the given namespace, the * 'getResourceAssociationTypesForNamespace' will also returns * collection of association type for a given namespace but will contain * duplicate association type in case of bi-directional relationship. * * @param string $namespace Namespace name to get * the association type belongs to * * @return array(ResourceAssociationType) */ public function getUniqueResourceAssociationTypesForNamespace($namespace) { if (is_null($this->_uniqueResourceAssociationTypes)) { $this->_uniqueResourceAssociationTypes = array(); foreach ($this->_resourceAssociationTypes as $nameSpaceName => $resourceAssociationTypesWithLookupKey) { $this->_uniqueResourceAssociationTypes[$nameSpaceName] = array(); foreach ($resourceAssociationTypesWithLookupKey as $lookupKey => $resourceAssociationType) { $resourceAssociationTypeName = $resourceAssociationType->getName(); if (!array_key_exists($resourceAssociationTypeName, $this->_uniqueResourceAssociationTypes[$nameSpaceName])) { $this->_uniqueResourceAssociationTypes[$namespace][$resourceAssociationTypeName] = $resourceAssociationType; } } } } if (array_key_exists($namespace, $this->_uniqueResourceAssociationTypes)) { return array_values($this->_uniqueResourceAssociationTypes[$namespace]); } return array(); } /** * Populate association set and type for the given resource (entity) set * * @param ResourceSetWrapper $resourceSetWrapper The resource set to inspect * * @return void * * @throws InvalidOperationException If IDSMP::getDerivedTypes * returns invalid type */ private function _populateAssociationForSet(ResourceSetWrapper $resourceSetWrapper) { $derivedTypes = $this->metadataQueryproviderWrapper->getDerivedTypes($resourceSetWrapper->getResourceType()); if (!is_null($derivedTypes)) { if (!is_array($derivedTypes)) { throw new InvalidOperationException(Messages::metadataAssociationTypeSetInvalidGetDerivedTypesReturnType($resourceSetWrapper->getName())); } //Populate ResourceAssociationSet and ResourceAssociationType //for derived types foreach ($derivedTypes as $derivedType) { $this->_populateAssociationForSetAndType($resourceSetWrapper, $derivedType); } } //Populate ResourceAssociationSet and ResourceAssociationType //for this type and base types $resourceType = $resourceSetWrapper->getResourceType(); while ($resourceType != null) { $this->_populateAssociationForSetAndType($resourceSetWrapper, $resourceType); $resourceType = $resourceType->getBaseType(); } } /** * Populate association for the given resouce set and its resource type * (derived, base or own type) * * @param ResourceSetWrapper $resourceSetWrapper The resource set to inspect * @param ResourceType $resourceType The resource type to inspect * * @return void * * @throws InvalidOperationException If validation fails at * _getResourceAssociationSet * @throws ODataException If validation fails at * MetadataQueryProviderWrapper::getResourceAssociationSet */ private function _populateAssociationForSetAndType(ResourceSetWrapper $resourceSetWrapper, ResourceType $resourceType) { $properties = $resourceType->getPropertiesDeclaredOnThisType(); foreach ($properties as $property) { if ($property->getTypeKind() == ResourceTypeKind::ENTITY) { $resourceAssociationSet = $this->_getResourceAssociationSet($resourceSetWrapper, $resourceType, $property); if (!is_null($resourceAssociationSet)) { $resourceAssociationSet->resourceAssociationType = $this->_getResourceAssociationType($resourceAssociationSet, $resourceSetWrapper, $resourceType, $property); } } } } /** * Gets and validate the ResourceAssociationSet instance for the * given source resource association end * This function first searches the ResourceAssociationSet cache, * if found return it otherwise * get the association set from metadata wrapper, * validate, cache and return it. * * @param ResourceSetWrapper $resourceSet Resource set of the * source association end * @param ResourceType $resourceType Resource type of the * source association end * @param ResourceProperty $navigationProperty Resource property of the * source association end * * @return ResourceAssociationSet/NULL The association set instance for the * given association set end, * NULL if the metadata wrapper * returns NULL * (either IDSMP implementation * returns null or * target resource set is invisible) * * @throws InvalidOperationException If validation of AssociationSet fails * @throws ODataException If validation fails at * MetadataQueryProviderWrapper::getResourceAssociationSet */ private function _getResourceAssociationSet(ResourceSetWrapper $resourceSet, ResourceType $resourceType, ResourceProperty $navigationProperty) { $associationSetLookupKey = $resourceSet->getName() . '_' . $resourceType->getFullName() . '_' . $navigationProperty->getName(); if (array_key_exists($associationSetLookupKey, $this->_resourceAssociationSets)) { return $this->_resourceAssociationSets[$associationSetLookupKey]; } $resourceAssociationSet = $this->metadataQueryproviderWrapper->getResourceAssociationSet($resourceSet, $resourceType, $navigationProperty); if (is_null($resourceAssociationSet)) { //Either the related ResourceSet is invisible or IDSMP implementation returns null return null; } /** * @var ResourceAssociationSetEnd */ $relatedEnd = $resourceAssociationSet->getRelatedResourceAssociationSetEnd( $resourceSet->getResourceSet(), $resourceType, $navigationProperty ); //For bidirectional relationship IDSMP::getResourceAssociationSet should //return same association set when called from either end if (!is_null($relatedEnd->getResourceProperty())) { //No need to check whether the following call returns NULL, //because the above call //MetadataQueryproviderWrapper::getResourceAssociationSet //causes the metadata wrapper to check the visibility of //related resource set and cache the corrosponding wrapper. //If found invisible it would have return NULL, //which we are any way handling above. $relatedResourceSetWrapper = $this->metadataQueryproviderWrapper->validateResourceSetAndGetWrapper($relatedEnd->getResourceSet()); $reverseResourceAssociationSet = $this->metadataQueryproviderWrapper->getResourceAssociationSet($relatedResourceSetWrapper, $relatedEnd->getResourceType(), $relatedEnd->getResourceProperty()); if (is_null($reverseResourceAssociationSet) || (!is_null($reverseResourceAssociationSet) && $resourceAssociationSet->getName() != $reverseResourceAssociationSet->getName())) { throw new InvalidOperationException(Messages::metadataAssociationTypeSetBidirectionalAssociationMustReturnSameResourceAssociationSetFromBothEnd()); } } $reverseAssociationSetLookupKey = null; if (!is_null($relatedEnd->getResourceProperty())) { $reverseAssociationSetLookupKey = $relatedEnd->getResourceSet()->getName() . '_' . $relatedEnd->getResourceProperty()->getResourceType()->getFullName() . '_' . $relatedEnd->getResourceProperty()->getName(); } else { $reverseAssociationSetLookupKey = $relatedEnd->getResourceSet()->getName() . '_Null_' . $resourceType->getFullName() . '_' . $navigationProperty->getName(); } if (array_key_exists($reverseAssociationSetLookupKey, $this->_resourceAssociationSets)) { throw new InvalidOperationException(Messages::metadataAssociationTypeSetMultipleAssociationSetsForTheSameAssociationTypeMustNotReferToSameEndSets($this->_resourceAssociationSets[$reverseAssociationSetLookupKey]->getName(), $resourceAssociationSet->getName(), $relatedEnd->getResourceSet()->getName())); } $this->_resourceAssociationSets[$associationSetLookupKey] = $resourceAssociationSet; $this->_resourceAssociationSets[$reverseAssociationSetLookupKey] = $resourceAssociationSet; return $resourceAssociationSet; } /** * Gets the ResourceAssociationType instance for the given * ResourceAssociationSet and one of it's end. * * This function first searches the ResourceAssociationType cache, * if found return it otherwise create the Association type for the given * association set, cache and return it. * * Creation of ResourceAssociationType includes two sub-tasks: * 1. Deciding name of 'ResourceAssociationType' * (see the function _getAssociationTypeName) * 2. Deciding names for two 'ResourceAssociationTypeEnd' of the * 'ResourceAssociationType' * Refer ./AssociationSetAndTypeNamingRules.txt for naming rules. * * @param ResourceAssociationSet $resourceAssociationSet Association set to * get the * association type * @param ResourceSetWrapper $resourceSet Resource set for * one of the ends of * given association set * @param ResourceType $resourceType Resource type for * one of the ends of * given association set * @param ResourceProperty $navigationProperty Resource property for * one of the ends of * given association set * * @return ResourceAssociationType The association type * for the given association set */ private function _getResourceAssociationType(ResourceAssociationSet $resourceAssociationSet, ResourceSetWrapper $resourceSet, ResourceType $resourceType, ResourceProperty $navigationProperty) { $resourceTypeNamespace = $this->getResourceTypeNamespace($resourceType); $resourceAssociationTypesInNamespace = &$this->getResourceAssociationTypesForNamespace($resourceTypeNamespace); $associationTypeLookupKey = $resourceType->getName() . '_' . $navigationProperty->getName(); if (array_key_exists($associationTypeLookupKey, $resourceAssociationTypesInNamespace)) { return $resourceAssociationTypesInNamespace[$associationTypeLookupKey]; } //Generate resource association type end names //Refer ./AssociationSetAndTypeNamingRules.txt $associationTypeEnd1Name = $associationTypeEnd2Name = null; $isBiDirectional = $resourceAssociationSet->isBidirectional(); if ($isBiDirectional) { $associationTypeEnd1Name = $resourceAssociationSet->getEnd1()->getResourceType()->getName() . '_' . $resourceAssociationSet->getEnd1()->getResourceProperty()->getName(); $associationTypeEnd2Name = $resourceAssociationSet->getEnd2()->getResourceType()->getName() . '_' . $resourceAssociationSet->getEnd2()->getResourceProperty()->getName(); } else { if (!is_null($resourceAssociationSet->getEnd1()->getResourceProperty())) { $associationTypeEnd1Name = $resourceAssociationSet->getEnd1()->getResourceType()->getName(); $associationTypeEnd2Name = $resourceAssociationSet->getEnd1()->getResourceProperty()->getName(); } else { $associationTypeEnd1Name = $resourceAssociationSet->getEnd2()->getResourceProperty()->getName(); $associationTypeEnd2Name = $resourceAssociationSet->getEnd2()->getResourceType()->getName(); } } //Generate resource assoication type name //Refer ./AssociationSetAndTypeNamingRules.txt $resourceAssociationTypeName = $this->_getAssociationTypeName($resourceAssociationSet); //Create and cache the association type $resourceAssociationType = new ResourceAssociationType( $resourceAssociationTypeName, $resourceTypeNamespace, new ResourceAssociationTypeEnd( $associationTypeEnd1Name, $resourceAssociationSet->getEnd1()->getResourceType(), $resourceAssociationSet->getEnd1()->getResourceProperty(), $resourceAssociationSet->getEnd2()->getResourceProperty() ), new ResourceAssociationTypeEnd( $associationTypeEnd2Name, $resourceAssociationSet->getEnd2()->getResourceType(), $resourceAssociationSet->getEnd2()->getResourceProperty(), $resourceAssociationSet->getEnd1()->getResourceProperty() ) ); $resourceAssociationTypesInNamespace[$associationTypeLookupKey] = $resourceAssociationType; if ($isBiDirectional) { $relatedAssociationSetEnd = $resourceAssociationSet->getRelatedResourceAssociationSetEnd($resourceSet->getResourceSet(), $resourceType, $navigationProperty); $relatedEndLookupKey = $relatedAssociationSetEnd->getResourceType()->getName() . '_' . $relatedAssociationSetEnd->getResourceProperty()->getName(); $resourceAssociationTypesInNamespace[$relatedEndLookupKey] = $resourceAssociationType; } return $resourceAssociationType; } /** * Generate association type name for a given association set, * this name is used as value of Name attribute of Association type node in the * metadata corrosponding to the given association set. * * Refer ./AssociationSetAndTypeNamingRules.txt for naming rules. * * @param ResourceAssociationSet $resourceAssociationSet The association set * * @return string The association type name */ private function _getAssociationTypeName(ResourceAssociationSet $resourceAssociationSet) { $end1 = !is_null($resourceAssociationSet->getEnd1()->getResourceProperty()) ? $resourceAssociationSet->getEnd1() : $resourceAssociationSet->getEnd2(); $end2 = $resourceAssociationSet->getRelatedResourceAssociationSetEnd($end1->getResourceSet(), $end1->getResourceType(), $end1->getResourceProperty()); //e.g. Customer_Orders (w.r.t Northwind DB) $associationTypeName = $end1->getResourceType()->getName() . '_' . $end1->getResourceProperty()->getName(); if (!is_null($end2->getResourceProperty())) { //Customer_Orders_Order_Customer $associationTypeName .= '_' . $end2->getResourceType()->getName() . '_' . $end2->getResourceProperty()->getName(); } return $associationTypeName; } } ?>
{ "content_hash": "652a549b4c349eb88808936a17ea1647", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 314, "avg_line_length": 51.24009324009324, "alnum_prop": 0.6631334728414157, "repo_name": "msopentechcn/odata-plugin-for-sugarcrm", "id": "310d4beb8b50d29e380a8ae5d6a6394e287b8d96", "size": "24268", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "odata/library/ODataProducer/Writers/Metadata/MetadataAssociationTypeSet.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "111" }, { "name": "HTML", "bytes": "1562155" }, { "name": "PHP", "bytes": "2687927" } ], "symlink_target": "" }
""" Tests for dataset creation """ import random import math import unittest import os import numpy as np import deepchem as dc try: import torch # noqa PYTORCH_IMPORT_FAILED = False except ImportError: PYTORCH_IMPORT_FAILED = True def load_solubility_data(): """Loads solubility dataset""" current_dir = os.path.dirname(os.path.abspath(__file__)) featurizer = dc.feat.CircularFingerprint(size=1024) tasks = ["log-solubility"] input_file = os.path.join(current_dir, "../../models/tests/example.csv") loader = dc.data.CSVLoader( tasks=tasks, feature_field="smiles", featurizer=featurizer) return loader.create_dataset(input_file) def load_multitask_data(): """Load example multitask data.""" current_dir = os.path.dirname(os.path.abspath(__file__)) featurizer = dc.feat.CircularFingerprint(size=1024) tasks = [ "task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16" ] input_file = os.path.join(current_dir, "../../models/tests/multitask_example.csv") loader = dc.data.CSVLoader( tasks=tasks, feature_field="smiles", featurizer=featurizer) return loader.create_dataset(input_file) class TestTransformer(dc.trans.Transformer): def transform_array(self, X, y, w, ids): return (2 * X, 1.5 * y, w, ids) def test_transform_disk(): """Test that the transform() method works for DiskDatasets.""" dataset = load_solubility_data() X = dataset.X y = dataset.y w = dataset.w ids = dataset.ids # Transform it transformer = TestTransformer(transform_X=True, transform_y=True) for parallel in (True, False): transformed = dataset.transform(transformer, parallel=parallel) np.testing.assert_array_equal(X, dataset.X) np.testing.assert_array_equal(y, dataset.y) np.testing.assert_array_equal(w, dataset.w) np.testing.assert_array_equal(ids, dataset.ids) np.testing.assert_array_equal(2 * X, transformed.X) np.testing.assert_array_equal(1.5 * y, transformed.y) np.testing.assert_array_equal(w, transformed.w) np.testing.assert_array_equal(ids, transformed.ids) def test_sparsify_and_densify(): """Test that sparsify and densify work as inverses.""" # Test on identity matrix num_samples = 10 num_features = num_samples X = np.eye(num_samples) X_sparse = dc.data.sparsify_features(X) X_reconstructed = dc.data.densify_features(X_sparse, num_features) np.testing.assert_array_equal(X, X_reconstructed) # Generate random sparse features dataset np.random.seed(123) p = .05 X = np.random.binomial(1, p, size=(num_samples, num_features)) X_sparse = dc.data.sparsify_features(X) X_reconstructed = dc.data.densify_features(X_sparse, num_features) np.testing.assert_array_equal(X, X_reconstructed) # Test edge case with array of all zeros X = np.zeros((num_samples, num_features)) X_sparse = dc.data.sparsify_features(X) X_reconstructed = dc.data.densify_features(X_sparse, num_features) np.testing.assert_array_equal(X, X_reconstructed) def test_pad_features(): """Test that pad_features pads features correctly.""" batch_size = 100 num_features = 10 # Test cases where n_samples < 2*n_samples < batch_size n_samples = 29 X_b = np.zeros((n_samples, num_features)) X_out = dc.data.pad_features(batch_size, X_b) assert len(X_out) == batch_size # Test cases where n_samples < batch_size n_samples = 79 X_b = np.zeros((n_samples, num_features)) X_out = dc.data.pad_features(batch_size, X_b) assert len(X_out) == batch_size # Test case where n_samples == batch_size n_samples = 100 X_b = np.zeros((n_samples, num_features)) X_out = dc.data.pad_features(batch_size, X_b) assert len(X_out) == batch_size # Test case for object featurization. n_samples = 2 X_b = np.array([{"a": 1}, {"b": 2}]) X_out = dc.data.pad_features(batch_size, X_b) assert len(X_out) == batch_size # Test case for more complicated object featurization n_samples = 2 X_b = np.array([(1, {"a": 1}), (2, {"b": 2})]) X_out = dc.data.pad_features(batch_size, X_b) assert len(X_out) == batch_size # Test case with multidimensional data n_samples = 50 num_atoms = 15 d = 3 X_b = np.zeros((n_samples, num_atoms, d)) X_out = dc.data.pad_features(batch_size, X_b) assert len(X_out) == batch_size def test_pad_batches(): """Test that pad_batch pads batches correctly.""" batch_size = 100 num_features = 10 num_tasks = 5 # Test cases where n_samples < 2*n_samples < batch_size n_samples = 29 X_b = np.zeros((n_samples, num_features)) y_b = np.zeros((n_samples, num_tasks)) w_b = np.zeros((n_samples, num_tasks)) ids_b = np.zeros((n_samples,)) X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b, ids_b) assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size # Test cases where n_samples < batch_size n_samples = 79 X_b = np.zeros((n_samples, num_features)) y_b = np.zeros((n_samples, num_tasks)) w_b = np.zeros((n_samples, num_tasks)) ids_b = np.zeros((n_samples,)) X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b, ids_b) assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size # Test case where n_samples == batch_size n_samples = 100 X_b = np.zeros((n_samples, num_features)) y_b = np.zeros((n_samples, num_tasks)) w_b = np.zeros((n_samples, num_tasks)) ids_b = np.zeros((n_samples,)) X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b, ids_b) assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size # Test case for object featurization. n_samples = 2 X_b = np.array([{"a": 1}, {"b": 2}]) y_b = np.zeros((n_samples, num_tasks)) w_b = np.zeros((n_samples, num_tasks)) ids_b = np.zeros((n_samples,)) X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b, ids_b) assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size # Test case for more complicated object featurization n_samples = 2 X_b = np.array([(1, {"a": 1}), (2, {"b": 2})]) y_b = np.zeros((n_samples, num_tasks)) w_b = np.zeros((n_samples, num_tasks)) ids_b = np.zeros((n_samples,)) X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b, ids_b) assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size # Test case with multidimensional data n_samples = 50 num_atoms = 15 d = 3 X_b = np.zeros((n_samples, num_atoms, d)) y_b = np.zeros((n_samples, num_tasks)) w_b = np.zeros((n_samples, num_tasks)) ids_b = np.zeros((n_samples,)) X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b, ids_b) assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size def test_get_task_names(): """Test that get_task_names returns correct task_names""" solubility_dataset = load_solubility_data() assert solubility_dataset.get_task_names() == ["log-solubility"] multitask_dataset = load_multitask_data() assert sorted(multitask_dataset.get_task_names()) == sorted([ "task0", "task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10", "task11", "task12", "task13", "task14", "task15", "task16" ]) def test_get_data_shape(): """Test that get_data_shape returns currect data shape""" solubility_dataset = load_solubility_data() assert solubility_dataset.get_data_shape() == (1024,) multitask_dataset = load_multitask_data() assert multitask_dataset.get_data_shape() == (1024,) def test_len(): """Test that len(dataset) works.""" solubility_dataset = load_solubility_data() assert len(solubility_dataset) == 10 def test_reshard(): """Test that resharding the dataset works.""" solubility_dataset = load_solubility_data() X, y, w, ids = (solubility_dataset.X, solubility_dataset.y, solubility_dataset.w, solubility_dataset.ids) assert solubility_dataset.get_number_shards() == 1 solubility_dataset.reshard(shard_size=1) assert solubility_dataset.get_shard_size() == 1 X_r, y_r, w_r, ids_r = (solubility_dataset.X, solubility_dataset.y, solubility_dataset.w, solubility_dataset.ids) assert solubility_dataset.get_number_shards() == 10 solubility_dataset.reshard(shard_size=10) assert solubility_dataset.get_shard_size() == 10 X_rr, y_rr, w_rr, ids_rr = (solubility_dataset.X, solubility_dataset.y, solubility_dataset.w, solubility_dataset.ids) # Test first resharding worked np.testing.assert_array_equal(X, X_r) np.testing.assert_array_equal(y, y_r) np.testing.assert_array_equal(w, w_r) np.testing.assert_array_equal(ids, ids_r) # Test second resharding worked np.testing.assert_array_equal(X, X_rr) np.testing.assert_array_equal(y, y_rr) np.testing.assert_array_equal(w, w_rr) np.testing.assert_array_equal(ids, ids_rr) def test_complete_shuffle(): shard_sizes = [1, 2, 3, 4, 5] all_Xs, all_ys, all_ws, all_ids = [], [], [], [] def shard_generator(): for sz in shard_sizes: X_b = np.random.rand(sz, 1) y_b = np.random.rand(sz, 1) w_b = np.random.rand(sz, 1) ids_b = np.random.rand(sz) all_Xs.append(X_b) all_ys.append(y_b) all_ws.append(w_b) all_ids.append(ids_b) yield X_b, y_b, w_b, ids_b dataset = dc.data.DiskDataset.create_dataset(shard_generator()) res = dataset.complete_shuffle() # approx 1/15! chance of equality np.testing.assert_equal(np.any(np.not_equal(dataset.X, res.X)), True) np.testing.assert_equal(np.any(np.not_equal(dataset.y, res.w)), True) np.testing.assert_equal(np.any(np.not_equal(dataset.w, res.y)), True) np.testing.assert_equal(np.any(np.not_equal(dataset.ids, res.ids)), True) np.testing.assert_array_equal( np.sort(dataset.X, axis=0), np.sort(res.X, axis=0)) np.testing.assert_array_equal( np.sort(dataset.y, axis=0), np.sort(res.y, axis=0)) np.testing.assert_array_equal( np.sort(dataset.w, axis=0), np.sort(res.w, axis=0)) np.testing.assert_array_equal(np.sort(dataset.ids), np.sort(res.ids)) def test_iterbatches(): """Test that iterating over batches of data works.""" solubility_dataset = load_solubility_data() batch_size = 2 data_shape = solubility_dataset.get_data_shape() tasks = solubility_dataset.get_task_names() for (X_b, y_b, w_b, ids_b) in solubility_dataset.iterbatches(batch_size): assert X_b.shape == (batch_size,) + data_shape assert y_b.shape == (batch_size,) + (len(tasks),) assert w_b.shape == (batch_size,) + (len(tasks),) assert ids_b.shape == (batch_size,) def test_itersamples_numpy(): """Test that iterating over samples in a NumpyDataset works.""" num_datapoints = 100 num_features = 10 num_tasks = 10 # Generate data X = np.random.rand(num_datapoints, num_features) y = np.random.randint(2, size=(num_datapoints, num_tasks)) w = np.random.randint(2, size=(num_datapoints, num_tasks)) ids = np.array(["id"] * num_datapoints) dataset = dc.data.NumpyDataset(X, y, w, ids) for i, (sx, sy, sw, sid) in enumerate(dataset.itersamples()): np.testing.assert_array_equal(sx, X[i]) np.testing.assert_array_equal(sy, y[i]) np.testing.assert_array_equal(sw, w[i]) np.testing.assert_array_equal(sid, ids[i]) def test_itersamples_disk(): """Test that iterating over samples in a DiskDataset works.""" solubility_dataset = load_solubility_data() X = solubility_dataset.X y = solubility_dataset.y w = solubility_dataset.w ids = solubility_dataset.ids for i, (sx, sy, sw, sid) in enumerate(solubility_dataset.itersamples()): np.testing.assert_array_equal(sx, X[i]) np.testing.assert_array_equal(sy, y[i]) np.testing.assert_array_equal(sw, w[i]) np.testing.assert_array_equal(sid, ids[i]) def test_transform_numpy(): """Test that the transform() method works for NumpyDatasets.""" num_datapoints = 100 num_features = 10 num_tasks = 10 # Generate data X = np.random.rand(num_datapoints, num_features) y = np.random.randint(2, size=(num_datapoints, num_tasks)) w = np.random.randint(2, size=(num_datapoints, num_tasks)) ids = np.array(["id"] * num_datapoints) dataset = dc.data.NumpyDataset(X, y, w, ids) # Transform it transformer = TestTransformer(transform_X=True, transform_y=True) transformed = dataset.transform(transformer) np.testing.assert_array_equal(X, dataset.X) np.testing.assert_array_equal(y, dataset.y) np.testing.assert_array_equal(w, dataset.w) np.testing.assert_array_equal(ids, dataset.ids) np.testing.assert_array_equal(2 * X, transformed.X) np.testing.assert_array_equal(1.5 * y, transformed.y) np.testing.assert_array_equal(w, transformed.w) np.testing.assert_array_equal(ids, transformed.ids) def test_to_numpy(): """Test that transformation to numpy arrays is sensible.""" solubility_dataset = load_solubility_data() data_shape = solubility_dataset.get_data_shape() tasks = solubility_dataset.get_task_names() X, y, w, ids = (solubility_dataset.X, solubility_dataset.y, solubility_dataset.w, solubility_dataset.ids) N_samples = len(solubility_dataset) N_tasks = len(tasks) assert X.shape == (N_samples,) + data_shape assert y.shape == (N_samples, N_tasks) assert w.shape == (N_samples, N_tasks) assert ids.shape == (N_samples,) def test_consistent_ordering(): """Test that ordering of labels is consistent over time.""" solubility_dataset = load_solubility_data() ids1 = solubility_dataset.ids ids2 = solubility_dataset.ids assert np.array_equal(ids1, ids2) def test_get_statistics(): """Test statistics computation of this dataset.""" solubility_dataset = load_solubility_data() X, y, _, _ = (solubility_dataset.X, solubility_dataset.y, solubility_dataset.w, solubility_dataset.ids) X_means, y_means = np.mean(X, axis=0), np.mean(y, axis=0) X_stds, y_stds = np.std(X, axis=0), np.std(y, axis=0) comp_X_means, comp_X_stds, comp_y_means, comp_y_stds = \ solubility_dataset.get_statistics() np.testing.assert_allclose(comp_X_means, X_means) np.testing.assert_allclose(comp_y_means, y_means) np.testing.assert_allclose(comp_X_stds, X_stds) np.testing.assert_allclose(comp_y_stds, y_stds) def test_disk_iterate_batch_size(): solubility_dataset = load_solubility_data() X, y, _, _ = (solubility_dataset.X, solubility_dataset.y, solubility_dataset.w, solubility_dataset.ids) batch_sizes = [] for X, y, _, _ in solubility_dataset.iterbatches( 3, epochs=2, pad_batches=False, deterministic=True): batch_sizes.append(len(X)) assert [3, 3, 3, 1, 3, 3, 3, 1] == batch_sizes def test_disk_pad_batches(): shard_sizes = [21, 11, 41, 21, 51] batch_size = 10 all_Xs, all_ys, all_ws, all_ids = [], [], [], [] def shard_generator(): for sz in shard_sizes: X_b = np.random.rand(sz, 1) y_b = np.random.rand(sz, 1) w_b = np.random.rand(sz, 1) ids_b = np.random.rand(sz) all_Xs.append(X_b) all_ys.append(y_b) all_ws.append(w_b) all_ids.append(ids_b) yield X_b, y_b, w_b, ids_b dataset = dc.data.DiskDataset.create_dataset(shard_generator()) all_Xs = np.concatenate(all_Xs, axis=0) all_ys = np.concatenate(all_ys, axis=0) all_ws = np.concatenate(all_ws, axis=0) all_ids = np.concatenate(all_ids, axis=0) test_Xs, test_ys, test_ws, test_ids = [], [], [], [] for bidx, (a, b, c, d) in enumerate( dataset.iterbatches( batch_size=batch_size, pad_batches=True, deterministic=True)): test_Xs.append(a) test_ys.append(b) test_ws.append(c) test_ids.append(d) test_Xs = np.concatenate(test_Xs, axis=0) test_ys = np.concatenate(test_ys, axis=0) test_ws = np.concatenate(test_ws, axis=0) test_ids = np.concatenate(test_ids, axis=0) total_size = sum(shard_sizes) assert bidx == math.ceil(total_size / batch_size) - 1 expected_batches = math.ceil(total_size / batch_size) * batch_size assert len(test_Xs) == expected_batches assert len(test_ys) == expected_batches assert len(test_ws) == expected_batches assert len(test_ids) == expected_batches np.testing.assert_array_equal(all_Xs, test_Xs[:total_size, :]) np.testing.assert_array_equal(all_ys, test_ys[:total_size, :]) np.testing.assert_array_equal(all_ws, test_ws[:total_size, :]) np.testing.assert_array_equal(all_ids, test_ids[:total_size]) def test_disk_iterate_y_w_None(): shard_sizes = [21, 11, 41, 21, 51] batch_size = 10 all_Xs, all_ids = [], [] def shard_generator(): for sz in shard_sizes: X_b = np.random.rand(sz, 1) ids_b = np.random.rand(sz) all_Xs.append(X_b) all_ids.append(ids_b) yield X_b, None, None, ids_b dataset = dc.data.DiskDataset.create_dataset(shard_generator()) all_Xs = np.concatenate(all_Xs, axis=0) all_ids = np.concatenate(all_ids, axis=0) test_Xs, test_ids = [], [] for bidx, (a, _, _, d) in enumerate( dataset.iterbatches( batch_size=batch_size, pad_batches=True, deterministic=True)): test_Xs.append(a) test_ids.append(d) test_Xs = np.concatenate(test_Xs, axis=0) test_ids = np.concatenate(test_ids, axis=0) total_size = sum(shard_sizes) assert bidx == math.ceil(total_size / batch_size) - 1 expected_batches = math.ceil(total_size / batch_size) * batch_size assert len(test_Xs) == expected_batches assert len(test_ids) == expected_batches np.testing.assert_array_equal(all_Xs, test_Xs[:total_size, :]) np.testing.assert_array_equal(all_ids, test_ids[:total_size]) def test_disk_iterate_batch(): all_batch_sizes = [None, 32, 17, 11] all_shard_sizes = [[7, 3, 12, 4, 5], [1, 1, 1, 1, 1], [31, 31, 31, 31, 31], [21, 11, 41, 21, 51]] for idx in range(25): shard_length = random.randint(1, 32) shard_sizes = [] for _ in range(shard_length): shard_sizes.append(random.randint(1, 128)) all_shard_sizes.append(shard_sizes) if idx == 0: # special case to test all_batch_sizes.append(None) else: all_batch_sizes.append(random.randint(1, 256)) for shard_sizes, batch_size in zip(all_shard_sizes, all_batch_sizes): all_Xs, all_ys, all_ws, all_ids = [], [], [], [] def shard_generator(): for sz in shard_sizes: X_b = np.random.rand(sz, 1) y_b = np.random.rand(sz, 1) w_b = np.random.rand(sz, 1) ids_b = np.random.rand(sz) all_Xs.append(X_b) all_ys.append(y_b) all_ws.append(w_b) all_ids.append(ids_b) yield X_b, y_b, w_b, ids_b dataset = dc.data.DiskDataset.create_dataset(shard_generator()) all_Xs = np.concatenate(all_Xs, axis=0) all_ys = np.concatenate(all_ys, axis=0) all_ws = np.concatenate(all_ws, axis=0) all_ids = np.concatenate(all_ids, axis=0) total_size = sum(shard_sizes) assert dataset.X.shape[0] == total_size # deterministic test_Xs, test_ys, test_ws, test_ids = [], [], [], [] for bidx, (a, b, c, d) in enumerate( dataset.iterbatches( batch_size=batch_size, pad_batches=False, deterministic=True)): test_Xs.append(a) test_ys.append(b) test_ws.append(c) test_ids.append(d) if batch_size is None: for idx, (tx, ty, tw, tids) in enumerate( zip(test_Xs, test_ys, test_ws, test_ids)): assert len(tx) == shard_sizes[idx] assert len(ty) == shard_sizes[idx] assert len(tw) == shard_sizes[idx] assert len(tids) == shard_sizes[idx] test_Xs = np.concatenate(test_Xs, axis=0) test_ys = np.concatenate(test_ys, axis=0) test_ws = np.concatenate(test_ws, axis=0) test_ids = np.concatenate(test_ids, axis=0) if batch_size is None: assert bidx == len(shard_sizes) - 1 else: assert bidx == math.ceil(total_size / batch_size) - 1 np.testing.assert_array_equal(all_Xs, test_Xs) np.testing.assert_array_equal(all_ys, test_ys) np.testing.assert_array_equal(all_ws, test_ws) np.testing.assert_array_equal(all_ids, test_ids) # non-deterministic test_Xs, test_ys, test_ws, test_ids = [], [], [], [] for bidx, (a, b, c, d) in enumerate( dataset.iterbatches( batch_size=batch_size, pad_batches=False, deterministic=False)): test_Xs.append(a) test_ys.append(b) test_ws.append(c) test_ids.append(d) # we don't know the order in which the shards are iterated in. test_Xs = np.concatenate(test_Xs, axis=0) test_ys = np.concatenate(test_ys, axis=0) test_ws = np.concatenate(test_ws, axis=0) test_ids = np.concatenate(test_ids, axis=0) if batch_size is None: assert bidx == len(shard_sizes) - 1 else: assert bidx == math.ceil(total_size / batch_size) - 1 np.testing.assert_array_equal( np.sort(all_Xs, axis=0), np.sort(test_Xs, axis=0)) np.testing.assert_array_equal( np.sort(all_ys, axis=0), np.sort(test_ys, axis=0)) np.testing.assert_array_equal( np.sort(all_ws, axis=0), np.sort(test_ws, axis=0)) np.testing.assert_array_equal( np.sort(all_ids, axis=0), np.sort(test_ids, axis=0)) def test_merge(): """Test that dataset merge works.""" num_datapoints = 10 num_features = 10 num_tasks = 1 num_datasets = 4 datasets = [] for i in range(num_datasets): Xi = np.random.rand(num_datapoints, num_features) yi = np.random.randint(2, size=(num_datapoints, num_tasks)) wi = np.ones((num_datapoints, num_tasks)) idsi = np.array(["id"] * num_datapoints) dataseti = dc.data.DiskDataset.from_numpy(Xi, yi, wi, idsi) datasets.append(dataseti) new_data = dc.data.datasets.DiskDataset.merge(datasets) # Check that we have all the data in assert new_data.X.shape == (num_datapoints * num_datasets, num_features) assert new_data.y.shape == (num_datapoints * num_datasets, num_tasks) assert len(new_data.tasks) == len(datasets[0].tasks) def test_make_tf_dataset(): """Test creating a Tensorflow Iterator from a Dataset.""" X = np.random.random((100, 5)) y = np.random.random((100, 1)) dataset = dc.data.NumpyDataset(X, y) iterator = dataset.make_tf_dataset( batch_size=10, epochs=2, deterministic=True) for i, (batch_X, batch_y, batch_w) in enumerate(iterator): offset = (i % 10) * 10 np.testing.assert_array_equal(X[offset:offset + 10, :], batch_X) np.testing.assert_array_equal(y[offset:offset + 10, :], batch_y) np.testing.assert_array_equal(np.ones((10, 1)), batch_w) assert i == 19 def _validate_pytorch_dataset(dataset): X = dataset.X y = dataset.y w = dataset.w ids = dataset.ids n_samples = X.shape[0] # Test iterating in order. ds = dataset.make_pytorch_dataset(epochs=2, deterministic=True) for i, (iter_X, iter_y, iter_w, iter_id) in enumerate(ds): j = i % n_samples np.testing.assert_array_equal(X[j, :], iter_X) np.testing.assert_array_equal(y[j, :], iter_y) np.testing.assert_array_equal(w[j, :], iter_w) assert ids[j] == iter_id assert i == 2 * n_samples - 1 # Test iterating out of order. ds = dataset.make_pytorch_dataset(epochs=2, deterministic=False) id_to_index = dict((id, i) for i, id in enumerate(ids)) id_count = dict((id, 0) for id in ids) for iter_X, iter_y, iter_w, iter_id in ds: j = id_to_index[iter_id] np.testing.assert_array_equal(X[j, :], iter_X) np.testing.assert_array_equal(y[j, :], iter_y) np.testing.assert_array_equal(w[j, :], iter_w) id_count[iter_id] += 1 assert all(id_count[id] == 2 for id in ids) # Test iterating in batches. ds = dataset.make_pytorch_dataset(epochs=2, deterministic=False, batch_size=7) id_to_index = dict((id, i) for i, id in enumerate(ids)) id_count = dict((id, 0) for id in ids) for iter_X, iter_y, iter_w, iter_id in ds: size = len(iter_id) assert size <= 7 for i in range(size): j = id_to_index[iter_id[i]] np.testing.assert_array_equal(X[j, :], iter_X[i]) np.testing.assert_array_equal(y[j, :], iter_y[i]) np.testing.assert_array_equal(w[j, :], iter_w[i]) id_count[iter_id[i]] += 1 assert all(id_count[id] == 2 for id in ids) # Test iterating with multiple workers. import torch # noqa ds = dataset.make_pytorch_dataset(epochs=2, deterministic=False) loader = torch.utils.data.DataLoader(ds, num_workers=3) id_count = dict((id, 0) for id in ids) for iter_X, iter_y, iter_w, iter_id in loader: j = id_to_index[iter_id[0]] np.testing.assert_array_equal(X[j, :], iter_X[0]) np.testing.assert_array_equal(y[j, :], iter_y[0]) np.testing.assert_array_equal(w[j, :], iter_w[0]) id_count[iter_id[0]] += 1 assert all(id_count[id] == 2 for id in ids) def test_dataframe(): """Test converting between Datasets and DataFrames.""" dataset = load_solubility_data() # A round trip from Dataset to DataFrame to Dataset should produce identical arrays. df = dataset.to_dataframe() dataset2 = dc.data.Dataset.from_dataframe(df) np.testing.assert_array_equal(dataset.X, dataset2.X) np.testing.assert_array_equal(dataset.y, dataset2.y) np.testing.assert_array_equal(dataset.w, dataset2.w) np.testing.assert_array_equal(dataset.ids, dataset2.ids) # Try specifying particular columns. dataset3 = dc.data.Dataset.from_dataframe( df, X=['X2', 'X4'], y='w', w=['y', 'X1']) np.testing.assert_array_equal(dataset.X[:, (1, 3)], dataset3.X) np.testing.assert_array_equal(dataset.w, dataset3.y) np.testing.assert_array_equal( np.stack([dataset.y[:, 0], dataset.X[:, 0]], axis=1), dataset3.w) def test_to_str(): """Tests to string representation of Dataset.""" dataset = dc.data.NumpyDataset( X=np.random.rand(5, 3), y=np.random.rand(5,), ids=np.arange(5)) ref_str = '<NumpyDataset X.shape: (5, 3), y.shape: (5,), w.shape: (5,), ids: [0 1 2 3 4], task_names: [0]>' assert str(dataset) == ref_str # Test id shrinkage dc.utils.set_print_threshold(10) dataset = dc.data.NumpyDataset( X=np.random.rand(50, 3), y=np.random.rand(50,), ids=np.arange(50)) ref_str = '<NumpyDataset X.shape: (50, 3), y.shape: (50,), w.shape: (50,), ids: [0 1 2 ... 47 48 49], task_names: [0]>' assert str(dataset) == ref_str # Test task shrinkage dataset = dc.data.NumpyDataset( X=np.random.rand(50, 3), y=np.random.rand(50, 20), ids=np.arange(50)) ref_str = '<NumpyDataset X.shape: (50, 3), y.shape: (50, 20), w.shape: (50, 1), ids: [0 1 2 ... 47 48 49], task_names: [ 0 1 2 ... 17 18 19]>' assert str(dataset) == ref_str # Test max print size dc.utils.set_max_print_size(25) dataset = dc.data.NumpyDataset( X=np.random.rand(50, 3), y=np.random.rand(50,), ids=np.arange(50)) ref_str = '<NumpyDataset X.shape: (50, 3), y.shape: (50,), w.shape: (50,), task_names: [0]>' assert str(dataset) == ref_str class TestDatasets(unittest.TestCase): """ Test basic top-level API for dataset objects. """ def test_numpy_iterate_batch_size(self): solubility_dataset = load_solubility_data() X, y, _, _ = (solubility_dataset.X, solubility_dataset.y, solubility_dataset.w, solubility_dataset.ids) solubility_dataset = dc.data.NumpyDataset.from_DiskDataset( solubility_dataset) batch_sizes = [] for X, y, _, _ in solubility_dataset.iterbatches( 3, epochs=2, pad_batches=False, deterministic=True): batch_sizes.append(len(X)) self.assertEqual([3, 3, 3, 1, 3, 3, 3, 1], batch_sizes) @unittest.skipIf(PYTORCH_IMPORT_FAILED, 'PyTorch is not installed') def test_make_pytorch_dataset_from_numpy(self): """Test creating a PyTorch Dataset from a NumpyDataset.""" X = np.random.random((100, 5)) y = np.random.random((100, 1)) ids = [str(i) for i in range(100)] dataset = dc.data.NumpyDataset(X, y, ids=ids) _validate_pytorch_dataset(dataset) @unittest.skipIf(PYTORCH_IMPORT_FAILED, 'PyTorch is not installed') def test_make_pytorch_dataset_from_images(self): """Test creating a PyTorch Dataset from an ImageDataset.""" path = os.path.join(os.path.dirname(__file__), 'images') files = [os.path.join(path, f) for f in os.listdir(path)] y = np.random.random((10, 1)) ids = [str(i) for i in range(len(files))] dataset = dc.data.ImageDataset(files, y, ids=ids) _validate_pytorch_dataset(dataset) @unittest.skipIf(PYTORCH_IMPORT_FAILED, 'PyTorch is not installed') def test_make_pytorch_dataset_from_disk(self): """Test creating a PyTorch Dataset from a DiskDataset.""" dataset = load_solubility_data() _validate_pytorch_dataset(dataset)
{ "content_hash": "f3675e6460b4d5fe20611457d876ea74", "timestamp": "", "source": "github", "line_count": 846, "max_line_length": 146, "avg_line_length": 34.45390070921986, "alnum_prop": 0.6424454508027995, "repo_name": "lilleswing/deepchem", "id": "711529e2143ea7618f3e005a559b4f71d078f365", "size": "29148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deepchem/data/tests/test_datasets.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16453" }, { "name": "Dockerfile", "bytes": "794" }, { "name": "HTML", "bytes": "20618" }, { "name": "Jupyter Notebook", "bytes": "59756" }, { "name": "Python", "bytes": "2597968" }, { "name": "Shell", "bytes": "11491" } ], "symlink_target": "" }
var DEBUG_TEXTURE = false; var mapLinear = THREE.Math.mapLinear; App.Dust = Dust; function Dust(opts) { this.pxRatio = opts.pxRatio || 1; this.particleSize = 32 * this.pxRatio; this.particleCount = 8000; this.area = 300; this.createParticles(); this.createMaterials(); this.createItem(); } Dust.create = App.ctor(Dust); Dust.prototype.createParticles = function () { var count = this.particleCount; var geom = this.geometry = new THREE.BufferGeometry(); var verts = new Float32Array(count * 3); var area = this.area; var areaHalf = area * 0.5; var ix; for (var i = 0, il = verts.length / 3; i < il; i ++) { ix = i * 3; verts[ix] = Math.random() * area - areaHalf; verts[ix + 1] = Math.random() * area - areaHalf; verts[ix + 2] = Math.random() * area - areaHalf; } geom.addAttribute('position', new THREE.BufferAttribute(verts, 3)); }; Dust.prototype.createTexture = function () { var canvas = document.createElement('canvas'); var texture = new THREE.Texture(canvas); var ctx = canvas.getContext('2d'); var size = Math.pow(2, 6); var sizeHalf = size * 0.5; var rings = 2; var t, radius, alpha; canvas.width = canvas.height = size; ctx.fillStyle = '#fff'; for (var i = 0; i < rings; i ++) { t = i / (rings - 1); radius = mapLinear(t * t, 0, 1, 4, sizeHalf); alpha = mapLinear(t, 0, 1, 1, 0.05); ctx.beginPath(); ctx.arc(sizeHalf, sizeHalf, radius, 0, Math.PI * 2); ctx.globalAlpha = alpha; ctx.fill(); } texture.needsUpdate = true; if (DEBUG_TEXTURE) { document.body.appendChild(canvas); canvas.style.position = 'absolute'; } return texture; }; Dust.prototype.createMaterials = function () { var params = { psColor : 0xffffff, opacity : 0.95, size : this.particleSize, map : this.createTexture(), scale : 150, area : this.area, blending: THREE.AdditiveBlending, transparent : true, depthTest : false, depthWrite : false }; this.materialFore = new App.DustMaterial(params); // params.depthTest = false; // params.opacity = 0.25; // this.materialFaint = new App.DustMaterial(params); // this.timeAttrFaint = this.materialFaint.uniforms.time; this.timeAttrFore = this.materialFore.uniforms.time; }; Dust.prototype.createItem = function () { // this.itemFaint = new THREE.PointCloud(this.geometry, this.materialFaint); this.itemFore = new THREE.Points(this.geometry, this.materialFore); }; Dust.prototype.addTo = function (scene) { // scene.add(this.itemFaint); scene.add(this.itemFore); }; Dust.prototype.updateGraphics = function (delta) { // this.timeAttrFaint.value += delta * 0.005; this.timeAttrFore.value += delta * 0.005; };
{ "content_hash": "af30395af6c081afad9f3147adbfc4ad", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 78, "avg_line_length": 25.36111111111111, "alnum_prop": 0.6487769258853596, "repo_name": "azukiapp/static-nginx-boilerplate", "id": "ec216a3878f75114ae16bd8ca55ece5e97a3e6a5", "size": "2739", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sites/particulate-medusae/static/js/items/Dust.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9373" }, { "name": "GLSL", "bytes": "10558" }, { "name": "HTML", "bytes": "18425" }, { "name": "JavaScript", "bytes": "1053420" }, { "name": "Shell", "bytes": "4218" } ], "symlink_target": "" }
#include "CppUTest/TestHarness_c.h" #include "CppUTest/PlatformSpecificFunctions_c.h" extern void functionWithUnusedParameter(void* PUNUSED(unlessParamater)); void functionWithUnusedParameter(void* PUNUSED(unlessParamater)) { } /* Declared in the cpp file */ extern int setup_teardown_was_called_in_test_group_in_C; extern int test_was_called_in_test_group_in_C; TEST_GROUP_C_SETUP(TestGroupInC) { setup_teardown_was_called_in_test_group_in_C++; } TEST_GROUP_C_TEARDOWN(TestGroupInC) { setup_teardown_was_called_in_test_group_in_C--; CHECK_C(test_was_called_in_test_group_in_C == 1); test_was_called_in_test_group_in_C--; } TEST_C(TestGroupInC, checkThatTheTestHasRun) { test_was_called_in_test_group_in_C++; } IGNORE_TEST_C(TestGroupInC, ignoreMacroForCFile) { test_was_called_in_test_group_in_C++; }
{ "content_hash": "c4542228f3a538aecacfaf433366d891", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 72, "avg_line_length": 23.194444444444443, "alnum_prop": 0.7377245508982035, "repo_name": "asgeroverby/cpputest", "id": "bfc7d767f09fbc9abb764aebb513b460f2437750", "size": "835", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "tests/CppUTest/TestHarness_cTestCFile.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3844" }, { "name": "C", "bytes": "64990" }, { "name": "C++", "bytes": "1311550" }, { "name": "CMake", "bytes": "28943" }, { "name": "M4", "bytes": "42560" }, { "name": "Makefile", "bytes": "110599" }, { "name": "Objective-C", "bytes": "1790" }, { "name": "PowerShell", "bytes": "8457" }, { "name": "Ruby", "bytes": "19028" }, { "name": "Shell", "bytes": "18298" }, { "name": "sed", "bytes": "30" } ], "symlink_target": "" }
package com.amazonaws.services.ec2.model.transform; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Map.Entry; import javax.xml.stream.events.XMLEvent; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.MapEntry; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * ModifyIdFormatResult StAX Unmarshaller */ public class ModifyIdFormatResultStaxUnmarshaller implements Unmarshaller<ModifyIdFormatResult, StaxUnmarshallerContext> { public ModifyIdFormatResult unmarshall(StaxUnmarshallerContext context) throws Exception { ModifyIdFormatResult modifyIdFormatResult = new ModifyIdFormatResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return modifyIdFormatResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return modifyIdFormatResult; } } } } private static ModifyIdFormatResultStaxUnmarshaller instance; public static ModifyIdFormatResultStaxUnmarshaller getInstance() { if (instance == null) instance = new ModifyIdFormatResultStaxUnmarshaller(); return instance; } }
{ "content_hash": "c5f52ebcfd9a3cb1631b9632962efa19", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 79, "avg_line_length": 31.072727272727274, "alnum_prop": 0.6916325336454067, "repo_name": "nterry/aws-sdk-java", "id": "7d4c484c572c2c8932e80f9a155c134ba4c6b12b", "size": "2296", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/ModifyIdFormatResultStaxUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "126417" }, { "name": "Java", "bytes": "113994954" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
package com.intellij.ui.tabs.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.*; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.ui.switcher.QuickActionProvider; import com.intellij.ui.switcher.SwitchProvider; import com.intellij.ui.switcher.SwitchTarget; import com.intellij.ui.tabs.*; import com.intellij.ui.tabs.impl.singleRow.SingleRowLayout; import com.intellij.ui.tabs.impl.singleRow.SingleRowPassInfo; import com.intellij.ui.tabs.impl.table.TableLayout; import com.intellij.ui.tabs.impl.table.TablePassInfo; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.Animator; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.TimedDeadzone; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.ComparableObject; import com.intellij.util.ui.update.LazyUiDisposable; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.plaf.ComponentUI; import java.awt.*; import java.awt.event.*; import java.awt.geom.Line2D; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.*; import java.util.List; public class JBTabsImpl extends JComponent implements JBTabs, PropertyChangeListener, TimerListener, DataProvider, PopupMenuListener, Disposable, JBTabsPresentation, Queryable, QuickActionProvider { public static final DataKey<JBTabsImpl> NAVIGATION_ACTIONS_KEY = DataKey.create("JBTabs"); public static final Color MAC_AQUA_BG_COLOR = Gray._200; final ActionManager myActionManager; private final List<TabInfo> myVisibleInfos = new ArrayList<TabInfo>(); private final Map<TabInfo, Integer> myHiddenInfos = new HashMap<TabInfo, Integer>(); private TabInfo mySelectedInfo; public final Map<TabInfo, TabLabel> myInfo2Label = new HashMap<TabInfo, TabLabel>(); public final Map<TabInfo, Toolbar> myInfo2Toolbar = new HashMap<TabInfo, Toolbar>(); public Dimension myHeaderFitSize; private Insets myInnerInsets = JBInsets.NONE; private final List<EventListener> myTabMouseListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private final List<TabsListener> myTabListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private boolean myFocused; private Getter<ActionGroup> myPopupGroup; private String myPopupPlace; TabInfo myPopupInfo; final DefaultActionGroup myNavigationActions; final PopupMenuListener myPopupListener; JPopupMenu myActivePopup; public boolean myHorizontalSide = true; private boolean myStealthTabMode = false; private boolean mySideComponentOnTabs = true; private DataProvider myDataProvider; private final WeakHashMap<Component, Component> myDeferredToRemove = new WeakHashMap<Component, Component>(); private final SingleRowLayout mySingleRowLayout; private final TableLayout myTableLayout = new TableLayout(this); private TabLayout myLayout; private LayoutPassInfo myLastLayoutPass; private TabInfo myLastPaintedSelection; public boolean myForcedRelayout; private UiDecorator myUiDecorator; static final UiDecorator ourDefaultDecorator = new DefaultDecorator(); private boolean myPaintFocus; private boolean myHideTabs = false; @Nullable private Project myProject; private boolean myRequestFocusOnLastFocusedComponent = false; private boolean myListenerAdded; final Set<TabInfo> myAttractions = new HashSet<TabInfo>(); private final Animator myAnimator; private List<TabInfo> myAllTabs; private boolean myPaintBlocked; private BufferedImage myImage; private IdeFocusManager myFocusManager; private final boolean myAdjustBorders = true; boolean myAddNavigationGroup = true; private boolean myGhostsAlwaysVisible = false; private boolean myDisposed; private boolean myToDrawBorderIfTabsHidden = true; private Color myActiveTabFillIn; private boolean myTabLabelActionsAutoHide; private final TabActionsAutoHideListener myTabActionsAutoHideListener = new TabActionsAutoHideListener(); private IdeGlassPane myGlassPane; @NonNls private static final String LAYOUT_DONE = "Layout.done"; @NonNls public static final String STRETCHED_BY_WIDTH = "Layout.stretchedByWidth"; private TimedDeadzone.Length myTabActionsMouseDeadzone = TimedDeadzone.DEFAULT; private long myRemoveDeferredRequest; private boolean myTestMode; private JBTabsPosition myPosition = JBTabsPosition.top; private final TabsBorder myBorder = new TabsBorder(this); private BaseNavigationAction myNextAction; private BaseNavigationAction myPrevAction; private boolean myTabDraggingEnabled; private DragHelper myDragHelper; private boolean myNavigationActionsEnabled = true; private boolean myUseBufferedPaint = true; private boolean myOwnSwitchProvider = true; private SwitchProvider mySwitchDelegate; protected TabInfo myDropInfo; private int myDropInfoIndex; protected boolean myShowDropLocation = true; private TabInfo myOldSelection; private SelectionChangeHandler mySelectionChangeHandler; private Runnable myDeferredFocusRequest; private boolean myAlwaysPaintSelectedTab; public JBTabsImpl(@NotNull Project project) { this(project, project); } private JBTabsImpl(@NotNull Project project, @NotNull Disposable parent) { this(project, ActionManager.getInstance(), IdeFocusManager.getInstance(project), parent); } public JBTabsImpl(@Nullable Project project, IdeFocusManager focusManager, @NotNull Disposable parent) { this(project, ActionManager.getInstance(), focusManager, parent); } public JBTabsImpl(@Nullable Project project, ActionManager actionManager, IdeFocusManager focusManager, @NotNull Disposable parent) { myProject = project; myActionManager = actionManager; myFocusManager = focusManager != null ? focusManager : IdeFocusManager.getGlobalInstance(); setOpaque(true); setPaintBorder(-1, -1, -1, -1); Disposer.register(parent, this); myNavigationActions = new DefaultActionGroup(); if (myActionManager != null) { myNextAction = new SelectNextAction(this, myActionManager); myPrevAction = new SelectPreviousAction(this, myActionManager); myNavigationActions.add(myNextAction); myNavigationActions.add(myPrevAction); } setUiDecorator(null); mySingleRowLayout = createSingleRowLayout(); myLayout = mySingleRowLayout; myPopupListener = new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { disposePopupListener(); } @Override public void popupMenuCanceled(final PopupMenuEvent e) { disposePopupListener(); } }; addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (mySingleRowLayout.myLastSingRowLayout != null && mySingleRowLayout.myLastSingRowLayout.moreRect != null && mySingleRowLayout.myLastSingRowLayout.moreRect.contains(e.getPoint())) { showMorePopup(e); } } }); addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (mySingleRowLayout.myLastSingRowLayout != null) { mySingleRowLayout.scroll(e.getUnitsToScroll() * mySingleRowLayout.getScrollUnitIncrement()); revalidateAndRepaint(false); } } }); myAnimator = new Animator("JBTabs Attractions", 2, 500, true) { @Override public void paintNow(final int frame, final int totalFrames, final int cycle) { repaintAttractions(); } }; setFocusCycleRoot(true); setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() { @Override public Component getDefaultComponent(final Container aContainer) { return getToFocus(); } }); add(mySingleRowLayout.myLeftGhost); add(mySingleRowLayout.myRightGhost); new LazyUiDisposable<JBTabsImpl>(parent, this, this) { @Override protected void initialize(@NotNull Disposable parent, @NotNull JBTabsImpl child, @Nullable Project project) { if (project != null) { myProject = project; } Disposer.register(child, myAnimator); Disposer.register(child, new Disposable() { @Override public void dispose() { removeTimerUpdate(); } }); if (!myTestMode) { final IdeGlassPane gp = IdeGlassPaneUtil.find(child); if (gp != null) { gp.addMouseMotionPreprocessor(myTabActionsAutoHideListener, child); myGlassPane = gp; } UIUtil.addAwtListener(new AWTEventListener() { @Override public void eventDispatched(final AWTEvent event) { if (mySingleRowLayout.myMorePopup != null) return; processFocusChange(); } }, AWTEvent.FOCUS_EVENT_MASK, child); myDragHelper = new DragHelper(child); myDragHelper.start(); } if (myProject != null && myFocusManager == IdeFocusManager.getGlobalInstance()) { myFocusManager = IdeFocusManager.getInstance(myProject); } } }; } protected SingleRowLayout createSingleRowLayout() { return new SingleRowLayout(this); } @Override public JBTabs setNavigationActionBinding(String prevActionId, String nextActionId) { if (myNextAction != null) { myNextAction.reconnect(nextActionId); } if (myPrevAction != null) { myPrevAction.reconnect(prevActionId); } return this; } public boolean isEditorTabs() { return false; } @Override public JBTabs setNavigationActionsEnabled(boolean enabled) { myNavigationActionsEnabled = enabled; return this; } @Override public final boolean isDisposed() { return myDisposed; } @Override public JBTabs setAdditionalSwitchProviderWhenOriginal(SwitchProvider delegate) { mySwitchDelegate = delegate; return this; } public static Image getComponentImage(TabInfo info) { JComponent cmp = info.getComponent(); BufferedImage img; if (cmp.isShowing()) { final int width = cmp.getWidth(); final int height = cmp.getHeight(); img = UIUtil.createImage(width > 0 ? width : 500, height > 0 ? height : 500, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); cmp.paint(g); } else { img = UIUtil.createImage(500, 500, BufferedImage.TYPE_INT_ARGB); } return img; } @Override public void dispose() { myDisposed = true; mySelectedInfo = null; resetTabsCache(); myAttractions.clear(); myVisibleInfos.clear(); myUiDecorator = null; myImage = null; myActivePopup = null; myInfo2Label.clear(); myInfo2Toolbar.clear(); myTabListeners.clear(); } void resetTabsCache() { myAllTabs = null; } private void processFocusChange() { Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) { setFocused(false); return; } if (owner == this || SwingUtilities.isDescendingFrom(owner, this)) { setFocused(true); } else { setFocused(false); } } private void repaintAttractions() { boolean needsUpdate = false; for (TabInfo each : myVisibleInfos) { TabLabel eachLabel = myInfo2Label.get(each); needsUpdate |= eachLabel.repaintAttraction(); } if (needsUpdate) { relayout(true, false); } } @Override public void addNotify() { super.addNotify(); addTimerUpdate(); if (myDeferredFocusRequest != null) { final Runnable request = myDeferredFocusRequest; myDeferredFocusRequest = null; request.run(); } } @Override public void removeNotify() { super.removeNotify(); setFocused(false); removeTimerUpdate(); if (ScreenUtil.isStandardAddRemoveNotify(this) && myGlassPane != null) { myGlassPane.removeMouseMotionPreprocessor(myTabActionsAutoHideListener); myGlassPane = null; } } @Override public void processMouseEvent(MouseEvent e) { super.processMouseEvent(e); } private void addTimerUpdate() { if (myActionManager != null && !myListenerAdded) { myActionManager.addTimerListener(500, this); myListenerAdded = true; } } private void removeTimerUpdate() { if (myActionManager != null && myListenerAdded) { myActionManager.removeTimerListener(this); myListenerAdded = false; } } void setTestMode(final boolean testMode) { myTestMode = testMode; } public void layoutComp(SingleRowPassInfo data, int deltaX, int deltaY, int deltaWidth, int deltaHeight) { if (data.hToolbar != null) { final int toolbarHeight = data.hToolbar.getPreferredSize().height; final Rectangle compRect = layoutComp(deltaX, toolbarHeight + deltaY, data.comp, deltaWidth, deltaHeight); layout(data.hToolbar, compRect.x, compRect.y - toolbarHeight, compRect.width, toolbarHeight); } else if (data.vToolbar != null) { final int toolbarWidth = data.vToolbar.getPreferredSize().width; final Rectangle compRect = layoutComp(toolbarWidth + deltaX, deltaY, data.comp, deltaWidth, deltaHeight); layout(data.vToolbar, compRect.x - toolbarWidth, compRect.y, toolbarWidth, compRect.height); } else { layoutComp(deltaX, deltaY, data.comp, deltaWidth, deltaHeight); } } public boolean isDropTarget(TabInfo info) { return myDropInfo != null && myDropInfo == info; } protected void setDropInfoIndex(int dropInfoIndex) { myDropInfoIndex = dropInfoIndex; } class TabActionsAutoHideListener extends MouseMotionAdapter { private TabLabel myCurrentOverLabel; private Point myLastOverPoint; @Override public void mouseMoved(final MouseEvent e) { if (!myTabLabelActionsAutoHide) return; myLastOverPoint = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), JBTabsImpl.this); processMouseOver(); } void processMouseOver() { if (!myTabLabelActionsAutoHide) return; if (myLastOverPoint == null) return; if (myLastOverPoint.x >= 0 && myLastOverPoint.x < getWidth() && myLastOverPoint.y > 0 && myLastOverPoint.y < getHeight()) { final TabLabel label = myInfo2Label.get(_findInfo(myLastOverPoint, true)); if (label != null) { if (myCurrentOverLabel != null) { myCurrentOverLabel.toggleShowActions(false); } label.toggleShowActions(true); myCurrentOverLabel = label; return; } } if (myCurrentOverLabel != null) { myCurrentOverLabel.toggleShowActions(false); myCurrentOverLabel = null; } } } @Override public ModalityState getModalityState() { return ModalityState.stateForComponent(this); } @Override public void run() { updateTabActions(false); } public void updateTabActions(final boolean validateNow) { final Ref<Boolean> changed = new Ref<Boolean>(Boolean.FALSE); for (final TabInfo eachInfo : myInfo2Label.keySet()) { updateTab(new Computable<Boolean>() { @Override public Boolean compute() { final boolean changes = myInfo2Label.get(eachInfo).updateTabActions(); changed.set(changed.get().booleanValue() || changes); return changes; } }, eachInfo); } if (changed.get().booleanValue()) { if (validateNow) { validate(); paintImmediately(0, 0, getWidth(), getHeight()); } } } public boolean canShowMorePopup() { final SingleRowPassInfo lastLayout = mySingleRowLayout.myLastSingRowLayout; return lastLayout != null && lastLayout.moreRect != null; } public void showMorePopup(@Nullable final MouseEvent e) { final SingleRowPassInfo lastLayout = mySingleRowLayout.myLastSingRowLayout; if (lastLayout == null) { return; } mySingleRowLayout.myMorePopup = new JBPopupMenu(); for (final TabInfo each : myVisibleInfos) { if (!mySingleRowLayout.isTabHidden(each)) continue; final JBMenuItem item = new JBMenuItem(each.getText(), each.getIcon()); item.setForeground(each.getDefaultForeground()); item.setBackground(each.getTabColor()); mySingleRowLayout.myMorePopup.add(item); item.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { select(each, true); } }); } mySingleRowLayout.myMorePopup.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { mySingleRowLayout.myMorePopup = null; } @Override public void popupMenuCanceled(final PopupMenuEvent e) { mySingleRowLayout.myMorePopup = null; } }); if (e != null) { mySingleRowLayout.myMorePopup.show(this, e.getX(), e.getY()); } else { final Rectangle rect = lastLayout.moreRect; if (rect != null) { mySingleRowLayout.myMorePopup.show(this, rect.x, rect.y + rect.height); } } } @Nullable private JComponent getToFocus() { final TabInfo info = getSelectedInfo(); if (info == null) return null; JComponent toFocus = null; if (isRequestFocusOnLastFocusedComponent() && info.getLastFocusOwner() != null && !isMyChildIsFocusedNow()) { toFocus = info.getLastFocusOwner(); } if (toFocus == null && info.getPreferredFocusableComponent() == null) { return null; } if (toFocus == null) { toFocus = info.getPreferredFocusableComponent(); final JComponent policyToFocus = myFocusManager.getFocusTargetFor(toFocus); if (policyToFocus != null) { toFocus = policyToFocus; } } return toFocus; } @Override public void requestFocus() { final JComponent toFocus = getToFocus(); if (toFocus != null) { toFocus.requestFocus(); } else { super.requestFocus(); } } @Override public boolean requestFocusInWindow() { final JComponent toFocus = getToFocus(); if (toFocus != null) { return toFocus.requestFocusInWindow(); } else { return super.requestFocusInWindow(); } } @Override @NotNull public TabInfo addTab(TabInfo info, int index) { return addTab(info, index, false, true); } public TabInfo addTabSilently(TabInfo info, int index) { return addTab(info, index, false, false); } private TabInfo addTab(TabInfo info, int index, boolean isDropTarget, boolean fireEvents) { if (!isDropTarget && getTabs().contains(info)) { return getTabs().get(getTabs().indexOf(info)); } info.getChangeSupport().addPropertyChangeListener(this); final TabLabel label = createTabLabel(info); myInfo2Label.put(info, label); if (!isDropTarget) { if (index < 0 || index > myVisibleInfos.size() - 1) { myVisibleInfos.add(info); } else { myVisibleInfos.add(index, info); } } resetTabsCache(); updateText(info); updateIcon(info); updateSideComponent(info); updateTabActions(info); add(label); adjust(info); updateAll(false, false); if (info.isHidden()) { updateHiding(); } if (!isDropTarget && fireEvents) { if (getTabCount() == 1) { fireBeforeSelectionChanged(null, info); fireSelectionChanged(null, info); } } revalidateAndRepaint(false); return info; } protected TabLabel createTabLabel(TabInfo info) { return new TabLabel(this, info); } @Override @NotNull public TabInfo addTab(TabInfo info) { return addTab(info, -1); } @Nullable public ActionGroup getPopupGroup() { return myPopupGroup != null ? myPopupGroup.get() : null; } public String getPopupPlace() { return myPopupPlace; } @Override @NotNull public JBTabs setPopupGroup(@NotNull final ActionGroup popupGroup, @NotNull String place, final boolean addNavigationGroup) { return setPopupGroup(new Getter<ActionGroup>() { @Override public ActionGroup get() { return popupGroup; } }, place, addNavigationGroup); } @NotNull public JBTabs setPopupGroup(@NotNull final Getter<ActionGroup> popupGroup, @NotNull final String place, final boolean addNavigationGroup) { myPopupGroup = popupGroup; myPopupPlace = place; myAddNavigationGroup = addNavigationGroup; return this; } private void updateAll(final boolean forcedRelayout, final boolean now) { mySelectedInfo = getSelectedInfo(); updateContainer(forcedRelayout, now); removeDeferred(); updateListeners(); updateTabActions(false); updateEnabling(); } private boolean isMyChildIsFocusedNow() { final Component owner = getFocusOwner(); if (owner == null) return false; if (mySelectedInfo != null) { if (!SwingUtilities.isDescendingFrom(owner, mySelectedInfo.getComponent())) return false; } return SwingUtilities.isDescendingFrom(owner, this); } @Nullable private static JComponent getFocusOwner() { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); return (JComponent)(owner instanceof JComponent ? owner : null); } @Override @NotNull public ActionCallback select(@NotNull TabInfo info, boolean requestFocus) { return _setSelected(info, requestFocus); } @NotNull private ActionCallback _setSelected(final TabInfo info, final boolean requestFocus) { if (mySelectionChangeHandler != null) { return mySelectionChangeHandler.execute(info, requestFocus, new ActiveRunnable() { @NotNull @Override public ActionCallback run() { return executeSelectionChange(info, requestFocus); } }); } else { return executeSelectionChange(info, requestFocus); } } @NotNull private ActionCallback executeSelectionChange(TabInfo info, boolean requestFocus) { if (mySelectedInfo != null && mySelectedInfo.equals(info)) { if (!requestFocus) { return new ActionCallback.Done(); } else { Component owner = myFocusManager.getFocusOwner(); JComponent c = info.getComponent(); if (c != null && owner != null) { if (c == owner || SwingUtilities.isDescendingFrom(owner, c)) { return new ActionCallback.Done(); } } return requestFocus(getToFocus()); } } if (myRequestFocusOnLastFocusedComponent && mySelectedInfo != null) { if (isMyChildIsFocusedNow()) { mySelectedInfo.setLastFocusOwner(getFocusOwner()); } } TabInfo oldInfo = mySelectedInfo; mySelectedInfo = info; final TabInfo newInfo = getSelectedInfo(); fireBeforeSelectionChanged(oldInfo, newInfo); updateContainer(false, true); fireSelectionChanged(oldInfo, newInfo); if (requestFocus) { final JComponent toFocus = getToFocus(); if (myProject != null && toFocus != null) { final ActionCallback result = new ActionCallback(); requestFocus(toFocus).doWhenProcessed(new Runnable() { @Override public void run() { if (myDisposed) { result.setRejected(); } else { removeDeferred().notifyWhenDone(result); } } }); return result; } else { requestFocus(); return removeDeferred(); } } else { return removeDeferred(); } } private void fireBeforeSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) { if (oldInfo != newInfo) { myOldSelection = oldInfo; try { for (TabsListener eachListener : myTabListeners) { eachListener.beforeSelectionChanged(oldInfo, newInfo); } } finally { myOldSelection = null; } } } private void fireSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) { if (oldInfo != newInfo) { for (TabsListener eachListener : myTabListeners) { if (eachListener != null) { eachListener.selectionChanged(oldInfo, newInfo); } } } } void fireTabsMoved() { for (TabsListener eachListener : myTabListeners) { if (eachListener != null) { eachListener.tabsMoved(); } } } void fireTabRemoved(TabInfo info) { for (TabsListener eachListener : myTabListeners) { if (eachListener != null) { eachListener.tabRemoved(info); } } } @NotNull private ActionCallback requestFocus(final JComponent toFocus) { if (toFocus == null) return new ActionCallback.Done(); if (myTestMode) { toFocus.requestFocus(); return new ActionCallback.Done(); } if (isShowing()) { return myFocusManager.requestFocus(new FocusCommand.ByComponent(toFocus), true); } else { final ActionCallback result = new ActionCallback(); final FocusRequestor requestor = myFocusManager.getFurtherRequestor(); final Ref<Boolean> queued = new Ref<Boolean>(false); Disposer.register(requestor, new Disposable() { @Override public void dispose() { if (!queued.get()) { result.setRejected(); } } }); myDeferredFocusRequest = new Runnable() { @Override public void run() { queued.set(true); requestor.requestFocus(new FocusCommand.ByComponent(toFocus), true).notify(result); } }; return result; } } @NotNull private ActionCallback removeDeferred() { final ActionCallback callback = new ActionCallback(); final long executionRequest = ++myRemoveDeferredRequest; final Runnable onDone = new Runnable() { @Override public void run() { if (myRemoveDeferredRequest == executionRequest) { removeDeferredNow(); } callback.setDone(); } }; myFocusManager.doWhenFocusSettlesDown(onDone); return callback; } private void queueForRemove(Component c) { if (c instanceof JComponent) { addToDeferredRemove(c); } else { remove(c); } } private void unqueueFromRemove(Component c) { myDeferredToRemove.remove(c); } private void removeDeferredNow() { for (Component each : myDeferredToRemove.keySet()) { if (each != null && each.getParent() == this) { remove(each); } } myDeferredToRemove.clear(); } @Override public void propertyChange(final PropertyChangeEvent evt) { final TabInfo tabInfo = (TabInfo)evt.getSource(); if (TabInfo.ACTION_GROUP.equals(evt.getPropertyName())) { updateSideComponent(tabInfo); relayout(false, false); } else if (TabInfo.COMPONENT.equals(evt.getPropertyName())) { relayout(true, false); } else if (TabInfo.TEXT.equals(evt.getPropertyName())) { updateText(tabInfo); } else if (TabInfo.ICON.equals(evt.getPropertyName())) { updateIcon(tabInfo); } else if (TabInfo.TAB_COLOR.equals(evt.getPropertyName())) { updateColor(tabInfo); } else if (TabInfo.ALERT_STATUS.equals(evt.getPropertyName())) { boolean start = ((Boolean)evt.getNewValue()).booleanValue(); updateAttraction(tabInfo, start); } else if (TabInfo.TAB_ACTION_GROUP.equals(evt.getPropertyName())) { updateTabActions(tabInfo); relayout(false, false); } else if (TabInfo.HIDDEN.equals(evt.getPropertyName())) { updateHiding(); relayout(false, false); } else if (TabInfo.ENABLED.equals(evt.getPropertyName())) { updateEnabling(); } } private void updateEnabling() { final List<TabInfo> all = getTabs(); for (TabInfo each : all) { final TabLabel eachLabel = myInfo2Label.get(each); eachLabel.setTabEnabled(each.isEnabled()); } final TabInfo selected = getSelectedInfo(); if (selected != null && !selected.isEnabled()) { final TabInfo toSelect = getToSelectOnRemoveOf(selected); if (toSelect != null) { select(toSelect, myFocusManager.getFocusedDescendantFor(this) != null); } } } private void updateHiding() { boolean update = false; Iterator<TabInfo> visible = myVisibleInfos.iterator(); while (visible.hasNext()) { TabInfo each = visible.next(); if (each.isHidden() && !myHiddenInfos.containsKey(each)) { myHiddenInfos.put(each, myVisibleInfos.indexOf(each)); visible.remove(); update = true; } } Iterator<TabInfo> hidden = myHiddenInfos.keySet().iterator(); while (hidden.hasNext()) { TabInfo each = hidden.next(); if (!each.isHidden() && myHiddenInfos.containsKey(each)) { myVisibleInfos.add(getIndexInVisibleArray(each), each); hidden.remove(); update = true; } } if (update) { resetTabsCache(); if (mySelectedInfo != null && myHiddenInfos.containsKey(mySelectedInfo)) { mySelectedInfo = getToSelectOnRemoveOf(mySelectedInfo); } updateAll(true, false); } } private int getIndexInVisibleArray(TabInfo each) { Integer index = myHiddenInfos.get(each); if (index == null) { index = Integer.valueOf(myVisibleInfos.size()); } if (index > myVisibleInfos.size()) { index = myVisibleInfos.size(); } if (index.intValue() < 0) { index = 0; } return index.intValue(); } private void updateIcon(final TabInfo tabInfo) { updateTab(new Computable<Boolean>() { @Override public Boolean compute() { myInfo2Label.get(tabInfo).setIcon(tabInfo.getIcon()); return true; } }, tabInfo); } private void updateColor(final TabInfo tabInfo) { myInfo2Label.get(tabInfo).setInactiveStateImage(null); updateTab(new Computable<Boolean>() { @Override public Boolean compute() { repaint(); return true; } }, tabInfo); } private void updateTab(Computable<Boolean> update, TabInfo info) { final TabLabel label = myInfo2Label.get(info); Boolean changes = update.compute(); if (label.getRootPane() != null) { if (label.isValid()) { if (changes) { label.repaint(); } } else { revalidateAndRepaint(false); } } } void revalidateAndRepaint(final boolean layoutNow) { if (myVisibleInfos.isEmpty()) { setOpaque(false); final Component nonOpaque = UIUtil.findUltimateParent(this); if (nonOpaque != null && getParent() != null) { final Rectangle toRepaint = SwingUtilities.convertRectangle(getParent(), getBounds(), nonOpaque); nonOpaque.repaint(toRepaint.x, toRepaint.y, toRepaint.width, toRepaint.height); } } else { setOpaque(true); } if (layoutNow) { validate(); } else { revalidate(); } repaint(); } private void updateAttraction(final TabInfo tabInfo, boolean start) { if (start) { myAttractions.add(tabInfo); } else { myAttractions.remove(tabInfo); tabInfo.setBlinkCount(0); } if (start && !myAnimator.isRunning()) { myAnimator.resume(); } else if (!start && myAttractions.isEmpty()) { myAnimator.suspend(); repaintAttractions(); } } private void updateText(final TabInfo tabInfo) { updateTab(new Computable<Boolean>() { @Override public Boolean compute() { final TabLabel label = myInfo2Label.get(tabInfo); label.setText(tabInfo.getColoredText()); label.setToolTipText(tabInfo.getTooltipText()); return true; } }, tabInfo); } private void updateSideComponent(final TabInfo tabInfo) { final Toolbar old = myInfo2Toolbar.get(tabInfo); if (old != null) { remove(old); } final Toolbar toolbar = createToolbarComponent(tabInfo); myInfo2Toolbar.put(tabInfo, toolbar); add(toolbar); } private void updateTabActions(final TabInfo info) { myInfo2Label.get(info).setTabActions(info.getTabLabelActions()); } @Override @Nullable public TabInfo getSelectedInfo() { if (myOldSelection != null) return myOldSelection; if (!myVisibleInfos.contains(mySelectedInfo)) { mySelectedInfo = null; } return mySelectedInfo != null ? mySelectedInfo : !myVisibleInfos.isEmpty() ? myVisibleInfos.get(0) : null; } @Nullable private TabInfo getToSelectOnRemoveOf(TabInfo info) { if (!myVisibleInfos.contains(info)) return null; if (mySelectedInfo != info) return null; if (myVisibleInfos.size() == 1) return null; int index = myVisibleInfos.indexOf(info); TabInfo result = null; if (index > 0) { result = findEnabledBackward(index, false); } if (result == null) { result = findEnabledForward(index, false); } return result; } @Nullable private TabInfo findEnabledForward(int from, boolean cycle) { if (from < 0) return null; int index = from; while (true) { index++; if (index == myVisibleInfos.size()) { if (!cycle) break; index = 0; } if (index == from) break; final TabInfo each = myVisibleInfos.get(index); if (each.isEnabled()) return each; } return null; } @Nullable private TabInfo findEnabledBackward(int from, boolean cycle) { if (from < 0) return null; int index = from; while (true) { index--; if (index == -1) { if (!cycle) break; index = myVisibleInfos.size() - 1; } if (index == from) break; final TabInfo each = myVisibleInfos.get(index); if (each.isEnabled()) return each; } return null; } protected Toolbar createToolbarComponent(final TabInfo tabInfo) { return new Toolbar(this, tabInfo); } @Override @NotNull public TabInfo getTabAt(final int tabIndex) { return getTabs().get(tabIndex); } @NotNull public List<TabInfo> getTabs() { if (myAllTabs != null) return myAllTabs; ArrayList<TabInfo> result = new ArrayList<TabInfo>(); result.addAll(myVisibleInfos); for (TabInfo each : myHiddenInfos.keySet()) { result.add(getIndexInVisibleArray(each), each); } myAllTabs = result; return result; } @Override public TabInfo getTargetInfo() { return myPopupInfo != null ? myPopupInfo : getSelectedInfo(); } @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { resetPopup(); } @Override public void popupMenuCanceled(final PopupMenuEvent e) { resetPopup(); } private void resetPopup() { //todo [kirillk] dirty hack, should rely on ActionManager to understand that menu item was either chosen on or cancelled SwingUtilities.invokeLater(new Runnable() { @Override public void run() { myPopupInfo = null; } }); } @Override public void setPaintBlocked(boolean blocked, final boolean takeSnapshot) { if (blocked && !myPaintBlocked) { if (takeSnapshot) { if (getWidth() > 0 && getHeight() > 0) { myImage = UIUtil.createImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); final Graphics2D g = myImage.createGraphics(); super.paint(g); g.dispose(); } } } myPaintBlocked = blocked; if (!myPaintBlocked) { if (myImage != null) { myImage.flush(); } myImage = null; repaint(); } } private void addToDeferredRemove(final Component c) { if (!myDeferredToRemove.containsKey(c)) { myDeferredToRemove.put(c, c); } } private boolean isToDrawBorderIfTabsHidden() { return myToDrawBorderIfTabsHidden; } @Override @NotNull public JBTabsPresentation setToDrawBorderIfTabsHidden(final boolean toDrawBorderIfTabsHidden) { myToDrawBorderIfTabsHidden = toDrawBorderIfTabsHidden; return this; } @Override @NotNull public JBTabs getJBTabs() { return this; } public static class Toolbar extends JPanel { private final JBTabsImpl myTabs; public Toolbar(JBTabsImpl tabs, TabInfo info) { myTabs = tabs; setLayout(new BorderLayout()); final ActionGroup group = info.getGroup(); final JComponent side = info.getSideComponent(); if (group != null && myTabs.myActionManager != null) { final String place = info.getPlace(); ActionToolbar toolbar = myTabs.myActionManager.createActionToolbar(place != null ? place : ActionPlaces.UNKNOWN, group, myTabs.myHorizontalSide); toolbar.setTargetComponent(info.getActionsContextComponent()); final JComponent actionToolbar = toolbar.getComponent(); add(actionToolbar, BorderLayout.CENTER); } if (side != null) { if (group != null) { add(side, BorderLayout.EAST); } else { add(side, BorderLayout.CENTER); } } } public boolean isEmpty() { return getComponentCount() == 0; } } @Override public void doLayout() { try { myHeaderFitSize = computeHeaderFitSize(); final Collection<TabLabel> labels = myInfo2Label.values(); for (TabLabel each : labels) { each.setTabActionsAutoHide(myTabLabelActionsAutoHide); } List<TabInfo> visible = new ArrayList<TabInfo>(); visible.addAll(myVisibleInfos); if (myDropInfo != null && !visible.contains(myDropInfo) && myShowDropLocation) { if (getDropInfoIndex() >= 0 && getDropInfoIndex() < visible.size()) { visible.add(getDropInfoIndex(), myDropInfo); } else { visible.add(myDropInfo); } } if (isSingleRow()) { myLastLayoutPass = mySingleRowLayout.layoutSingleRow(visible); mySingleRowLayout.scroll(0); myLastLayoutPass = mySingleRowLayout.layoutSingleRow(visible); myTableLayout.myLastTableLayout = null; } else { myLastLayoutPass = myTableLayout.layoutTable(visible); mySingleRowLayout.myLastSingRowLayout = null; } if (isStealthModeEffective() && !isHideTabs()) { final TabLabel label = getSelectedLabel(); final Rectangle bounds = label.getBounds(); final Insets insets = getLayoutInsets(); layout(label, insets.left, bounds.y, getWidth() - insets.right - insets.left, bounds.height); } moveDraggedTabLabel(); myTabActionsAutoHideListener.processMouseOver(); } finally { myForcedRelayout = false; } applyResetComponents(); } void moveDraggedTabLabel() { if (myDragHelper != null && myDragHelper.myDragRec != null) { final TabLabel selectedLabel = myInfo2Label.get(getSelectedInfo()); if (selectedLabel != null) { final Rectangle bounds = selectedLabel.getBounds(); if (isHorizontalTabs()) { selectedLabel.setBounds(myDragHelper.myDragRec.x, bounds.y, bounds.width, bounds.height); } else { selectedLabel.setBounds(bounds.x, myDragHelper.myDragRec.y, bounds.width, bounds.height); } } } } private Dimension computeHeaderFitSize() { final Max max = computeMaxSize(); if (myPosition == JBTabsPosition.top || myPosition == JBTabsPosition.bottom) { return new Dimension(getSize().width, myHorizontalSide ? Math.max(max.myLabel.height, max.myToolbar.height) : max.myLabel.height); } else { return new Dimension(max.myLabel.width + (myHorizontalSide ? 0 : max.myToolbar.width), getSize().height); } } public Rectangle layoutComp(int componentX, int componentY, final JComponent comp, int deltaWidth, int deltaHeight) { final Insets insets = getLayoutInsets(); final Insets border = isHideTabs() ? new Insets(0, 0, 0, 0) : myBorder.getEffectiveBorder(); final boolean noTabsVisible = isStealthModeEffective() || isHideTabs(); if (noTabsVisible) { border.top = getBorder(-1); border.bottom = getBorder(-1); border.left = getBorder(-1); border.right = getBorder(-1); } final Insets inner = getInnerInsets(); border.top += inner.top; border.bottom += inner.bottom; border.left += inner.left; border.right += inner.right; int x = insets.left + componentX + border.left; int y = insets.top + componentY + border.top; int width = getWidth() - insets.left - insets.right - componentX - border.left - border.right; int height = getHeight() - insets.top - insets.bottom - componentY - border.top - border.bottom; if (!noTabsVisible) { width += deltaWidth; height += deltaHeight; } return layout(comp, x, y, width, height); } @Override public JBTabsPresentation setInnerInsets(final Insets innerInsets) { myInnerInsets = innerInsets; return this; } private Insets getInnerInsets() { return myInnerInsets; } public Insets getLayoutInsets() { Insets insets = getInsets(); if (insets == null) { insets = new Insets(0, 0, 0, 0); } return insets; } public int getToolbarInset() { return getArcSize() + 1; } public void resetLayout(boolean resetLabels) { if (resetLabels) { mySingleRowLayout.myLeftGhost.reset(); mySingleRowLayout.myRightGhost.reset(); } for (TabInfo each : myVisibleInfos) { reset(each, resetLabels); } if (myDropInfo != null) { reset(myDropInfo, resetLabels); } for (TabInfo each : myHiddenInfos.keySet()) { reset(each, resetLabels); } for (Component eachDeferred : myDeferredToRemove.keySet()) { resetLayout((JComponent)eachDeferred); } } private void reset(final TabInfo each, final boolean resetLabels) { final JComponent c = each.getComponent(); if (c != null) { resetLayout(c); } resetLayout(myInfo2Toolbar.get(each)); if (resetLabels) { resetLayout(myInfo2Label.get(each)); } } private static int getArcSize() { return 4; } private static int getEdgeArcSize() { return 3; } public static int getGhostTabLength() { return 15; } protected JBTabsPosition getPosition() { return myPosition; } protected void doPaintBackground(Graphics2D g2d, Rectangle clip) { g2d.setColor(getBackground()); g2d.fill(clip); } @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); if (myVisibleInfos.isEmpty()) return; Graphics2D g2d = (Graphics2D)g; final GraphicsConfig config = new GraphicsConfig(g2d); config.setAntialiasing(true); final Rectangle clip = g2d.getClipBounds(); doPaintBackground(g2d, clip); final TabInfo selected = getSelectedInfo(); if (selected != null) { Rectangle compBounds = selected.getComponent().getBounds(); if (compBounds.contains(clip) && !compBounds.intersects(clip)) return; } boolean leftGhostExists = isSingleRow(); boolean rightGhostExists = isSingleRow(); if (!isStealthModeEffective() && !isHideTabs()) { if (isSingleRow() && mySingleRowLayout.myLastSingRowLayout.lastGhostVisible) { paintLastGhost(g2d); } paintNonSelectedTabs(g2d, leftGhostExists, rightGhostExists); if (isSingleRow() && mySingleRowLayout.myLastSingRowLayout.firstGhostVisible) { paintFirstGhost(g2d); } } config.setAntialiasing(false); if (isSideComponentVertical()) { Toolbar toolbarComp = myInfo2Toolbar.get(mySelectedInfo); if (toolbarComp != null && !toolbarComp.isEmpty()) { Rectangle toolBounds = toolbarComp.getBounds(); g2d.setColor(CaptionPanel.CNT_ACTIVE_BORDER_COLOR); g2d.drawLine((int)toolBounds.getMaxX(), toolBounds.y, (int)toolBounds.getMaxX(), (int)toolBounds.getMaxY() - 1); } } else if (!isSideComponentOnTabs()) { Toolbar toolbarComp = myInfo2Toolbar.get(mySelectedInfo); if (toolbarComp != null && !toolbarComp.isEmpty()) { Rectangle toolBounds = toolbarComp.getBounds(); g2d.setColor(CaptionPanel.CNT_ACTIVE_BORDER_COLOR); g2d.drawLine(toolBounds.x, (int)toolBounds.getMaxY(), (int)toolBounds.getMaxX() - 1, (int)toolBounds.getMaxY()); } } config.restore(); } @Nullable protected Color getActiveTabColor(@Nullable final Color c) { final TabInfo info = getSelectedInfo(); if (info == null) { return c; } final Color tabColor = info.getTabColor(); return tabColor == null ? c : tabColor; } protected void paintSelectionAndBorder(Graphics2D g2d) { if (mySelectedInfo == null) return; final ShapeInfo shapeInfo = computeSelectedLabelShape(); if (!isHideTabs()) { g2d.setColor(getBackground()); g2d.fill(shapeInfo.fillPath.getShape()); } final int alpha; int paintTopY = shapeInfo.labelTopY; int paintBottomY = shapeInfo.labelBottomY; final boolean paintFocused = myPaintFocus && (myFocused || myActivePopup != null || myAlwaysPaintSelectedTab); Color bgPreFill = null; if (paintFocused) { final Color bgColor = getActiveTabColor(getActiveTabFillIn()); if (bgColor == null) { shapeInfo.from = getFocusedTopFillColor(); shapeInfo.to = getFocusedBottomFillColor(); } else { bgPreFill = bgColor; alpha = 255; paintBottomY = shapeInfo.labelTopY + shapeInfo.labelPath.deltaY(getArcSize() - 2); shapeInfo.from = ColorUtil.toAlpha(UIUtil.getFocusedFillColor(), alpha); shapeInfo.to = ColorUtil.toAlpha(getActiveTabFillIn(), alpha); } } else { final Color bgColor = getActiveTabColor(getActiveTabFillIn()); if (isPaintFocus()) { if (bgColor == null) { alpha = 150; shapeInfo.from = ColorUtil.toAlpha(UIUtil.getPanelBackground().brighter(), alpha); shapeInfo.to = ColorUtil.toAlpha(UIUtil.getPanelBackground(), alpha); } else { alpha = 255; shapeInfo.from = ColorUtil.toAlpha(bgColor, alpha); shapeInfo.to = ColorUtil.toAlpha(bgColor, alpha); } } else { alpha = 255; final Color tabColor = getActiveTabColor(null); final Color defaultBg = UIUtil.isUnderDarcula() ? UIUtil.getControlColor() : Color.white; shapeInfo.from = tabColor == null ? defaultBg : tabColor; shapeInfo.to = tabColor == null ? defaultBg : tabColor; } } if (!isHideTabs()) { if (bgPreFill != null) { g2d.setColor(bgPreFill); g2d.fill(shapeInfo.fillPath.getShape()); } final Line2D.Float gradientLine = shapeInfo.fillPath.transformLine(shapeInfo.fillPath.getX(), paintTopY, shapeInfo.fillPath.getX(), paintBottomY); g2d.setPaint(UIUtil.getGradientPaint((float)gradientLine.getX1(), (float)gradientLine.getY1(), shapeInfo.fillPath.transformY1(shapeInfo.from, shapeInfo.to), (float)gradientLine.getX2(), (float)gradientLine.getY2(), shapeInfo.fillPath.transformY1(shapeInfo.to, shapeInfo.from))); g2d.fill(shapeInfo.fillPath.getShape()); } final Color tabColor = getActiveTabColor(null); Color borderColor = tabColor == null ? UIUtil.getBoundsColor(paintFocused) : tabColor.darker(); g2d.setColor(borderColor); if (!isHideTabs()) { g2d.draw(shapeInfo.path.getShape()); } paintBorder(g2d, shapeInfo, borderColor); } protected Color getFocusedTopFillColor() { return UIUtil.getFocusedFillColor(); } protected Color getFocusedBottomFillColor() { return UIUtil.getFocusedFillColor(); } protected ShapeInfo computeSelectedLabelShape() { final ShapeInfo shape = new ShapeInfo(); shape.path = getEffectiveLayout().createShapeTransform(getSize()); shape.insets = shape.path.transformInsets(getLayoutInsets()); shape.labelPath = shape.path.createTransform(getSelectedLabel().getBounds()); shape.labelBottomY = shape.labelPath.getMaxY() + shape.labelPath.deltaY(1); shape.labelTopY = shape.labelPath.getY(); shape.labelLeftX = shape.labelPath.getX(); shape.labelRightX = shape.labelPath.getX() + shape.labelPath.deltaX(shape.labelPath.getWidth()); Insets border = myBorder.getEffectiveBorder(); TabInfo selected = getSelectedInfo(); boolean first = myLastLayoutPass.getPreviousFor(selected) == null; boolean last = myLastLayoutPass.getNextFor(selected) == null; boolean leftEdge = !isSingleRow() && first && border.left == 0; boolean rightEdge = !isSingleRow() && last && Boolean.TRUE.equals(myInfo2Label.get(selected).getClientProperty(STRETCHED_BY_WIDTH)) && border.right == 0; boolean isDraggedNow = selected != null && myDragHelper != null && selected.equals(myDragHelper.getDragSource()); if (leftEdge && !isDraggedNow) { shape.path.moveTo(shape.insets.left, shape.labelTopY + shape.labelPath.deltaY(getEdgeArcSize())); shape.path.quadTo(shape.labelLeftX, shape.labelTopY, shape.labelLeftX + shape.labelPath.deltaX(getEdgeArcSize()), shape.labelTopY); shape.path.lineTo(shape.labelRightX - shape.labelPath.deltaX(getArcSize()), shape.labelTopY); } else { shape.path.moveTo(shape.insets.left, shape.labelBottomY); shape.path.lineTo(shape.labelLeftX, shape.labelBottomY); shape.path.lineTo(shape.labelLeftX, shape.labelTopY + shape.labelPath.deltaY(getArcSize())); shape.path.quadTo(shape.labelLeftX, shape.labelTopY, shape.labelLeftX + shape.labelPath.deltaX(getArcSize()), shape.labelTopY); } int lastX = shape.path.getWidth() - shape.path.deltaX(shape.insets.right + 1); if (isStealthModeEffective()) { shape.path.lineTo(lastX - shape.path.deltaX(getArcSize()), shape.labelTopY); shape.path.quadTo(lastX, shape.labelTopY, lastX, shape.labelTopY + shape.path.deltaY(getArcSize())); shape.path.lineTo(lastX, shape.labelBottomY); } else { if (rightEdge) { shape.path.lineTo(shape.labelRightX + 1 - shape.path.deltaX(getArcSize()), shape.labelTopY); shape.path.quadTo(shape.labelRightX + 1, shape.labelTopY, shape.labelRightX + 1, shape.labelTopY + shape.path.deltaY(getArcSize())); } else { shape.path.lineTo(shape.labelRightX - shape.path.deltaX(getArcSize()), shape.labelTopY); shape.path.quadTo(shape.labelRightX, shape.labelTopY, shape.labelRightX, shape.labelTopY + shape.path.deltaY(getArcSize())); } if (myLastLayoutPass.hasCurveSpaceFor(selected)) { shape.path.lineTo(shape.labelRightX, shape.labelBottomY - shape.path.deltaY(getArcSize())); shape.path.quadTo(shape.labelRightX, shape.labelBottomY, shape.labelRightX + shape.path.deltaX(getArcSize()), shape.labelBottomY); } else { if (rightEdge) { shape.path.lineTo(shape.labelRightX + 1, shape.labelBottomY); } else { shape.path.lineTo(shape.labelRightX, shape.labelBottomY); } } } if (!rightEdge) { shape.path.lineTo(lastX, shape.labelBottomY); } if (isStealthModeEffective()) { shape.path.closePath(); } shape.fillPath = shape.path.copy(); if (!isHideTabs()) { shape.fillPath.lineTo(lastX, shape.labelBottomY + shape.fillPath.deltaY(1)); shape.fillPath.lineTo(shape.labelLeftX, shape.labelBottomY + shape.fillPath.deltaY(1)); shape.fillPath.closePath(); } return shape; } protected TabLabel getSelectedLabel() { return myInfo2Label.get(getSelectedInfo()); } protected static class ShapeInfo { public ShapeInfo() {} public ShapeTransform path; public ShapeTransform fillPath; public ShapeTransform labelPath; public int labelBottomY; public int labelTopY; public int labelLeftX; public int labelRightX; public Insets insets; public Color from; public Color to; } protected void paintFirstGhost(Graphics2D g2d) { final ShapeTransform path = getEffectiveLayout().createShapeTransform(mySingleRowLayout.myLastSingRowLayout.firstGhost); int topX = path.getX() + path.deltaX(getCurveArc()); int topY = path.getY() + path.deltaY(getSelectionTabVShift()); int bottomX = path.getMaxX() + path.deltaX(1); int bottomY = path.getMaxY() + path.deltaY(1); path.moveTo(topX, topY); final boolean isLeftFromSelection = mySingleRowLayout.myLastSingRowLayout.toLayout.indexOf(getSelectedInfo()) == 0; if (isLeftFromSelection) { path.lineTo(bottomX, topY); } else { path.lineTo(bottomX - getArcSize(), topY); path.quadTo(bottomX, topY, bottomX, topY + path.deltaY(getArcSize())); } path.lineTo(bottomX, bottomY); path.lineTo(topX, bottomY); path.quadTo(topX - path.deltaX(getCurveArc() * 2 - 1), bottomY - path.deltaY(Math.abs(bottomY - topY) / 4), topX, bottomY - path.deltaY(Math.abs(bottomY - topY) / 2)); path.quadTo(topX + path.deltaX(getCurveArc() - 1), topY + path.deltaY(Math.abs(bottomY - topY) / 4), topX, topY); path.closePath(); g2d.setColor(getBackground()); g2d.fill(path.getShape()); g2d.setColor(getBoundsColor()); g2d.draw(path.getShape()); g2d.setColor(getTopBlockColor()); g2d.drawLine(topX + path.deltaX(1), topY + path.deltaY(1), bottomX - path.deltaX(getArcSize()), topY + path.deltaY(1)); g2d.setColor(getRightBlockColor()); g2d.drawLine(bottomX - path.deltaX(1), topY + path.deltaY(getArcSize()), bottomX - path.deltaX(1), bottomY - path.deltaY(1)); } protected void paintLastGhost(Graphics2D g2d) { final ShapeTransform path = getEffectiveLayout().createShapeTransform(mySingleRowLayout.myLastSingRowLayout.lastGhost); int topX = path.getX() - path.deltaX(getArcSize()); int topY = path.getY() + path.deltaY(getSelectionTabVShift()); int bottomX = path.getMaxX() - path.deltaX(getCurveArc()); int bottomY = path.getMaxY() + path.deltaY(1); path.moveTo(topX, topY); path.lineTo(bottomX, topY); path.quadTo(bottomX - getCurveArc(), topY + (bottomY - topY) / 4, bottomX, topY + (bottomY - topY) / 2); path.quadTo(bottomX + getCurveArc(), bottomY - (bottomY - topY) / 4, bottomX, bottomY); path.lineTo(topX, bottomY); path.closePath(); g2d.setColor(getBackground()); g2d.fill(path.getShape()); g2d.setColor(getBoundsColor()); g2d.draw(path.getShape()); g2d.setColor(getTopBlockColor()); g2d.drawLine(topX, topY + path.deltaY(1), bottomX - path.deltaX(getCurveArc()), topY + path.deltaY(1)); } private static int getCurveArc() { return 2; } private static Color getBoundsColor() { return new JBColor(Color.gray, Gray._0.withAlpha(80)); } private static Color getRightBlockColor() { return new JBColor(Color.lightGray, Gray._0.withAlpha(0)); } private static Color getTopBlockColor() { return new JBColor(Color.white, Gray._0.withAlpha(0)); } private void paintNonSelectedTabs(final Graphics2D g2d, final boolean leftGhostExists, final boolean rightGhostExists) { TabInfo selected = getSelectedInfo(); if (myLastPaintedSelection == null || !myLastPaintedSelection.equals(selected)) { List<TabInfo> tabs = getTabs(); for (TabInfo each : tabs) { myInfo2Label.get(each).setInactiveStateImage(null); } } for (int eachRow = 0; eachRow < myLastLayoutPass.getRowCount(); eachRow++) { for (int eachColumn = myLastLayoutPass.getColumnCount(eachRow) - 1; eachColumn >= 0; eachColumn--) { final TabInfo each = myLastLayoutPass.getTabAt(eachRow, eachColumn); if (getSelectedInfo() == each) { continue; } paintNonSelected(g2d, each, leftGhostExists, rightGhostExists, eachRow, eachColumn); } } myLastPaintedSelection = selected; } private void paintNonSelected(final Graphics2D g2d, final TabInfo each, final boolean leftGhostExists, final boolean rightGhostExists, int row, int column) { if (myDropInfo == each) return; final TabLabel label = myInfo2Label.get(each); if (label.getBounds().width == 0) return; int imageInsets = getArcSize() + 1; Rectangle bounds = label.getBounds(); int x = bounds.x - imageInsets; int y = bounds.y; int width = bounds.width + imageInsets * 2 + 1; int height = bounds.height + getArcSize() + 1; if (isToBufferPainting()) { BufferedImage img = label.getInactiveStateImage(bounds); if (img == null) { img = UIUtil.createImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D imgG2d = img.createGraphics(); imgG2d.addRenderingHints(g2d.getRenderingHints()); doPaintInactive(imgG2d, leftGhostExists, label, new Rectangle(imageInsets, 0, label.getWidth(), label.getHeight()), rightGhostExists, row, column); imgG2d.dispose(); } g2d.drawImage(img, x, y, width, height, null); label.setInactiveStateImage(img); } else { doPaintInactive(g2d, leftGhostExists, label, label.getBounds(), rightGhostExists, row, column); label.setInactiveStateImage(null); } } private boolean isToBufferPainting() { return Registry.is("ide.tabbedPane.bufferedPaint") && myUseBufferedPaint; } protected List<TabInfo> getVisibleInfos() { return myVisibleInfos; } protected LayoutPassInfo getLastLayoutPass() { return myLastLayoutPass; } @Override public Color getBackground() { return UIUtil.isUnderNimbusLookAndFeel() ? UIUtil.getPanelBackground() : super.getBackground(); } protected void doPaintInactive(Graphics2D g2d, boolean leftGhostExists, TabLabel label, Rectangle effectiveBounds, boolean rightGhostExists, int row, int column) { int tabIndex = myVisibleInfos.indexOf(label.getInfo()); final int arc = getArcSize(); Color topBlockColor = getTopBlockColor(); Color rightBlockColor = getRightBlockColor(); Color boundsColor = getBoundsColor(); Color backgroundColor = getBackground(); final Color tabColor = label.getInfo().getTabColor(); if (tabColor != null) { backgroundColor = tabColor; boundsColor = tabColor.darker(); topBlockColor = tabColor.brighter().brighter(); rightBlockColor = tabColor; } final TabInfo selected = getSelectedInfo(); final int selectionTabVShift = getSelectionTabVShift(); final TabInfo prev = myLastLayoutPass.getPreviousFor(myVisibleInfos.get(tabIndex)); final TabInfo next = myLastLayoutPass.getNextFor(myVisibleInfos.get(tabIndex)); boolean firstShowing = prev == null; if (!firstShowing && !leftGhostExists) { firstShowing = myInfo2Label.get(prev).getBounds().width == 0; } boolean lastShowing = next == null; if (!lastShowing) { lastShowing = myInfo2Label.get(next).getBounds().width == 0; } boolean leftFromSelection = selected != null && tabIndex == myVisibleInfos.indexOf(selected) - 1; final ShapeTransform shape = getEffectiveLayout().createShapeTransform(effectiveBounds); int leftX = firstShowing ? shape.getX() : shape.getX() - shape.deltaX(arc + 1); int topY = shape.getY() + shape.deltaY(selectionTabVShift); int rightX = !lastShowing && leftFromSelection ? shape.getMaxX() + shape.deltaX(arc + 1) : shape.getMaxX(); int bottomY = shape.getMaxY() + shape.deltaY(1); Insets border = myBorder.getEffectiveBorder(); if (border.left > 0 || leftGhostExists || !firstShowing) { shape.moveTo(leftX, bottomY); shape.lineTo(leftX, topY + shape.deltaY(arc)); shape.quadTo(leftX, topY, leftX + shape.deltaX(arc), topY); } else { if (firstShowing) { shape.moveTo(leftX, topY + shape.deltaY(getEdgeArcSize())); shape.quadTo(leftX, topY, leftX + shape.deltaX(getEdgeArcSize()), topY); } } boolean rightEdge = false; if (border.right > 0 || rightGhostExists || !lastShowing || !Boolean.TRUE.equals(label.getClientProperty(STRETCHED_BY_WIDTH))) { shape.lineTo(rightX - shape.deltaX(arc), topY); shape.quadTo(rightX, topY, rightX, topY + shape.deltaY(arc)); shape.lineTo(rightX, bottomY); } else { if (lastShowing) { shape.lineTo(rightX - shape.deltaX(arc), topY); shape.quadTo(rightX + 1, topY, rightX + 1, topY + shape.deltaY(arc)); shape.lineTo(rightX + 1, bottomY); rightEdge = true; } } if (!isSingleRow()) { final TablePassInfo info = myTableLayout.myLastTableLayout; if (!info.isInSelectionRow(label.getInfo())) { shape.lineTo(rightX, bottomY + shape.deltaY(getArcSize())); shape.lineTo(leftX, bottomY + shape.deltaY(getArcSize())); shape.lineTo(leftX, bottomY); } } if (!rightEdge) { shape.lineTo(leftX, bottomY); } g2d.setColor(backgroundColor); g2d.fill(shape.getShape()); // TODO final Line2D.Float gradientLine = shape.transformLine(0, topY, 0, topY + shape.deltaY((int)(shape.getHeight() / 1.5))); final Paint gp = UIUtil.isUnderDarcula() ? UIUtil.getGradientPaint(gradientLine.x1, gradientLine.y1, shape.transformY1(backgroundColor, backgroundColor), gradientLine.x2, gradientLine.y2, shape.transformY1(backgroundColor, backgroundColor)) : UIUtil.getGradientPaint(gradientLine.x1, gradientLine.y1, shape.transformY1(backgroundColor.brighter().brighter(), backgroundColor), gradientLine.x2, gradientLine.y2, shape.transformY1(backgroundColor, backgroundColor.brighter().brighter())); final Paint old = g2d.getPaint(); g2d.setPaint(gp); g2d.fill(shape.getShape()); g2d.setPaint(old); g2d.setColor(topBlockColor); g2d.draw( shape.transformLine(leftX + shape.deltaX(arc + 1), topY + shape.deltaY(1), rightX - shape.deltaX(arc - 1), topY + shape.deltaY(1))); if (!rightEdge) { g2d.setColor(rightBlockColor); g2d.draw(shape.transformLine(rightX - shape.deltaX(1), topY + shape.deltaY(arc - 1), rightX - shape.deltaX(1), bottomY)); } g2d.setColor(boundsColor); g2d.draw(shape.getShape()); } public static int getSelectionTabVShift() { return 2; } protected void paintBorder(Graphics2D g2d, ShapeInfo shape, final Color borderColor) { final ShapeTransform shaper = shape.path.copy().reset(); final Insets paintBorder = shape.path.transformInsets(myBorder.getEffectiveBorder()); int topY = shape.labelPath.getMaxY() + shape.labelPath.deltaY(1); int bottomY = topY + paintBorder.top - 2; int middleY = topY + (bottomY - topY) / 2; final int boundsX = shape.path.getX() + shape.path.deltaX(shape.insets.left); final int boundsY = isHideTabs() ? shape.path.getY() + shape.path.deltaY(shape.insets.top) : shape.labelPath.getMaxY() + shape.path.deltaY(1); final int boundsHeight = Math.abs(shape.path.getMaxY() - boundsY) - shape.insets.bottom - paintBorder.bottom; final int boundsWidth = Math.abs(shape.path.getMaxX() - (shape.insets.left + shape.insets.right)); if (paintBorder.top > 0) { if (isHideTabs()) { if (isToDrawBorderIfTabsHidden()) { g2d.setColor(borderColor); g2d.fill(shaper.reset().doRect(boundsX, boundsY, boundsWidth, 1).getShape()); } } else { Color tabFillColor = getActiveTabColor(null); if (tabFillColor == null) { tabFillColor = shape.path.transformY1(shape.to, shape.from); } g2d.setColor(tabFillColor); g2d.fill(shaper.reset().doRect(boundsX, topY + shape.path.deltaY(1), boundsWidth, paintBorder.top - 1).getShape()); g2d.setColor(borderColor); if (paintBorder.top == 2) { final Line2D.Float line = shape.path.transformLine(boundsX, topY, boundsX + shape.path.deltaX(boundsWidth - 1), topY); g2d.drawLine((int)line.x1, (int)line.y1, (int)line.x2, (int)line.y2); } else if (paintBorder.top > 2) { //todo kirillk //start hack int deltaY = 0; if (myPosition == JBTabsPosition.bottom || myPosition == JBTabsPosition.right) { deltaY = 1; } //end hack final int topLine = topY + shape.path.deltaY(paintBorder.top - 1); g2d.fill(shaper.reset().doRect(boundsX, topLine + deltaY, boundsWidth - 1, 1).getShape()); } } } g2d.setColor(borderColor); //bottom g2d.fill(shaper.reset().doRect(boundsX, Math.abs(shape.path.getMaxY() - shape.insets.bottom - paintBorder.bottom), boundsWidth, paintBorder.bottom).getShape()); //left g2d.fill(shaper.reset().doRect(boundsX, boundsY, paintBorder.left, boundsHeight).getShape()); //right g2d.fill(shaper.reset() .doRect(shape.path.getMaxX() - shape.insets.right - paintBorder.right, boundsY, paintBorder.right, boundsHeight).getShape()); } protected boolean isStealthModeEffective() { return myStealthTabMode && getTabCount() == 1 && (isSideComponentVertical() || !isSideComponentOnTabs()) && getTabsPosition() == JBTabsPosition.top; } private boolean isNavigationVisible() { if (myStealthTabMode && getTabCount() == 1) return false; return !myVisibleInfos.isEmpty(); } @Override public void paint(final Graphics g) { Rectangle clip = g.getClipBounds(); if (clip == null) { return; } if (myPaintBlocked) { if (myImage != null) { g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null); } return; } super.paint(g); } @Override protected void paintChildren(final Graphics g) { super.paintChildren(g); final GraphicsConfig config = new GraphicsConfig(g); config.setAntialiasing(true); paintSelectionAndBorder((Graphics2D)g); config.restore(); final TabLabel selected = getSelectedLabel(); if (selected != null) { selected.paintImage(g); } mySingleRowLayout.myMoreIcon.paintIcon(this, g); } private Max computeMaxSize() { Max max = new Max(); for (TabInfo eachInfo : myVisibleInfos) { final TabLabel label = myInfo2Label.get(eachInfo); max.myLabel.height = Math.max(max.myLabel.height, label.getPreferredSize().height); max.myLabel.width = Math.max(max.myLabel.width, label.getPreferredSize().width); final Toolbar toolbar = myInfo2Toolbar.get(eachInfo); if (myLayout.isSideComponentOnTabs() && toolbar != null && !toolbar.isEmpty()) { max.myToolbar.height = Math.max(max.myToolbar.height, toolbar.getPreferredSize().height); max.myToolbar.width = Math.max(max.myToolbar.width, toolbar.getPreferredSize().width); } } max.myToolbar.height++; return max; } @Override public Dimension getMinimumSize() { return computeSize(new Function<JComponent, Dimension>() { @Override public Dimension fun(JComponent component) { return component.getMinimumSize(); } }, 1); } @Override public Dimension getPreferredSize() { return computeSize(new Function<JComponent, Dimension>() { @Override public Dimension fun(JComponent component) { return component.getPreferredSize(); } }, 3); } private Dimension computeSize(Function<JComponent, Dimension> transform, int tabCount) { Dimension size = new Dimension(); for (TabInfo each : myVisibleInfos) { final JComponent c = each.getComponent(); if (c != null) { final Dimension eachSize = transform.fun(c); size.width = Math.max(eachSize.width, size.width); size.height = Math.max(eachSize.height, size.height); } } addHeaderSize(size, tabCount); return size; } private void addHeaderSize(Dimension size, final int tabsCount) { Dimension header = computeHeaderPreferredSize(tabsCount); final boolean horizontal = getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom; if (horizontal) { size.height += header.height; size.width = Math.max(size.width, header.width); } else { size.height += Math.max(size.height, header.height); size.width += header.width; } final Insets insets = getLayoutInsets(); size.width += insets.left + insets.right + 1; size.height += insets.top + insets.bottom + 1; } private Dimension computeHeaderPreferredSize(int tabsCount) { final Iterator<TabInfo> infos = myInfo2Label.keySet().iterator(); Dimension size = new Dimension(); int currentTab = 0; final boolean horizontal = getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom; while (infos.hasNext()) { final boolean canGrow = currentTab < tabsCount; TabInfo eachInfo = infos.next(); final TabLabel eachLabel = myInfo2Label.get(eachInfo); final Dimension eachPrefSize = eachLabel.getPreferredSize(); if (horizontal) { if (canGrow) { size.width += eachPrefSize.width; } size.height = Math.max(size.height, eachPrefSize.height); } else { size.width = Math.max(size.width, eachPrefSize.width); if (canGrow) { size.height += eachPrefSize.height; } } currentTab++; } if (isSingleRow() && isGhostsAlwaysVisible()) { if (horizontal) { size.width += getGhostTabLength() * 2; } else { size.height += getGhostTabLength() * 2; } } if (horizontal) { size.height += myBorder.getTabBorderSize(); } else { size.width += myBorder.getTabBorderSize(); } return size; } @Override public int getTabCount() { return getTabs().size(); } @Override @NotNull public JBTabsPresentation getPresentation() { return this; } @Override @NotNull public ActionCallback removeTab(final TabInfo info) { return removeTab(info, null, true); } @NotNull public ActionCallback removeTab(final TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus) { return removeTab(info, forcedSelectionTransfer, transferFocus, false); } @NotNull private ActionCallback removeTab(TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus, boolean isDropTarget) { if (!isDropTarget) { if (info == null || !getTabs().contains(info)) return new ActionCallback.Done(); } if (isDropTarget && myLastLayoutPass != null) { myLastLayoutPass.myVisibleInfos.remove(info); } final ActionCallback result = new ActionCallback(); TabInfo toSelect; if (forcedSelectionTransfer == null) { toSelect = getToSelectOnRemoveOf(info); } else { assert myVisibleInfos.contains(forcedSelectionTransfer) : "Cannot find tab for selection transfer, tab=" + forcedSelectionTransfer; toSelect = forcedSelectionTransfer; } if (toSelect != null) { boolean clearSelection = info.equals(mySelectedInfo); processRemove(info, false); if (clearSelection) { mySelectedInfo = info; } _setSelected(toSelect, transferFocus).doWhenProcessed(new Runnable() { @Override public void run() { removeDeferred().notifyWhenDone(result); } }); } else { processRemove(info, true); removeDeferred().notifyWhenDone(result); } if (myVisibleInfos.isEmpty()) { removeDeferredNow(); } revalidateAndRepaint(true); fireTabRemoved(info); return result; } private void processRemove(final TabInfo info, boolean forcedNow) { remove(myInfo2Label.get(info)); remove(myInfo2Toolbar.get(info)); JComponent tabComponent = info.getComponent(); if (!isToDeferRemoveForLater(tabComponent) || forcedNow) { remove(tabComponent); } else { queueForRemove(tabComponent); } myVisibleInfos.remove(info); myHiddenInfos.remove(info); myInfo2Label.remove(info); myInfo2Toolbar.remove(info); resetTabsCache(); updateAll(false, false); // avoid leaks myLastPaintedSelection = null; } @Nullable public TabInfo findInfo(Component component) { for (TabInfo each : getTabs()) { if (each.getComponent() == component) return each; } return null; } @Override public TabInfo findInfo(MouseEvent event) { return findInfo(event, false); } @Nullable private TabInfo findInfo(final MouseEvent event, final boolean labelsOnly) { final Point point = SwingUtilities.convertPoint(event.getComponent(), event.getPoint(), this); return _findInfo(point, labelsOnly); } @Override public TabInfo findInfo(final Object object) { for (int i = 0; i < getTabCount(); i++) { final TabInfo each = getTabAt(i); final Object eachObject = each.getObject(); if (eachObject != null && eachObject.equals(object)) return each; } return null; } @Nullable private TabInfo _findInfo(final Point point, boolean labelsOnly) { Component component = findComponentAt(point); if (component == null) return null; while (component != this || component != null) { if (component instanceof TabLabel) { return ((TabLabel)component).getInfo(); } if (!labelsOnly) { final TabInfo info = findInfo(component); if (info != null) return info; } if (component == null) break; component = component.getParent(); } return null; } @Override public void removeAllTabs() { for (TabInfo each : getTabs()) { removeTab(each); } } private static class Max { final Dimension myLabel = new Dimension(); final Dimension myToolbar = new Dimension(); } private void updateContainer(boolean forced, final boolean layoutNow) { for (TabInfo each : new ArrayList<TabInfo>(myVisibleInfos)) { final JComponent eachComponent = each.getComponent(); if (getSelectedInfo() == each && getSelectedInfo() != null) { unqueueFromRemove(eachComponent); final Container parent = eachComponent.getParent(); if (parent != null && parent != this) { parent.remove(eachComponent); } if (eachComponent.getParent() == null) { add(eachComponent); } } else { if (eachComponent.getParent() == null) continue; if (isToDeferRemoveForLater(eachComponent)) { queueForRemove(eachComponent); } else { remove(eachComponent); } } } mySingleRowLayout.scrollSelectionInView(); relayout(forced, layoutNow); } @Override protected void addImpl(final Component comp, final Object constraints, final int index) { unqueueFromRemove(comp); if (comp instanceof TabLabel) { ((TabLabel)comp).apply(myUiDecorator.getDecoration()); } super.addImpl(comp, constraints, index); } private static boolean isToDeferRemoveForLater(JComponent c) { return c.getRootPane() != null; } void relayout(boolean forced, final boolean layoutNow) { if (!myForcedRelayout) { myForcedRelayout = forced; } revalidateAndRepaint(layoutNow); } public TabsBorder getTabsBorder() { return myBorder; } @Override @NotNull public JBTabs addTabMouseListener(@NotNull MouseListener listener) { removeListeners(); myTabMouseListeners.add(listener); addListeners(); return this; } @Override @NotNull public JComponent getComponent() { return this; } @Override public boolean isCycleRoot() { return false; } private void addListeners() { for (TabInfo eachInfo : myVisibleInfos) { final TabLabel label = myInfo2Label.get(eachInfo); for (EventListener eachListener : myTabMouseListeners) { if (eachListener instanceof MouseListener) { label.addMouseListener((MouseListener)eachListener); } else if (eachListener instanceof MouseMotionListener) { label.addMouseMotionListener((MouseMotionListener)eachListener); } else { assert false; } } } } private void removeListeners() { for (TabInfo eachInfo : myVisibleInfos) { final TabLabel label = myInfo2Label.get(eachInfo); for (EventListener eachListener : myTabMouseListeners) { if (eachListener instanceof MouseListener) { label.removeMouseListener((MouseListener)eachListener); } else if (eachListener instanceof MouseMotionListener) { label.removeMouseMotionListener((MouseMotionListener)eachListener); } else { assert false; } } } } private void updateListeners() { removeListeners(); addListeners(); } @Override public JBTabs addListener(@NotNull TabsListener listener) { myTabListeners.add(listener); return this; } @Override public JBTabs setSelectionChangeHandler(SelectionChangeHandler handler) { mySelectionChangeHandler = handler; return this; } public void setFocused(final boolean focused) { if (myFocused == focused) return; myFocused = focused; if (myPaintFocus) { repaint(); } } @Override public int getIndexOf(@Nullable final TabInfo tabInfo) { return myVisibleInfos.indexOf(tabInfo); } @Override public boolean isHideTabs() { return myHideTabs; } @Override public void setHideTabs(final boolean hideTabs) { if (isHideTabs() == hideTabs) return; myHideTabs = hideTabs; relayout(true, false); } @Override public JBTabsPresentation setPaintBorder(int top, int left, int right, int bottom) { return myBorder.setPaintBorder(top, left, right, bottom); } @Override public JBTabsPresentation setTabSidePaintBorder(int size) { return myBorder.setTabSidePaintBorder(size); } static int getBorder(int size) { return size == -1 ? 1 : size; } private boolean isPaintFocus() { return myPaintFocus; } @Override @NotNull public JBTabsPresentation setActiveTabFillIn(@Nullable final Color color) { if (!isChanged(myActiveTabFillIn, color)) return this; myActiveTabFillIn = color; revalidateAndRepaint(false); return this; } private static boolean isChanged(Object oldObject, Object newObject) { if (oldObject == null && newObject == null) return false; return oldObject != null && !oldObject.equals(newObject) || newObject != null && !newObject.equals(oldObject); } @Override @NotNull public JBTabsPresentation setTabLabelActionsAutoHide(final boolean autoHide) { if (myTabLabelActionsAutoHide != autoHide) { myTabLabelActionsAutoHide = autoHide; revalidateAndRepaint(false); } return this; } @Nullable protected Color getActiveTabFillIn() { return myActiveTabFillIn; } @Override public JBTabsPresentation setFocusCycle(final boolean root) { setFocusCycleRoot(root); return this; } @Override public JBTabsPresentation setPaintFocus(final boolean paintFocus) { myPaintFocus = paintFocus; return this; } @Override public JBTabsPresentation setAlwaysPaintSelectedTab(final boolean paintSelected) { myAlwaysPaintSelectedTab = paintSelected; return this; } private abstract static class BaseNavigationAction extends AnAction { private final ShadowAction myShadow; private final ActionManager myActionManager; private final JBTabsImpl myTabs; protected BaseNavigationAction(final String copyFromID, JBTabsImpl tabs, ActionManager mgr) { myActionManager = mgr; myTabs = tabs; myShadow = new ShadowAction(this, myActionManager.getAction(copyFromID), tabs); Disposer.register(tabs, myShadow); setEnabledInModalContext(true); } @Override public final void update(final AnActionEvent e) { JBTabsImpl tabs = e.getData(NAVIGATION_ACTIONS_KEY); e.getPresentation().setVisible(tabs != null); if (tabs == null) return; tabs = findNavigatableTabs(tabs); e.getPresentation().setEnabled(tabs != null); if (tabs != null) { _update(e, tabs, tabs.myVisibleInfos.indexOf(tabs.getSelectedInfo())); } } @Nullable protected JBTabsImpl findNavigatableTabs(JBTabsImpl tabs) { // The debugger UI contains multiple nested JBTabsImpl, where the innermost JBTabsImpl has only one tab. In this case, // the action should target the outer JBTabsImpl. if (tabs == null || tabs != myTabs) { return null; } if (isNavigatable(tabs)) { return tabs; } Component c = tabs.getParent(); while (c != null) { if (c instanceof JBTabsImpl && isNavigatable((JBTabsImpl)c)) { return (JBTabsImpl)c; } c = c.getParent(); } return null; } private static boolean isNavigatable(JBTabsImpl tabs) { final int selectedIndex = tabs.myVisibleInfos.indexOf(tabs.getSelectedInfo()); return tabs.isNavigationVisible() && selectedIndex >= 0 && tabs.myNavigationActionsEnabled; } public void reconnect(String actionId) { myShadow.reconnect(myActionManager.getAction(actionId)); } protected abstract void _update(AnActionEvent e, final JBTabsImpl tabs, int selectedIndex); @Override public final void actionPerformed(final AnActionEvent e) { JBTabsImpl tabs = e.getData(NAVIGATION_ACTIONS_KEY); tabs = findNavigatableTabs(tabs); if (tabs == null) return; final int index = tabs.myVisibleInfos.indexOf(tabs.getSelectedInfo()); if (index == -1) return; _actionPerformed(e, tabs, index); } protected abstract void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex); } private static class SelectNextAction extends BaseNavigationAction { private SelectNextAction(JBTabsImpl tabs, ActionManager mgr) { super(IdeActions.ACTION_NEXT_TAB, tabs, mgr); } @Override protected void _update(final AnActionEvent e, final JBTabsImpl tabs, int selectedIndex) { e.getPresentation().setEnabled(tabs.findEnabledForward(selectedIndex, true) != null); } @Override protected void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex) { tabs.select(tabs.findEnabledForward(selectedIndex, true), true); } } private static class SelectPreviousAction extends BaseNavigationAction { private SelectPreviousAction(JBTabsImpl tabs, ActionManager mgr) { super(IdeActions.ACTION_PREVIOUS_TAB, tabs, mgr); } @Override protected void _update(final AnActionEvent e, final JBTabsImpl tabs, int selectedIndex) { e.getPresentation().setEnabled(tabs.findEnabledBackward(selectedIndex, true) != null); } @Override protected void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex) { tabs.select(tabs.findEnabledBackward(selectedIndex, true), true); } } private void disposePopupListener() { if (myActivePopup != null) { myActivePopup.removePopupMenuListener(myPopupListener); myActivePopup = null; } } @Override public JBTabsPresentation setStealthTabMode(final boolean stealthTabMode) { myStealthTabMode = stealthTabMode; relayout(true, false); return this; } public boolean isStealthTabMode() { return myStealthTabMode; } @Override public JBTabsPresentation setSideComponentVertical(final boolean vertical) { myHorizontalSide = !vertical; for (TabInfo each : myVisibleInfos) { each.getChangeSupport().firePropertyChange(TabInfo.ACTION_GROUP, "new1", "new2"); } relayout(true, false); return this; } @Override public JBTabsPresentation setSideComponentOnTabs(boolean onTabs) { mySideComponentOnTabs = onTabs; relayout(true, false); return this; } @Override public JBTabsPresentation setSingleRow(boolean singleRow) { myLayout = singleRow ? mySingleRowLayout : myTableLayout; relayout(true, false); return this; } @Override public JBTabsPresentation setGhostsAlwaysVisible(final boolean visible) { myGhostsAlwaysVisible = visible; relayout(true, false); return this; } public boolean useSmallLabels() { return false; } public boolean useBoldLabels() { return false; } public boolean hasUnderline() { return false; } public boolean isGhostsAlwaysVisible() { return myGhostsAlwaysVisible; } @Override public boolean isSingleRow() { return getEffectiveLayout() == mySingleRowLayout; } public boolean isSideComponentVertical() { return !myHorizontalSide; } public boolean isSideComponentOnTabs() { return mySideComponentOnTabs; } public TabLayout getEffectiveLayout() { if (myLayout == myTableLayout && getTabsPosition() == JBTabsPosition.top) return myTableLayout; return mySingleRowLayout; } @Override public JBTabsPresentation setUiDecorator(@Nullable UiDecorator decorator) { myUiDecorator = decorator == null ? ourDefaultDecorator : decorator; applyDecoration(); return this; } @Override protected void setUI(final ComponentUI newUI) { super.setUI(newUI); applyDecoration(); } @Override public void updateUI() { super.updateUI(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { applyDecoration(); revalidateAndRepaint(false); } }); } private void applyDecoration() { if (myUiDecorator != null) { UiDecorator.UiDecoration uiDecoration = myUiDecorator.getDecoration(); for (TabLabel each : myInfo2Label.values()) { each.apply(uiDecoration); } } for (TabInfo each : getTabs()) { adjust(each); } relayout(true, false); } private void adjust(final TabInfo each) { if (myAdjustBorders) { UIUtil.removeScrollBorder(each.getComponent()); } } public void sortTabs(Comparator<TabInfo> comparator) { Collections.sort(myVisibleInfos, comparator); relayout(true, false); } private boolean isRequestFocusOnLastFocusedComponent() { return myRequestFocusOnLastFocusedComponent; } @Override public JBTabsPresentation setRequestFocusOnLastFocusedComponent(final boolean requestFocusOnLastFocusedComponent) { myRequestFocusOnLastFocusedComponent = requestFocusOnLastFocusedComponent; return this; } @Override @Nullable public Object getData(@NonNls final String dataId) { if (myDataProvider != null) { final Object value = myDataProvider.getData(dataId); if (value != null) return value; } if (SwitchProvider.KEY.getName().equals(dataId) && myOwnSwitchProvider) { return this; } if (QuickActionProvider.KEY.getName().equals(dataId)) { return this; } return NAVIGATION_ACTIONS_KEY.is(dataId) ? this : null; } @Override public List<AnAction> getActions(boolean originalProvider) { ArrayList<AnAction> result = new ArrayList<AnAction>(); TabInfo selection = getSelectedInfo(); if (selection != null) { ActionGroup group = selection.getGroup(); if (group != null) { AnAction[] children = group.getChildren(null); Collections.addAll(result, children); } } return result; } @Override public DataProvider getDataProvider() { return myDataProvider; } public JBTabsImpl setDataProvider(@NotNull final DataProvider dataProvider) { myDataProvider = dataProvider; return this; } public static boolean isSelectionClick(final MouseEvent e, boolean canBeQuick) { if (e.getClickCount() == 1 || canBeQuick) { if (!e.isPopupTrigger()) { return e.getButton() == MouseEvent.BUTTON1 && !e.isControlDown() && !e.isAltDown() && !e.isMetaDown(); } } return false; } private static class DefaultDecorator implements UiDecorator { @Override @NotNull public UiDecoration getDecoration() { return new UiDecoration(null, new Insets(0, 4, 0, 5)); } } public Rectangle layout(JComponent c, Rectangle bounds) { final Rectangle now = c.getBounds(); if (!bounds.equals(now)) { c.setBounds(bounds); } c.putClientProperty(LAYOUT_DONE, Boolean.TRUE); return bounds; } public Rectangle layout(JComponent c, int x, int y, int width, int height) { return layout(c, new Rectangle(x, y, width, height)); } public static void resetLayout(JComponent c) { if (c == null) return; c.putClientProperty(LAYOUT_DONE, null); c.putClientProperty(STRETCHED_BY_WIDTH, null); } private void applyResetComponents() { for (int i = 0; i < getComponentCount(); i++) { final Component each = getComponent(i); if (each instanceof JComponent) { final JComponent jc = (JComponent)each; final Object done = jc.getClientProperty(LAYOUT_DONE); if (!Boolean.TRUE.equals(done)) { layout(jc, new Rectangle(0, 0, 0, 0)); } } } } @Override @NotNull public JBTabsPresentation setTabLabelActionsMouseDeadzone(final TimedDeadzone.Length length) { myTabActionsMouseDeadzone = length; final List<TabInfo> all = getTabs(); for (TabInfo each : all) { final TabLabel eachLabel = myInfo2Label.get(each); eachLabel.updateTabActions(); } return this; } @Override @NotNull public JBTabsPresentation setTabsPosition(final JBTabsPosition position) { myPosition = position; relayout(true, false); return this; } @Override public JBTabsPosition getTabsPosition() { return myPosition; } public TimedDeadzone.Length getTabActionsMouseDeadzone() { return myTabActionsMouseDeadzone; } @Override public JBTabsPresentation setTabDraggingEnabled(boolean enabled) { myTabDraggingEnabled = enabled; return this; } public boolean isTabDraggingEnabled() { return myTabDraggingEnabled; } @Override public JBTabsPresentation setProvideSwitchTargets(boolean provide) { myOwnSwitchProvider = provide; return this; } void reallocate(TabInfo source, TabInfo target) { if (source == target || source == null || target == null) return; final int targetIndex = myVisibleInfos.indexOf(target); myVisibleInfos.remove(source); myVisibleInfos.add(targetIndex, source); invalidate(); relayout(true, true); } boolean isHorizontalTabs() { return getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom; } @Override public void putInfo(@NotNull Map<String, String> info) { final TabInfo selected = getSelectedInfo(); if (selected != null) { selected.putInfo(info); } } public void setUseBufferedPaint(boolean useBufferedPaint) { myUseBufferedPaint = useBufferedPaint; revalidate(); repaint(); } @Override public List<SwitchTarget> getTargets(boolean onlyVisible, boolean originalProvider) { ArrayList<SwitchTarget> result = new ArrayList<SwitchTarget>(); for (TabInfo each : myVisibleInfos) { result.add(new TabTarget(each)); } if (originalProvider && mySwitchDelegate != null) { List<SwitchTarget> additional = mySwitchDelegate.getTargets(onlyVisible, false); if (additional != null) { result.addAll(additional); } } return result; } @Override public SwitchTarget getCurrentTarget() { if (mySwitchDelegate != null) { SwitchTarget selection = mySwitchDelegate.getCurrentTarget(); if (selection != null) return selection; } return new TabTarget(getSelectedInfo()); } private class TabTarget extends ComparableObject.Impl implements SwitchTarget { private final TabInfo myInfo; private TabTarget(TabInfo info) { myInfo = info; } @Override public ActionCallback switchTo(boolean requestFocus) { return select(myInfo, requestFocus); } @Override public boolean isVisible() { return getRectangle() != null; } @Override public RelativeRectangle getRectangle() { TabLabel label = myInfo2Label.get(myInfo); if (label.getRootPane() == null) return null; Rectangle b = label.getBounds(); b.x += 2; b.width -= 4; b.y += 2; b.height -= 4; return new RelativeRectangle(label.getParent(), b); } @Override public Component getComponent() { return myInfo2Label.get(myInfo); } @Override public String toString() { return myInfo.getText(); } @NotNull @Override public Object[] getEqualityObjects() { return new Object[]{myInfo}; } } @Override public void resetDropOver(TabInfo tabInfo) { if (myDropInfo != null) { TabInfo dropInfo = myDropInfo; myDropInfo = null; myShowDropLocation = true; setDropInfoIndex(-1); if (!isDisposed()) { removeTab(dropInfo, null, false, true); } } } @Override public Image startDropOver(TabInfo tabInfo, RelativePoint point) { myDropInfo = tabInfo; int index = myLayout.getDropIndexFor(point.getPoint(this)); setDropInfoIndex(index); addTab(myDropInfo, index, true, true); TabLabel label = myInfo2Label.get(myDropInfo); Dimension size = label.getPreferredSize(); label.setBounds(0, 0, size.width, size.height); BufferedImage img = UIUtil.createImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); label.paintOffscreen(g); g.dispose(); relayout(true, false); return img; } @Override public void processDropOver(TabInfo over, RelativePoint point) { int index = myLayout.getDropIndexFor(point.getPoint(this)); if (index != getDropInfoIndex()) { setDropInfoIndex(index); relayout(true, false); } } public int getDropInfoIndex() { return myDropInfoIndex; } public boolean isEmptyVisible() { return myVisibleInfos.isEmpty(); } public static int getInterTabSpaceLength() { return 1; } @Override public String toString() { return "JBTabs visible=" + myVisibleInfos + " selected=" + mySelectedInfo; } }
{ "content_hash": "5705ed3d8a690abd96faa666817330fc", "timestamp": "", "source": "github", "line_count": 3329, "max_line_length": 140, "avg_line_length": 28.966656653649746, "alnum_prop": 0.6641709011718345, "repo_name": "romankagan/DDBWorkbench", "id": "ba9e46e3209561c3a66cd3d32a53b460000a22ea", "size": "97030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "182" }, { "name": "C", "bytes": "174330" }, { "name": "C#", "bytes": "390" }, { "name": "C++", "bytes": "85270" }, { "name": "CSS", "bytes": "102018" }, { "name": "Erlang", "bytes": "10" }, { "name": "FLUX", "bytes": "57" }, { "name": "Groovy", "bytes": "1899897" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "128604770" }, { "name": "JavaScript", "bytes": "123045" }, { "name": "Objective-C", "bytes": "19702" }, { "name": "Perl", "bytes": "6549" }, { "name": "Python", "bytes": "17759911" }, { "name": "Ruby", "bytes": "1213" }, { "name": "Shell", "bytes": "45691" }, { "name": "TeX", "bytes": "60798" }, { "name": "XSLT", "bytes": "113531" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; using NBitcoin.BitcoinCore; namespace NBitcoin { /// <summary> /// Injected proxy to <see cref="StandardScripts"/>. /// </summary> public class StandardScriptsRegistry : IStandardScriptsRegistry { /// <summary> /// Registers a new standard script template if it does not exist yet based on <see cref="ScriptTemplate.Type"/>. /// </summary> /// <param name="scriptTemplate">The standard script template to register.</param> public virtual void RegisterStandardScriptTemplate(ScriptTemplate scriptTemplate) { StandardScripts.RegisterStandardScriptTemplate(scriptTemplate); } public virtual bool IsStandardTransaction(Transaction tx, Network network) { return StandardScripts.IsStandardTransaction(tx, network); } public virtual bool AreOutputsStandard(Network network, Transaction tx) { return StandardScripts.AreOutputsStandard(network, tx); } public virtual ScriptTemplate GetTemplateFromScriptPubKey(Script script) { return StandardScripts.GetTemplateFromScriptPubKey(script); } public virtual bool IsStandardScriptPubKey(Network network, Script scriptPubKey) { return StandardScripts.IsStandardScriptPubKey(network, scriptPubKey); } public virtual bool AreInputsStandard(Network network, Transaction tx, CoinsView coinsView) { return StandardScripts.AreInputsStandard(network, tx, coinsView); } } }
{ "content_hash": "2ee796f4f8acb3ebf0ae477dc30fcb3d", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 121, "avg_line_length": 35.04255319148936, "alnum_prop": 0.6775956284153005, "repo_name": "mikedennis/StratisBitcoinFullNode", "id": "9292f33e31bc14a2e19316f432b5f980122ae2e6", "size": "1649", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/NBitcoin/StandardScriptsRegistry.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "216" }, { "name": "C#", "bytes": "11765001" }, { "name": "CSS", "bytes": "162959" }, { "name": "Dockerfile", "bytes": "1636" }, { "name": "HTML", "bytes": "44120" }, { "name": "JavaScript", "bytes": "4289" }, { "name": "PowerShell", "bytes": "8508" }, { "name": "Shell", "bytes": "3446" } ], "symlink_target": "" }
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc1024.Test; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DigitalOutput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj.Servo; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Ultrasonic; import edu.wpi.first.wpilibj.interfaces.Gyro; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static Talon drivetrainright; public static Talon drivetrainleft; public static Encoder gyrospeed; //public static AHRS navx; //public static Servo climberFlinger; public static Encoder leftEncoder; public static Encoder rightEncoder; //public static Encoder testEncoder; public static AnalogGyro gyro; public static DigitalOutput ping; public static DigitalInput echo; public static AnalogInput Ultrasonic; public static Ultrasonic Ultra; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static void init() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS drivetrainright = new Talon(0); LiveWindow.addActuator("drivetrain", "right", drivetrainright); drivetrainleft = new Talon(1); LiveWindow.addActuator("drivetrain", "left", drivetrainleft); //navx = new AHRS(SerialPort.Port.kMXP); //LiveWindow.addActuator("drivetrain", "navx", navx); //climberFlinger = new Servo(8); //LiveWindow.addActuator("drivetrain", "Servo", climberFlinger); leftEncoder = new Encoder(0,1); LiveWindow.addActuator("drivetrain", "Encoder", leftEncoder); rightEncoder = new Encoder(2,3); LiveWindow.addActuator("drivetrain", "Encoder", rightEncoder); //testEncoder = new Encoder(4,5); gyro = new AnalogGyro(1); LiveWindow.addActuator("drivetrain", "Gyro", gyro); //gyrospeed = new Encoder(1, 0); ping = new DigitalOutput(5); echo = new DigitalInput(4); Ultrasonic = new AnalogInput(3); Ultra = new Ultrasonic(ping, echo); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS } }
{ "content_hash": "408d3786b0136b238857bfab3c498cfb", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 80, "avg_line_length": 38.06666666666667, "alnum_prop": 0.7119089316987741, "repo_name": "Xanawatt/TestingGit", "id": "8819575f3f418a8a08c47ae0320337f25bd7cd91", "size": "3426", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/usfirst/frc1024/Test/RobotMap.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "18470" } ], "symlink_target": "" }
if(!dojo._hasResource["dojox.data.OpenSearchStore"]){ dojo._hasResource["dojox.data.OpenSearchStore"]=true; dojo.provide("dojox.data.OpenSearchStore"); dojo.require("dojo.data.util.simpleFetch"); dojo.require("dojox.xml.DomParser"); dojo.require("dojox.xml.parser"); dojo.experimental("dojox.data.OpenSearchStore"); dojo.declare("dojox.data.OpenSearchStore",null,{constructor:function(_1){ if(_1){ this.label=_1.label; this.url=_1.url; this.itemPath=_1.itemPath; } var _2=dojo.xhrGet({url:this.url,handleAs:"xml",sync:true}); _2.addCallback(this,"_processOsdd"); _2.addErrback(function(){ throw new Error("Unable to load OpenSearch Description document from ".args.url); }); },url:"",itemPath:"",_storeRef:"_S",urlElement:null,iframeElement:null,ATOM_CONTENT_TYPE:3,ATOM_CONTENT_TYPE_STRING:"atom",RSS_CONTENT_TYPE:2,RSS_CONTENT_TYPE_STRING:"rss",XML_CONTENT_TYPE:1,XML_CONTENT_TYPE_STRING:"xml",_assertIsItem:function(_3){ if(!this.isItem(_3)){ throw new Error("dojox.data.OpenSearchStore: a function was passed an item argument that was not an item"); } },_assertIsAttribute:function(_4){ if(typeof _4!=="string"){ throw new Error("dojox.data.OpenSearchStore: a function was passed an attribute argument that was not an attribute name string"); } },getFeatures:function(){ return {"dojo.data.api.Read":true}; },getValue:function(_5,_6,_7){ var _8=this.getValues(_5,_6); if(_8){ return _8[0]; } return _7; },getAttributes:function(_9){ return ["content"]; },hasAttribute:function(_a,_b){ if(this.getValue(_a,_b)){ return true; } return false; },isItemLoaded:function(_c){ return this.isItem(_c); },loadItem:function(_d){ },getLabel:function(_e){ return undefined; },getLabelAttributes:function(_f){ return null; },containsValue:function(_10,_11,_12){ var _13=this.getValues(_10,_11); for(var i=0;i<_13.length;i++){ if(_13[i]===_12){ return true; } } return false; },getValues:function(_15,_16){ this._assertIsItem(_15); this._assertIsAttribute(_16); var _17=this.processItem(_15,_16); if(_17){ return [_17]; } return undefined; },isItem:function(_18){ if(_18&&_18[this._storeRef]===this){ return true; } return false; },close:function(_19){ },process:function(_1a){ return this["_processOSD"+this.contentType](_1a); },processItem:function(_1b,_1c){ return this["_processItem"+this.contentType](_1b.node,_1c); },_createSearchUrl:function(_1d){ var _1e=this.urlElement.attributes.getNamedItem("template").nodeValue; var _1f=this.urlElement.attributes; var _20=_1e.indexOf("{searchTerms}"); _1e=_1e.substring(0,_20)+_1d.query.searchTerms+_1e.substring(_20+13); dojo.forEach([{"name":"count","test":_1d.count,"def":"10"},{"name":"startIndex","test":_1d.start,"def":this.urlElement.attributes.getNamedItem("indexOffset")?this.urlElement.attributes.getNamedItem("indexOffset").nodeValue:0},{"name":"startPage","test":_1d.startPage,"def":this.urlElement.attributes.getNamedItem("pageOffset")?this.urlElement.attributes.getNamedItem("pageOffset").nodeValue:0},{"name":"language","test":_1d.language,"def":"*"},{"name":"inputEncoding","test":_1d.inputEncoding,"def":"UTF-8"},{"name":"outputEncoding","test":_1d.outputEncoding,"def":"UTF-8"}],function(_21){ _1e=_1e.replace("{"+_21.name+"}",_21.test||_21.def); _1e=_1e.replace("{"+_21.name+"?}",_21.test||_21.def); }); return _1e; },_fetchItems:function(_22,_23,_24){ if(!_22.query){ _22.query={}; } var _25=this; var url=this._createSearchUrl(_22); var _27={url:url,preventCache:true}; var xhr=dojo.xhrGet(_27); xhr.addErrback(function(_29){ _24(_29,_22); }); xhr.addCallback(function(_2a){ var _2b=[]; if(_2a){ _2b=_25.process(_2a); for(var i=0;i<_2b.length;i++){ _2b[i]={node:_2b[i]}; _2b[i][_25._storeRef]=_25; } } _23(_2b,_22); }); },_processOSDxml:function(_2d){ var div=dojo.doc.createElement("div"); div.innerHTML=_2d; return dojo.query(this.itemPath,div); },_processItemxml:function(_2f,_30){ if(_30==="content"){ return _2f.innerHTML; } return undefined; },_processOSDatom:function(_31){ return this._processOSDfeed(_31,"entry"); },_processItematom:function(_32,_33){ return this._processItemfeed(_32,_33,"content"); },_processOSDrss:function(_34){ return this._processOSDfeed(_34,"item"); },_processItemrss:function(_35,_36){ return this._processItemfeed(_35,_36,"description"); },_processOSDfeed:function(_37,_38){ _37=dojox.xml.parser.parse(_37); var _39=[]; var _3a=_37.getElementsByTagName(_38); for(var i=0;i<_3a.length;i++){ _39.push(_3a.item(i)); } return _39; },_processItemfeed:function(_3c,_3d,_3e){ if(_3d==="content"){ var _3f=_3c.getElementsByTagName(_3e).item(0); return this._getNodeXml(_3f,true); } return undefined; },_getNodeXml:function(_40,_41){ var i; switch(_40.nodeType){ case 1: var xml=[]; if(!_41){ xml.push("<"+_40.tagName); var _44; for(i=0;i<_40.attributes.length;i++){ _44=_40.attributes.item(i); xml.push(" "+_44.nodeName+"=\""+_44.nodeValue+"\""); } xml.push(">"); } for(i=0;i<_40.childNodes.length;i++){ xml.push(this._getNodeXml(_40.childNodes.item(i))); } if(!_41){ xml.push("</"+_40.tagName+">\n"); } return xml.join(""); case 3: case 4: return _40.nodeValue; } return undefined; },_processOsdd:function(doc){ var _46=doc.getElementsByTagName("Url"); var _47=[]; var _48; var i; for(i=0;i<_46.length;i++){ _48=_46[i].attributes.getNamedItem("type").nodeValue; switch(_48){ case "application/rss+xml": _47[i]=this.RSS_CONTENT_TYPE; break; case "application/atom+xml": _47[i]=this.ATOM_CONTENT_TYPE; break; default: _47[i]=this.XML_CONTENT_TYPE; break; } } var _4a=0; var _4b=_47[0]; for(i=1;i<_46.length;i++){ if(_47[i]>_4b){ _4a=i; _4b=_47[i]; } } var _4c=_46[_4a].nodeName.toLowerCase(); if(_4c=="url"){ var _4d=_46[_4a].attributes; this.urlElement=_46[_4a]; switch(_47[_4a]){ case this.ATOM_CONTENT_TYPE: this.contentType=this.ATOM_CONTENT_TYPE_STRING; break; case this.RSS_CONTENT_TYPE: this.contentType=this.RSS_CONTENT_TYPE_STRING; break; case this.XML_CONTENT_TYPE: this.contentType=this.XML_CONTENT_TYPE_STRING; break; } } }}); dojo.extend(dojox.data.OpenSearchStore,dojo.data.util.simpleFetch); }
{ "content_hash": "9ca6f689ac4b5ba662b51b7fc62e06c2", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 589, "avg_line_length": 28.28301886792453, "alnum_prop": 0.6942961974649766, "repo_name": "logzio/camel", "id": "1bec2833f996b0b6ccbecd132fcf8949d0b64b6a", "size": "6190", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "components/camel-web/src/main/webapp/js/dojox/data/OpenSearchStore.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "20202" }, { "name": "Batchfile", "bytes": "106" }, { "name": "CSS", "bytes": "221391" }, { "name": "Eagle", "bytes": "2898" }, { "name": "Elm", "bytes": "5970" }, { "name": "FreeMarker", "bytes": "12394" }, { "name": "Groovy", "bytes": "23444" }, { "name": "HTML", "bytes": "406194" }, { "name": "Java", "bytes": "42719701" }, { "name": "JavaScript", "bytes": "3695475" }, { "name": "PHP", "bytes": "88860" }, { "name": "Protocol Buffer", "bytes": "578" }, { "name": "Python", "bytes": "36" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "299988" }, { "name": "Shell", "bytes": "9057" }, { "name": "Tcl", "bytes": "4974" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "284036" } ], "symlink_target": "" }
static DCHSoundCloudApi *sharedInstance = nil; @interface DCHSoundCloudApi() @property (nonatomic, copy) NSString *clientID; @property (nonatomic, strong) DCHSoundCloudPlayer *player; @end @implementation DCHSoundCloudApi #pragma mark - Public + (instancetype)sharedInstance{ NSAssert(nil != sharedInstance && sharedInstance.clientID != nil, @"[DCHSoundCloudApi setClientID:] has to be called before using sharedInstance"); return sharedInstance; } + (void)setClientID:(NSString *)clientID{ sharedInstance = [[DCHSoundCloudApi alloc] init]; sharedInstance.clientID = clientID; [DDLog addLogger:[DDTTYLogger sharedInstance]]; } - (void)playItemAtUrl:(NSString *)url progressHandler:(DCHSoundCloudApiProgressHandler)progressHandler{ NSAssert(0 != url.length, @"DCHSoundCloudApi can't play an empty url"); [[DCHSoundCloudResolve startAsyncWithUrl:url clientId:self.clientID] continueWithBlock:^id(BFTask *task){ NSURL *trackURL = [NSURL URLWithString:task.result]; NSURLSessionTask *sessionTask = [[NSURLSession sharedSession] dataTaskWithURL:trackURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^(void){ if (error){ NSLog(@"ERROR GETTING DATA: %@", [error localizedDescription]); return; } _isPlaying = YES; self.player = [[DCHSoundCloudPlayer alloc] initWithData:data]; [self.player playWithProgressHandler:progressHandler]; }); }]; [sessionTask resume]; return nil; }]; } - (void)stop{ _isPlaying = NO; [self.player stop]; } @end
{ "content_hash": "8499dabb564b825035b0ab3df12995db", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 151, "avg_line_length": 38.417910447761194, "alnum_prop": 0.4553224553224553, "repo_name": "dchirita/DCHSoundCloudApi", "id": "89c367541a6b4727f99f4426ef5a635bcda8d3a7", "size": "2802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pod/Classes/DCHSoundCloudApi.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "13536" }, { "name": "Ruby", "bytes": "1858" } ], "symlink_target": "" }
package org.kie.services.client.serialization.jaxb.impl.audit; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonSubTypes; import org.codehaus.jackson.annotate.JsonSubTypes.Type; import org.codehaus.jackson.annotate.JsonTypeInfo; import org.codehaus.jackson.annotate.JsonTypeInfo.As; import org.codehaus.jackson.annotate.JsonTypeInfo.Id; import org.kie.api.runtime.manager.audit.NodeInstanceLog; import org.kie.api.runtime.manager.audit.ProcessInstanceLog; import org.kie.api.runtime.manager.audit.VariableInstanceLog; import org.kie.services.client.serialization.jaxb.impl.JaxbCommandResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbPaginatedList; @XmlRootElement(name="log-instance-list") @XmlAccessorType(XmlAccessType.FIELD) @SuppressWarnings("rawtypes") @JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE, fieldVisibility=JsonAutoDetect.Visibility.ANY) public class JaxbHistoryLogList implements JaxbCommandResponse<List<Object>>, JaxbPaginatedList<Object> { @XmlElements({ @XmlElement(name = "process-instance-log", type = JaxbProcessInstanceLog.class), @XmlElement(name = "node-instance-log", type = JaxbNodeInstanceLog.class), @XmlElement(name = "variable-instance-log", type = JaxbVariableInstanceLog.class), }) @JsonTypeInfo(use=Id.CLASS, include=As.WRAPPER_OBJECT) @JsonSubTypes({ @Type(value=JaxbProcessInstanceLog.class), @Type(value=JaxbNodeInstanceLog.class), @Type(value=JaxbVariableInstanceLog.class) }) private List<AbstractJaxbHistoryObject> historyLogList; @XmlAttribute @XmlSchemaType(name = "int") private Integer index; @XmlElement(name = "command-name") @XmlSchemaType(name = "string") private String commandName; @XmlElement(name="page-number") @XmlSchemaType(name="int") private Integer pageNumber; @XmlElement(name="page-size") @XmlSchemaType(name="int") private Integer pageSize; public JaxbHistoryLogList() { // Default constructor } public JaxbHistoryLogList( List<? extends Object> logList ) { initialize(logList); } private void initialize( List<? extends Object> logList ) { this.historyLogList = new ArrayList<AbstractJaxbHistoryObject>(); if( logList == null || logList.size() == 0 ) { return; } for( Object logObj : logList ) { if( logObj instanceof ProcessInstanceLog ) { this.historyLogList.add(new JaxbProcessInstanceLog((ProcessInstanceLog) logObj)); } else if( logObj instanceof NodeInstanceLog ) { this.historyLogList.add(new JaxbNodeInstanceLog((NodeInstanceLog) logObj)); } else if( logObj instanceof VariableInstanceLog ) { this.historyLogList.add(new JaxbVariableInstanceLog((VariableInstanceLog) logObj)); } else { throw new IllegalArgumentException(logObj.getClass().getSimpleName() + " is not an acceptable object (list) for this constructor."); } } } public List<AbstractJaxbHistoryObject> getHistoryLogList() { lazyInitResponseList(); return historyLogList; } public void setHistoryLogList(List<AbstractJaxbHistoryObject> list) { this.historyLogList = list; } private void lazyInitResponseList() { if( this.historyLogList == null ) { this.historyLogList = new ArrayList<AbstractJaxbHistoryObject>(); } } /** * {@link JaxbCommandResponse} methods */ @Override public Integer getIndex() { return index; } @Override public void setIndex(Integer index) { this.index = index; } @Override public String getCommandName() { return commandName; } @Override public void setCommandName(String cmdName) { this.commandName = cmdName; } @Override @JsonIgnore public List<Object> getResult() { lazyInitResponseList(); List<Object> results = new ArrayList<Object>(); for( AbstractJaxbHistoryObject<Object> jaxbHistLog : this.historyLogList ) { results.add(jaxbHistLog ); } return results; } @Override public void setResult(List<Object> result) { initialize(result);; } @Override public void addContents(List<Object> contentList) { initialize(contentList); } @JsonTypeInfo(use=Id.CLASS, include=As.WRAPPER_OBJECT) @JsonSubTypes({ @Type(value=JaxbProcessInstanceLog.class), @Type(value=JaxbNodeInstanceLog.class), @Type(value=JaxbVariableInstanceLog.class) }) public List<AbstractJaxbHistoryObject> getList() { return historyLogList; } public void setList(List<AbstractJaxbHistoryObject> historyLogList) { this.historyLogList = historyLogList; } @Override public Integer getPageNumber() { return this.pageNumber; } @Override public void setPageNumber(Integer page) { this.pageNumber = page; } @Override public Integer getPageSize() { return this.pageSize; } @Override public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } }
{ "content_hash": "8ea5480fe73c19565474597221b60c77", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 148, "avg_line_length": 31.815217391304348, "alnum_prop": 0.6838059446532285, "repo_name": "OnePaaS/droolsjbpm-integration", "id": "49543178709e617df38eb8bc76cde18b6e7239ff", "size": "6404", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "kie-remote/kie-remote-jaxb/src/main/java/org/kie/services/client/serialization/jaxb/impl/audit/JaxbHistoryLogList.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2569" }, { "name": "Java", "bytes": "5129950" }, { "name": "Shell", "bytes": "3525" }, { "name": "XSLT", "bytes": "2865" } ], "symlink_target": "" }
using System; using System.Linq; using System.Management.Automation; using Xrm.Framework.CI.Common; using Xrm.Framework.CI.Common.Entities; using Xrm.Framework.CI.PowerShell.Cmdlets.Common; namespace Xrm.Framework.CI.PowerShell.Cmdlets { /// <summary> /// <para type="synopsis">Sets a CDS Connection Reference.</para> /// <para type="description">This cmdlet links a connection reference to an existing connection /// </para> /// </summary> /// <example> /// <code>C:\PS>Set-XrmConnectionReference -Name "new_Name" -ConnectionId "id""</code> /// </example> [Cmdlet(VerbsCommon.Set, "XrmConnectionReference")] public class SetXrmConnectionReferenceCommand : XrmCommandBase { #region Parameters /// <summary> /// <para type="description">The LogicalName of the connection reference</para> /// </summary> [Parameter(Mandatory = true)] public string Name { get; set; } /// <summary> /// <para type="description">The Id of the connection</para> /// </summary> [Parameter(Mandatory = true)] public string ConnectionId { get; set; } #endregion #region Process Record protected override void ProcessRecord() { base.ProcessRecord(); ConnectionReferenceManager manager = new ConnectionReferenceManager(Logger, OrganizationService); manager.SetConnectionReference(Name, ConnectionId); } #endregion } }
{ "content_hash": "8507b06c306e43a098bd8f23f5ad01e5", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 109, "avg_line_length": 30.48, "alnum_prop": 0.6404199475065617, "repo_name": "WaelHamze/xrm-ci-framework", "id": "43310b9c9f9d7760fd4065f47f406e714a4ded91", "size": "1526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MSDYNV9/Xrm.Framework.CI/Xrm.Framework.CI.PowerShell.Cmdlets/SetXrmConnectionReferenceCommand.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "19363299" }, { "name": "CSS", "bytes": "267932" }, { "name": "HTML", "bytes": "47099" }, { "name": "JavaScript", "bytes": "67" }, { "name": "PowerShell", "bytes": "485827" }, { "name": "XSLT", "bytes": "1240" } ], "symlink_target": "" }
package io.github.mzmine.util; import java.time.LocalDateTime; import java.time.ZonedDateTime; import org.jetbrains.annotations.NotNull; /** * Parse and format dates. MZmine uses {@link LocalDateTime} to represent date + time in this * format: 2022-06-01T18:36:09 * <p> * 2022-06-01T18:36:09Z is a zoned format that needs to be parsed by {@link ZonedDateTime} * * @author Robin Schmid <a href="https://github.com/robinschmid">https://github.com/robinschmid</a> */ public class DateTimeUtils { /** * Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30. The string * must represent a valid date-time and is parsed using DateTimeFormatter.ISO_LOCAL_DATE_TIME. * * @param dateTime the text to parse such as "2007-12-03T10:15:30" or "2007-12-03T10:15:30Z" * @return the parsed local date-time, not null * @throws java.time.format.DateTimeParseException – if the text cannot be parsed */ @NotNull public static LocalDateTime parse(@NotNull String dateTime) { try { // ZonedDateTime with 2022-06-01T18:36:09Z where the Z stands for UTC return ZonedDateTime.parse(dateTime).toLocalDateTime(); } catch (Exception ignored) { // try to parse LocalDateTime 2022-06-01T18:36:09 return LocalDateTime.parse(dateTime); } } }
{ "content_hash": "0ea7a41da073ab17ee2da13830ec9600", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 100, "avg_line_length": 34.71052631578947, "alnum_prop": 0.7164518574677786, "repo_name": "mzmine/mzmine3", "id": "f6db42230a4f9b07f3ff029f3b015527418711f3", "size": "2466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/github/mzmine/util/DateTimeUtils.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24537" }, { "name": "HTML", "bytes": "206954" }, { "name": "Java", "bytes": "12683356" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">GestureDemo</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> </resources>
{ "content_hash": "b8260883dd7ebe79b29b48f743d1820c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 27.625, "alnum_prop": 0.6787330316742082, "repo_name": "liyanippon/working", "id": "271e424317377526df329d6423d23a3b568babc3", "size": "221", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "java开发资料/dataStu/android手势(eclipse)/GesturePswDemo-master/GesturePswDemo/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "30036" }, { "name": "Batchfile", "bytes": "7951" }, { "name": "C", "bytes": "139882" }, { "name": "C#", "bytes": "933821" }, { "name": "C++", "bytes": "164358" }, { "name": "CSS", "bytes": "1505309" }, { "name": "HTML", "bytes": "15213230" }, { "name": "Java", "bytes": "7271602" }, { "name": "JavaScript", "bytes": "2721649" }, { "name": "M4", "bytes": "193907" }, { "name": "PHP", "bytes": "409031" }, { "name": "Pascal", "bytes": "275042" }, { "name": "Perl", "bytes": "3913080" }, { "name": "Perl 6", "bytes": "20453" }, { "name": "PowerShell", "bytes": "372744" }, { "name": "Prolog", "bytes": "374" }, { "name": "Puppet", "bytes": "1944" }, { "name": "Python", "bytes": "989" }, { "name": "Shell", "bytes": "256369" }, { "name": "Tcl", "bytes": "2138370" }, { "name": "Vim script", "bytes": "590417" }, { "name": "Visual Basic", "bytes": "416" }, { "name": "XSLT", "bytes": "50637" } ], "symlink_target": "" }
/** * @author Adrien Brault <adrien.brault@gmail.com> */ 'use strict'; var Point = require('./Point'); /** * @class Polygon * @constructor * @param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon, * a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arugments passed can be * all the points of the polygon e.g. `new Polygon(new Point(), new Point(), ...)`, or the * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ function Polygon(points) { //if points isn't an array, use arguments as the array if(!(points instanceof Array)) points = Array.prototype.slice.call(arguments); //if this is a flat array of numbers, convert it to points if(typeof points[0] === 'number') { var p = []; for(var i = 0, il = points.length; i < il; i+=2) { p.push( new Point(points[i], points[i + 1]) ); } points = p; } this.points = points; } var proto = Polygon.prototype; /** * Creates a clone of this polygon * * @method clone * @return {Polygon} a copy of the polygon */ proto.clone = function() { var points = []; for (var i=0; i<this.points.length; i++) { points.push(this.points[i].clone()); } return new Polygon(points); }; /** * Checks if the x, and y coords passed to this function are contained within this polygon * * @method contains * @param x {Number} The X coord of the point to test * @param y {Number} The Y coord of the point to test * @return {Boolean} if the x/y coords are within this polygon */ proto.contains = function(x, y) { var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js for(var i = 0, j = this.points.length - 1; i < this.points.length; j = i++) { var xi = this.points[i].x, yi = this.points[i].y, xj = this.points[j].x, yj = this.points[j].y, intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); if(intersect) inside = !inside; } return inside; }; module.exports = Polygon;
{ "content_hash": "ecbbbf6ebe842b494a9420b4a1ce063e", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 119, "avg_line_length": 28.271604938271604, "alnum_prop": 0.5873362445414847, "repo_name": "drkibitz/node-pixi", "id": "b3c3b03ab8c1975541370d31cbac4a4f49b07674", "size": "2290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pixi/geom/Polygon.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "413693" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Elasticsearch.Net; namespace Nest { [DebuggerDisplay("{DebugDisplay,nq}")] public class Names : IUrlParameter { private readonly IEnumerable<Name> _names; public Names(IEnumerable<string> names) { if (!names.HasAny()) throw new ArgumentException("can not create Names on an empty enumerable of string", nameof(names)); this._names = names.Select(n => (Name)n); } public Names(IEnumerable<Name> names) { this._names = names; } public static Names Parse(string names) { if (names.IsNullOrEmpty()) throw new ArgumentException("can not create Names on an empty enumerable of string", nameof(names)); var nameList = names.Split(new [] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s=>s.Trim()); return new Names(nameList); } //TODO to explicit private implemenation public string GetString(IConnectionConfigurationValues settings) => string.Join(",", this._names.Select(n => n.GetString(settings))); private string DebugDisplay => GetString(null); public static implicit operator Names(Name name) => new Names(new[] { name }); public static implicit operator Names(string names) => Parse(names); } }
{ "content_hash": "77a07d68a0ba98aaa4bbffe39c5b3ce8", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 130, "avg_line_length": 32.30769230769231, "alnum_prop": 0.7246031746031746, "repo_name": "CSGOpenSource/elasticsearch-net", "id": "9ab5fb398a9c06b91eb06eec41a5795cd03ea1b0", "size": "1262", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Nest/CommonAbstractions/Infer/Name/Names.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3270" }, { "name": "C#", "bytes": "8180341" }, { "name": "F#", "bytes": "42280" }, { "name": "HTML", "bytes": "295209" }, { "name": "Shell", "bytes": "1853" }, { "name": "Smalltalk", "bytes": "3426" } ], "symlink_target": "" }
// Copyright 2009 Google Inc. // All Rights Reserved. /** * This file exposes the external Google Visualization API. * * The file can be used to enable auto complete of objects and methods provided by the * Google Visualization API, and for easier exploration of the API. * * To enable auto complete in a development environment - copy the file into the project * you are working on where the development tool you are using can index the file. * * Disclaimer: there may be missing classes and methods and the file may * be updated and/or changed. For the most up to date API reference please visit: * {@link http://code.google.com/intl/iw/apis/visualization/documentation/reference.html} */ var google = {}; google.visualization = {}; google.visualization.DataTable = function(opt_data, opt_version){}; google.visualization.DataTable.prototype.getNumberOfRows = function(){}; google.visualization.DataTable.prototype.getNumberOfColumns = function(){}; google.visualization.DataTable.prototype.clone = function(){}; google.visualization.DataTable.prototype.getColumnId = function(columnIndex){}; google.visualization.DataTable.prototype.getColumnIndex = function(columnId){}; google.visualization.DataTable.prototype.getColumnLabel = function(columnIndex){}; google.visualization.DataTable.prototype.getColumnPattern = function(columnIndex){}; google.visualization.DataTable.prototype.getColumnType = function(columnIndex){}; google.visualization.DataTable.prototype.getValue = function(rowIndex, columnIndex){}; google.visualization.DataTable.prototype.getFormattedValue = function(rowIndex, columnIndex){}; google.visualization.DataTable.prototype.getProperty = function(rowIndex, columnIndex, property){}; google.visualization.DataTable.prototype.getProperties = function(rowIndex, columnIndex){}; google.visualization.DataTable.prototype.getTableProperties = function(){}; google.visualization.DataTable.prototype.getTableProperty = function(property){}; google.visualization.DataTable.prototype.setTableProperties = function(properties){}; google.visualization.DataTable.prototype.setTableProperty = function(property, value){}; google.visualization.DataTable.prototype.setValue = function(rowIndex, columnIndex, value){}; google.visualization.DataTable.prototype.setFormattedValue = function(rowIndex, columnIndex, formattedValue){}; google.visualization.DataTable.prototype.setProperties = function(rowIndex, columnIndex, properties){}; google.visualization.DataTable.prototype.setProperty = function(rowIndex, columnIndex, property, value){}; google.visualization.DataTable.prototype.setCell = function(rowIndex, columnIndex, opt_value, opt_formattedValue, opt_properties){}; google.visualization.DataTable.prototype.setRowProperties = function(rowIndex, properties){}; google.visualization.DataTable.prototype.setRowProperty = function(rowIndex, property, value){}; google.visualization.DataTable.prototype.getRowProperty = function(rowIndex, property){}; google.visualization.DataTable.prototype.getRowProperties = function(rowIndex){}; google.visualization.DataTable.prototype.setColumnLabel = function(columnIndex, newLabel){}; google.visualization.DataTable.prototype.setColumnProperties = function(columnIndex, properties){}; google.visualization.DataTable.prototype.setColumnProperty = function(columnIndex, property, value){}; google.visualization.DataTable.prototype.getColumnProperty = function(columnIndex, property){}; google.visualization.DataTable.prototype.getColumnProperties = function(columnIndex){}; google.visualization.DataTable.prototype.insertColumn = function(atColIndex, type, opt_label, opt_id){}; google.visualization.DataTable.prototype.addColumn = function(type, opt_label, opt_id){}; google.visualization.DataTable.prototype.insertRows = function(atRowIndex, numOrArray){}; google.visualization.DataTable.prototype.addRows = function(numOrArray){}; google.visualization.DataTable.prototype.addRow = function(opt_cellArray){}; google.visualization.DataTable.prototype.getColumnRange = function(columnIndex){}; google.visualization.DataTable.prototype.getSortedRows = function(sortColumns){}; google.visualization.DataTable.prototype.sort = function(sortColumns){}; google.visualization.DataTable.prototype.getDistinctValues = function(column){}; google.visualization.DataTable.prototype.getFilteredRows = function(columnFilters){}; google.visualization.DataTable.prototype.removeRows = function(fromRowIndex, numRows){}; google.visualization.DataTable.prototype.removeRow = function(rowIndex){}; google.visualization.DataTable.prototype.removeColumns = function(fromColIndex, numCols){}; google.visualization.DataTable.prototype.removeColumn = function(colIndex){}; google.visualization.QueryResponse = function(responseObj){}; google.visualization.QueryResponse.getVersionFromResponse = function(responseObj){}; google.visualization.QueryResponse.prototype.getVersion = function(){}; google.visualization.QueryResponse.prototype.getExecutionStatus = function(){}; google.visualization.QueryResponse.prototype.isError = function(){}; google.visualization.QueryResponse.prototype.hasWarning = function(){}; google.visualization.QueryResponse.prototype.containsReason = function(reason){}; google.visualization.QueryResponse.prototype.getDataSignature = function(){}; google.visualization.QueryResponse.prototype.getDataTable = function(){}; google.visualization.QueryResponse.prototype.getReasons = function(){}; google.visualization.QueryResponse.prototype.getMessage = function(){}; google.visualization.QueryResponse.prototype.getDetailedMessage = function(){}; google.visualization.Query = function(dataSourceUrl){}; google.visualization.Query.refreshAllQueries = function(){}; google.visualization.Query.setResponse = function(response){}; google.visualization.Query.prototype.setRefreshInterval = function(intervalSeconds){}; google.visualization.Query.prototype.send = function(responseHandler){}; google.visualization.Query.prototype.makeRequest = function(responseHandler, opt_params){}; google.visualization.Query.prototype.abort = function(){}; google.visualization.Query.prototype.setTimeout = function(timeoutSeconds){}; google.visualization.Query.prototype.setRefreshable = function(refreshable){}; google.visualization.Query.prototype.setQuery = function(queryString){}; google.visualization.errors.addError = function(container, message, opt_detailedMessage, opt_options){}; google.visualization.errors.removeAll = function(container){}; google.visualization.errors.addErrorFromQueryResponse = function(container, response){}; google.visualization.errors.removeError = function(id){}; google.visualization.errors.getContainer = function(errorId){}; google.visualization.events.addListener = function(eventSource, eventName, eventHandler){}; google.visualization.events.trigger = function(eventSource, eventName, eventDetails){}; google.visualization.events.removeListener = function(listener){}; google.visualization.DataView = function(dataTable){}; google.visualization.DataView.prototype.setColumns = function(colIndices){}; google.visualization.DataView.prototype.setRows = function(arg0, opt_arg1){}; google.visualization.DataView.prototype.getViewColumns = function(){}; google.visualization.DataView.prototype.getViewRows = function(){}; google.visualization.DataView.prototype.hideColumns = function(colIndices){}; google.visualization.DataView.prototype.hideRows = function(arg0, opt_arg1){}; google.visualization.DataView.prototype.getViewColumnIndex = function(tableColumnIndex){}; google.visualization.DataView.prototype.getViewRowIndex = function(tableRowIndex){}; google.visualization.DataView.prototype.getTableColumnIndex = function(viewColumnIndex){}; google.visualization.DataView.prototype.getTableRowIndex = function(viewRowIndex){}; google.visualization.DataView.prototype.getNumberOfRows = function(){}; google.visualization.DataView.prototype.getNumberOfColumns = function(){}; google.visualization.DataView.prototype.getColumnId = function(columnIndex){}; google.visualization.DataView.prototype.getColumnIndex = function(columnId){}; google.visualization.DataView.prototype.getColumnLabel = function(columnIndex){}; google.visualization.DataView.prototype.getColumnPattern = function(columnIndex){}; google.visualization.DataView.prototype.getColumnType = function(columnIndex){}; google.visualization.DataView.prototype.getValue = function(rowIndex, columnIndex){}; google.visualization.DataView.prototype.getFormattedValue = function(rowIndex, columnIndex){}; google.visualization.DataView.prototype.getProperty = function(rowIndex, columnIndex, property){}; google.visualization.DataView.prototype.getColumnProperty = function(columnIndex, property){}; google.visualization.DataView.prototype.getColumnProperties = function(columnIndex){}; google.visualization.DataView.prototype.getTableProperty = function(property){}; google.visualization.DataView.prototype.getTableProperties = function(){}; google.visualization.DataView.prototype.getRowProperty = function(rowIndex, property){}; google.visualization.DataView.prototype.getRowProperties = function(rowIndex){}; google.visualization.DataView.prototype.getColumnRange = function(columnIndex){}; google.visualization.DataView.prototype.getDistinctValues = function(columnIndex){}; google.visualization.DataView.prototype.getSortedRows = function(sortColumns){}; google.visualization.DataView.prototype.getFilteredRows = function(columnFilters){}; google.visualization.formatters = {}; google.visualization.formatters.ArrowFormat = function(opt_options){}; google.visualization.formatters.ArrowFormat.prototype.format = function(dataTable, columnIndex){}; google.visualization.formatters.BarFormat = function(opt_options){}; google.visualization.formatters.BarFormat.prototype.format = function(dataTable, columnIndex){}; google.visualization.formatters.ColorFormat = function(){}; google.visualization.formatters.ColorFormat.prototype.addRange = function(from, to, color, bgcolor){}; google.visualization.formatters.ColorFormat.prototype.addGradientRange = function(from, to, color, fromBgColor, toBgColor){}; google.visualization.formatters.ColorFormat.prototype.format = function(dataTable, columnIndex){}; google.visualization.formatters.DateFormat = function(opt_options){}; google.visualization.formatters.DateFormat.prototype.format = function(dataTable, columnIndex){}; google.visualization.formatters.NumberFormat = function(opt_options){}; google.visualization.formatters.NumberFormat.prototype.format = function(dataTable, columnIndex){}; google.visualization.formatters.PatternFormat = function(pattern){}; google.visualization.formatters.PatternFormat.prototype.format = function(dataTable, srcColumnIndices, opt_dstColumnIndex){}; google.visualization.GadgetHelper = function(){}; google.visualization.GadgetHelper.prototype.createQueryFromPrefs = function(prefs){}; google.visualization.GadgetHelper.prototype.validateResponse = function(response) {}; google.visualization.AnnotatedTimeLine = function(container){}; google.visualization.AnnotatedTimeLine.prototype.draw = function(data, options){}; google.visualization.AnnotatedTimeLine.prototype.getSelection = function(){}; google.visualization.AnnotatedTimeLine.prototype.getVisibleChartRange = function(){}; google.visualization.AnnotatedTimeLine.prototype.setVisibleChartRange = function(firstDate, lastDate, opt_animate){}; google.visualization.AnnotatedTimeLine.prototype.showDataColumns = function(columnIndexes){}; google.visualization.AnnotatedTimeLine.prototype.hideDataColumns = function(columnIndexes){}; google.visualization.AreaChart = function(container){}; google.visualization.AreaChart.prototype.draw = function(data, options){}; google.visualization.BarChart = function(container){}; google.visualization.BarChart.prototype.draw = function(data, options){}; google.visualization.ColumnChart = function(container){}; google.visualization.ColumnChart.prototype.draw = function(data, options){}; google.visualization.Gauge = function(container){}; google.visualization.Gauge.prototype.draw = function(dataTable, opt_options){}; google.visualization.GeoMap = function(container){}; google.visualization.GeoMap.clickOnRegion = function(id, zoomLevel, segmentBy, instanceIndex){}; google.visualization.GeoMap.prototype.setSelection = function(selection){}; google.visualization.GeoMap.prototype.getSelection = function(){}; google.visualization.GeoMap.prototype.draw = function(dataTable, options){}; google.visualization.Map = function(container){}; google.visualization.Map.prototype.draw = function(dataTable, options){}; google.visualization.Map.prototype.setSelection = function(selection){}; google.visualization.Map.prototype.getSelection = function(){}; google.visualization.ImageAreaChart = function(container){}; google.visualization.ImageAreaChart.prototype.draw = function(data, options){}; google.visualization.ImageBarChart = function(container){}; google.visualization.ImageBarChart.prototype.draw = function(data, options){}; google.visualization.ImageChart = function(container){}; google.visualization.ImageChart.prototype.draw = function(data, options){}; google.visualization.ImageLineChart = function(container){}; google.visualization.ImageLineChart.prototype.draw = function(data, options){}; google.visualization.ImagePieChart = function(container){}; google.visualization.ImagePieChart.prototype.draw = function(data, options){}; google.visualization.ImageSparkLine = function(container, opt_domHelper){}; google.visualization.ImageSparkLine.prototype.getSelection = function(){}; google.visualization.ImageSparkLine.prototype.setSelection = function(selection){}; google.visualization.ImageSparkLine.prototype.draw = function(dataTable, options){}; google.visualization.IntensityMap = function(container){}; google.visualization.IntensityMap.prototype.getSelection = function(){}; google.visualization.IntensityMap.prototype.setSelection = function(selection){}; google.visualization.IntensityMap.prototype.draw = function(dataTable, options){}; google.visualization.LineChart = function(container){}; google.visualization.LineChart.prototype.draw = function(data, options){}; google.visualization.MotionChart = function(container){}; google.visualization.MotionChart.prototype.draw = function(dataTable, options){}; google.visualization.MotionChart.prototype.getState = function(){}; google.visualization.PieChart = function(container){}; google.visualization.PieChart.prototype.draw = function(data, options){}; google.visualization.ScatterChart = function(container){}; google.visualization.ScatterChart.prototype.draw = function(data, options){}; google.visualization.OrgChart = function(container){}; google.visualization.OrgChart.prototype.draw = function(dataTable, options){}; google.visualization.OrgChart.prototype.getSelection = function(){}; google.visualization.OrgChart.prototype.setSelection = function(selection){}; google.visualization.OrgChart.prototype.getCollapsedNodes = function(){}; google.visualization.OrgChart.prototype.getChildrenIndexes = function(rowInd){}; google.visualization.OrgChart.prototype.collapse = function(rowInd, collapse){}; google.visualization.Table = function(container){}; google.visualization.Table.prototype.draw = function(dataTable, options){}; google.visualization.Table.prototype.getSortInfo = function(){}; google.visualization.Table.prototype.getSelection = function(){}; google.visualization.Table.prototype.setSelection = function(selection){}; google.visualization.drawToolbar = function(container, components){}; google.visualization.Player = function(container){}; google.visualization.Player.prototype.draw = function(options){};
{ "content_hash": "6e20acaa54f1fff04e1b672b231e62d3", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 132, "avg_line_length": 65.98326359832636, "alnum_prop": 0.8201014584654407, "repo_name": "eatshopsleep/Eat-Shop-Sleep", "id": "7725d1ff1a40b6dff04a7e7d90e9ecea4abd4d01", "size": "15770", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Resources/gviz-api.js", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Form Validation Class * * @package CodeIgniter * @subpackage Libraries * @category Validation * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/form_validation.html */ class CI_Form_validation { /** * Reference to the CodeIgniter instance * * @var object */ protected $CI; /** * Validation data for the current form submission * * @var array */ protected $_field_data = array(); /** * Validation rules for the current form * * @var array */ protected $_config_rules = array(); /** * Array of validation errors * * @var array */ protected $_error_array = array(); /** * Array of custom error messages * * @var array */ protected $_error_messages = array(); /** * Start tag for error wrapping * * @var string */ protected $_error_prefix = '<p>'; /** * End tag for error wrapping * * @var string */ protected $_error_suffix = '</p>'; /** * Custom error message * * @var string */ protected $error_string = ''; /** * Whether the form data has been validated as safe * * @var bool */ protected $_safe_form_data = FALSE; /** * Custom data to validate * * @var array */ public $validation_data = array(); /** * Initialize Form_Validation class * * @param array $rules * @return void */ public function __construct($rules = array()) { $this->CI =& get_instance(); // applies delimiters set in config file. if (isset($rules['error_prefix'])) { $this->_error_prefix = $rules['error_prefix']; unset($rules['error_prefix']); } if (isset($rules['error_suffix'])) { $this->_error_suffix = $rules['error_suffix']; unset($rules['error_suffix']); } // Validation rules can be stored in a config file. $this->_config_rules = $rules; // Automatically load the form helper $this->CI->load->helper('form'); log_message('info', 'Form Validation Class Initialized'); } // -------------------------------------------------------------------- /** * Set Rules * * This function takes an array of field names and validation * rules as input, any custom error messages, validates the info, * and stores it * * @param mixed $field * @param string $label * @param mixed $rules * @param array $errors * @return CI_Form_validation */ public function set_rules($field, $label = '', $rules = array(), $errors = array()) { // No reason to set rules if we have no POST data // or a validation array has not been specified if ($this->CI->input->method() !== 'post' && empty($this->validation_data)) { return $this; } // If an array was passed via the first parameter instead of individual string // values we cycle through it and recursively call this function. if (is_array($field)) { foreach ($field as $row) { // Houston, we have a problem... if ( ! isset($row['field'], $row['rules'])) { continue; } // If the field label wasn't passed we use the field name $label = isset($row['label']) ? $row['label'] : $row['field']; // Add the custom error message array $errors = (isset($row['errors']) && is_array($row['errors'])) ? $row['errors'] : array(); // Here we go! $this->set_rules($row['field'], $label, $row['rules'], $errors); } return $this; } // No fields? Nothing to do... if ( ! is_string($field) OR $field === '') { return $this; } elseif ( ! is_array($rules)) { // BC: Convert pipe-separated rules string to an array if (is_string($rules)) { $rules = explode('|', $rules); } else { return $this; } } // If the field label wasn't passed we use the field name $label = ($label === '') ? $field : $label; $indexes = array(); // Is the field name an array? If it is an array, we break it apart // into its components so that we can fetch the corresponding POST data later if (($is_array = (bool) preg_match_all('/\[(.*?)\]/', $field, $matches)) === TRUE) { sscanf($field, '%[^[][', $indexes[0]); for ($i = 0, $c = count($matches[0]); $i < $c; $i++) { if ($matches[1][$i] !== '') { $indexes[] = $matches[1][$i]; } } } // Build our master array $this->_field_data[$field] = array( 'field' => $field, 'label' => $label, 'rules' => $rules, 'errors' => $errors, 'is_array' => $is_array, 'keys' => $indexes, 'postdata' => NULL, 'error' => '' ); return $this; } // -------------------------------------------------------------------- /** * By default, form validation uses the $_POST array to validate * * If an array is set through this method, then this array will * be used instead of the $_POST array * * Note that if you are validating multiple arrays, then the * reset_validation() function should be called after validating * each array due to the limitations of CI's singleton * * @param array $data * @return CI_Form_validation */ public function set_data(array $data) { if ( ! empty($data)) { $this->validation_data = $data; } return $this; } // -------------------------------------------------------------------- /** * Set Error Message * * Lets users set their own error messages on the fly. Note: * The key name has to match the function name that it corresponds to. * * @param array * @param string * @return CI_Form_validation */ public function set_message($lang, $val = '') { if ( ! is_array($lang)) { $lang = array($lang => $val); } $this->_error_messages = array_merge($this->_error_messages, $lang); return $this; } // -------------------------------------------------------------------- /** * Set The Error Delimiter * * Permits a prefix/suffix to be added to each error message * * @param string * @param string * @return CI_Form_validation */ public function set_error_delimiters($prefix = '<p>', $suffix = '</p>') { $this->_error_prefix = $prefix; $this->_error_suffix = $suffix; return $this; } // -------------------------------------------------------------------- /** * Get Error Message * * Gets the error message associated with a particular field * * @param string $field Field name * @param string $prefix HTML start tag * @param string $suffix HTML end tag * @return string */ public function error($field, $prefix = '', $suffix = '') { if (empty($this->_field_data[$field]['error'])) { return ''; } if ($prefix === '') { $prefix = $this->_error_prefix; } if ($suffix === '') { $suffix = $this->_error_suffix; } return $prefix.$this->_field_data[$field]['error'].$suffix; } // -------------------------------------------------------------------- /** * Get Array of Error Messages * * Returns the error messages as an array * * @return array */ public function error_array() { return $this->_error_array; } // -------------------------------------------------------------------- /** * Error String * * Returns the error messages as a string, wrapped in the error delimiters * * @param string * @param string * @return string */ public function error_string($prefix = '', $suffix = '') { // No errors, validation passes! if (count($this->_error_array) === 0) { return ''; } if ($prefix === '') { $prefix = $this->_error_prefix; } if ($suffix === '') { $suffix = $this->_error_suffix; } // Generate the error string $str = ''; foreach ($this->_error_array as $val) { if ($val !== '') { $str .= $prefix.$val.$suffix."\n"; } } return $str; } // -------------------------------------------------------------------- /** * Run the Validator * * This function does all the work. * * @param string $group * @return bool */ public function run($group = '') { // Do we even have any data to process? Mm? $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data; if (count($validation_array) === 0) { return FALSE; } // Does the _field_data array containing the validation rules exist? // If not, we look to see if they were assigned via a config file if (count($this->_field_data) === 0) { // No validation rules? We're done... if (count($this->_config_rules) === 0) { return FALSE; } if (empty($group)) { // Is there a validation rule for the particular URI being accessed? $group = trim($this->CI->uri->ruri_string(), '/'); isset($this->_config_rules[$group]) OR $group = $this->CI->router->class.'/'.$this->CI->router->method; } $this->set_rules(isset($this->_config_rules[$group]) ? $this->_config_rules[$group] : $this->_config_rules); // Were we able to set the rules correctly? if (count($this->_field_data) === 0) { log_message('debug', 'Unable to find validation rules'); return FALSE; } } // Load the language file containing error messages $this->CI->lang->load('form_validation'); // Cycle through the rules for each field and match the corresponding $validation_data item foreach ($this->_field_data as $field => $row) { // Fetch the data from the validation_data array item and cache it in the _field_data array. // Depending on whether the field name is an array or a string will determine where we get it from. if ($row['is_array'] === TRUE) { $this->_field_data[$field]['postdata'] = $this->_reduce_array($validation_array, $row['keys']); } elseif (isset($validation_array[$field]) && $validation_array[$field] !== '') { $this->_field_data[$field]['postdata'] = $validation_array[$field]; } } // Execute validation rules // Note: A second foreach (for now) is required in order to avoid false-positives // for rules like 'matches', which correlate to other validation fields. foreach ($this->_field_data as $field => $row) { // Don't try to validate if we have no rules set if (empty($row['rules'])) { continue; } $this->_execute($row, $row['rules'], $this->_field_data[$field]['postdata']); } // Did we end up with any errors? $total_errors = count($this->_error_array); if ($total_errors > 0) { $this->_safe_form_data = TRUE; } // Now we need to re-set the POST data with the new, processed data $this->_reset_post_array(); return ($total_errors === 0); } // -------------------------------------------------------------------- /** * Traverse a multidimensional $_POST array index until the data is found * * @param array * @param array * @param int * @return mixed */ protected function _reduce_array($array, $keys, $i = 0) { if (is_array($array) && isset($keys[$i])) { return isset($array[$keys[$i]]) ? $this->_reduce_array($array[$keys[$i]], $keys, ($i+1)) : NULL; } // NULL must be returned for empty fields return ($array === '') ? NULL : $array; } // -------------------------------------------------------------------- /** * Re-populate the _POST array with our finalized and processed data * * @return void */ protected function _reset_post_array() { foreach ($this->_field_data as $field => $row) { if ($row['postdata'] !== NULL) { if ($row['is_array'] === FALSE) { if (isset($_POST[$row['field']])) { $_POST[$row['field']] = $row['postdata']; } } else { // start with a reference $post_ref =& $_POST; // before we assign values, make a reference to the right POST key if (count($row['keys']) === 1) { $post_ref =& $post_ref[current($row['keys'])]; } else { foreach ($row['keys'] as $val) { $post_ref =& $post_ref[$val]; } } if (is_array($row['postdata'])) { $array = array(); foreach ($row['postdata'] as $k => $v) { $array[$k] = $v; } $post_ref = $array; } else { $post_ref = $row['postdata']; } } } } } // -------------------------------------------------------------------- /** * Executes the Validation routines * * @param array * @param array * @param mixed * @param int * @return mixed */ protected function _execute($row, $rules, $postdata = NULL, $cycles = 0) { // If the $_POST data is an array we will run a recursive call if (is_array($postdata)) { foreach ($postdata as $key => $val) { $this->_execute($row, $rules, $val, $key); } return; } // If the field is blank, but NOT required, no further tests are necessary $callback = FALSE; if ( ! in_array('required', $rules) && ($postdata === NULL OR $postdata === '')) { // Before we bail out, does the rule contain a callback? foreach ($rules as &$rule) { if (is_string($rule)) { if (strncmp($rule, 'callback_', 9) === 0) { $callback = TRUE; $rules = array(1 => $rule); break; } } elseif (is_callable($rule)) { $callback = TRUE; $rules = array(1 => $rule); break; } } if ( ! $callback) { return; } } // Isset Test. Typically this rule will only apply to checkboxes. if (($postdata === NULL OR $postdata === '') && ! $callback) { if (in_array('isset', $rules, TRUE) OR in_array('required', $rules)) { // Set the message type $type = in_array('required', $rules) ? 'required' : 'isset'; // Check if a custom message is defined if (isset($this->_field_data[$row['field']]['errors'][$type])) { $line = $this->_field_data[$row['field']]['errors'][$type]; } elseif (isset($this->_error_messages[$type])) { $line = $this->_error_messages[$type]; } elseif (FALSE === ($line = $this->CI->lang->line('form_validation_'.$type)) // DEPRECATED support for non-prefixed keys && FALSE === ($line = $this->CI->lang->line($type, FALSE))) { $line = 'The field was not set'; } // Build the error message $message = $this->_build_error_msg($line, $this->_translate_fieldname($row['label'])); // Save the error message $this->_field_data[$row['field']]['error'] = $message; if ( ! isset($this->_error_array[$row['field']])) { $this->_error_array[$row['field']] = $message; } } return; } // -------------------------------------------------------------------- // Cycle through each rule and run it foreach ($rules as $rule) { $_in_array = FALSE; // We set the $postdata variable with the current data in our master array so that // each cycle of the loop is dealing with the processed data from the last cycle if ($row['is_array'] === TRUE && is_array($this->_field_data[$row['field']]['postdata'])) { // We shouldn't need this safety, but just in case there isn't an array index // associated with this cycle we'll bail out if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles])) { continue; } $postdata = $this->_field_data[$row['field']]['postdata'][$cycles]; $_in_array = TRUE; } else { // If we get an array field, but it's not expected - then it is most likely // somebody messing with the form on the client side, so we'll just consider // it an empty field $postdata = is_array($this->_field_data[$row['field']]['postdata']) ? NULL : $this->_field_data[$row['field']]['postdata']; } // Is the rule a callback? $callback = $callable = FALSE; if (is_string($rule)) { if (strpos($rule, 'callback_') === 0) { $rule = substr($rule, 9); $callback = TRUE; } } elseif (is_callable($rule)) { $callable = TRUE; } elseif (is_array($rule) && isset($rule[0], $rule[1]) && is_callable($rule[1])) { // We have a "named" callable, so save the name $callable = $rule[0]; $rule = $rule[1]; } // Strip the parameter (if exists) from the rule // Rules can contain a parameter: max_length[5] $param = FALSE; if ( ! $callable && preg_match('/(.*?)\[(.*)\]/', $rule, $match)) { $rule = $match[1]; $param = $match[2]; } // Call the function that corresponds to the rule if ($callback OR $callable !== FALSE) { if ($callback) { if ( ! method_exists($this->CI, $rule)) { log_message('debug', 'Unable to find callback validation rule: '.$rule); $result = FALSE; } else { // Run the function and grab the result $result = $this->CI->$rule($postdata, $param); } } else { $result = is_array($rule) ? $rule[0]->{$rule[1]}($postdata) : $rule($postdata); // Is $callable set to a rule name? if ($callable !== FALSE) { $rule = $callable; } } // Re-assign the result to the master data array if ($_in_array === TRUE) { $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } // If the field isn't required and we just processed a callback we'll move on... if ( ! in_array('required', $rules, TRUE) && $result !== FALSE) { continue; } } elseif ( ! method_exists($this, $rule)) { // If our own wrapper function doesn't exist we see if a native PHP function does. // Users can use any native PHP function call that has one param. if (function_exists($rule)) { // Native PHP functions issue warnings if you pass them more parameters than they use $result = ($param !== FALSE) ? $rule($postdata, $param) : $rule($postdata); if ($_in_array === TRUE) { $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } } else { log_message('debug', 'Unable to find validation rule: '.$rule); $result = FALSE; } } else { $result = $this->$rule($postdata, $param); if ($_in_array === TRUE) { $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } } // Did the rule test negatively? If so, grab the error. if ($result === FALSE) { // Callable rules might not have named error messages if ( ! is_string($rule)) { return; } // Check if a custom message is defined if (isset($this->_field_data[$row['field']]['errors'][$rule])) { $line = $this->_field_data[$row['field']]['errors'][$rule]; } elseif ( ! isset($this->_error_messages[$rule])) { if (FALSE === ($line = $this->CI->lang->line('form_validation_'.$rule)) // DEPRECATED support for non-prefixed keys && FALSE === ($line = $this->CI->lang->line($rule, FALSE))) { $line = $this->CI->lang->line('form_validation_error_message_not_set').'('.$rule.')'; } } else { $line = $this->_error_messages[$rule]; } // Is the parameter we are inserting into the error message the name // of another field? If so we need to grab its "field label" if (isset($this->_field_data[$param], $this->_field_data[$param]['label'])) { $param = $this->_translate_fieldname($this->_field_data[$param]['label']); } // Build the error message $message = $this->_build_error_msg($line, $this->_translate_fieldname($row['label']), $param); // Save the error message $this->_field_data[$row['field']]['error'] = $message; if ( ! isset($this->_error_array[$row['field']])) { $this->_error_array[$row['field']] = $message; } return; } } } // -------------------------------------------------------------------- /** * Translate a field name * * @param string the field name * @return string */ protected function _translate_fieldname($fieldname) { // Do we need to translate the field name? // We look for the prefix lang: to determine this if (sscanf($fieldname, 'lang:%s', $line) === 1) { // Were we able to translate the field name? If not we use $line if (FALSE === ($fieldname = $this->CI->lang->line('form_validation_'.$line)) // DEPRECATED support for non-prefixed keys && FALSE === ($fieldname = $this->CI->lang->line($line, FALSE))) { return $line; } } return $fieldname; } // -------------------------------------------------------------------- /** * Build an error message using the field and param. * * @param string The error message line * @param string A field's human name * @param mixed A rule's optional parameter * @return string */ protected function _build_error_msg($line, $field = '', $param = '') { // Check for %s in the string for legacy support. if (strpos($line, '%s') !== FALSE) { return sprintf($line, $field, $param); } return str_replace(array('{field}', '{param}'), array($field, $param), $line); } // -------------------------------------------------------------------- /** * Checks if the rule is present within the validator * * Permits you to check if a rule is present within the validator * * @param string the field name * @return bool */ public function has_rule($field) { return isset($this->_field_data[$field]); } // -------------------------------------------------------------------- /** * Get the value from a form * * Permits you to repopulate a form field with the value it was submitted * with, or, if that value doesn't exist, with the default * * @param string the field name * @param string * @return string */ public function set_value($field = '', $default = '') { if ( ! isset($this->_field_data[$field], $this->_field_data[$field]['postdata'])) { return $default; } // If the data is an array output them one at a time. // E.g: form_input('name[]', set_value('name[]'); if (is_array($this->_field_data[$field]['postdata'])) { return array_shift($this->_field_data[$field]['postdata']); } return $this->_field_data[$field]['postdata']; } // -------------------------------------------------------------------- /** * Set Select * * Enables pull-down lists to be set to the value the user * selected in the event of an error * * @param string * @param string * @param bool * @return string */ public function set_select($field = '', $value = '', $default = FALSE) { if ( ! isset($this->_field_data[$field], $this->_field_data[$field]['postdata'])) { return ($default === TRUE && count($this->_field_data) === 0) ? ' selected="selected"' : ''; } $field = $this->_field_data[$field]['postdata']; $value = (string) $value; if (is_array($field)) { // Note: in_array('', array(0)) returns TRUE, do not use it foreach ($field as &$v) { if ($value === $v) { return ' selected="selected"'; } } return ''; } elseif (($field === '' OR $value === '') OR ($field !== $value)) { return ''; } return ' selected="selected"'; } // -------------------------------------------------------------------- /** * Set Radio * * Enables radio buttons to be set to the value the user * selected in the event of an error * * @param string * @param string * @param bool * @return string */ public function set_radio($field = '', $value = '', $default = FALSE) { if ( ! isset($this->_field_data[$field], $this->_field_data[$field]['postdata'])) { return ($default === TRUE && count($this->_field_data) === 0) ? ' checked="checked"' : ''; } $field = $this->_field_data[$field]['postdata']; $value = (string) $value; if (is_array($field)) { // Note: in_array('', array(0)) returns TRUE, do not use it foreach ($field as &$v) { if ($value === $v) { return ' checked="checked"'; } } return ''; } elseif (($field === '' OR $value === '') OR ($field !== $value)) { return ''; } return ' checked="checked"'; } // -------------------------------------------------------------------- /** * Set Checkbox * * Enables checkboxes to be set to the value the user * selected in the event of an error * * @param string * @param string * @param bool * @return string */ public function set_checkbox($field = '', $value = '', $default = FALSE) { // Logic is exactly the same as for radio fields return $this->set_radio($field, $value, $default); } // -------------------------------------------------------------------- /** * Required * * @param string * @return bool */ public function required($str) { return is_array($str) ? (bool) count($str) : (trim($str) !== ''); } // -------------------------------------------------------------------- /** * Performs a Regular Expression match test. * * @param string * @param string regex * @return bool */ public function regex_match($str, $regex) { return (bool) preg_match($regex, $str); } // -------------------------------------------------------------------- /** * Match one field to another * * @param string $str string to compare against * @param string $field * @return bool */ public function matches($str, $field) { return isset($this->_field_data[$field], $this->_field_data[$field]['postdata']) ? ($str === $this->_field_data[$field]['postdata']) : FALSE; } // -------------------------------------------------------------------- /** * Differs from another field * * @param string * @param string field * @return bool */ public function differs($str, $field) { return ! (isset($this->_field_data[$field]) && $this->_field_data[$field]['postdata'] === $str); } // -------------------------------------------------------------------- /** * Is Unique * * Check if the input value doesn't already exist * in the specified database field. * * @param string $str * @param string $field * @return bool */ public function is_unique($str, $field) { sscanf($field, '%[^.].%[^.]', $table, $field); return isset($this->CI->db) ? ($this->CI->db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0) : FALSE; } // -------------------------------------------------------------------- /** * Minimum Length * * @param string * @param string * @return bool */ public function min_length($str, $val) { if ( ! is_numeric($val)) { return FALSE; } return ($val <= mb_strlen($str)); } // -------------------------------------------------------------------- /** * Max Length * * @param string * @param string * @return bool */ public function max_length($str, $val) { if ( ! is_numeric($val)) { return FALSE; } return ($val >= mb_strlen($str)); } // -------------------------------------------------------------------- /** * Exact Length * * @param string * @param string * @return bool */ public function exact_length($str, $val) { if ( ! is_numeric($val)) { return FALSE; } return (mb_strlen($str) === (int) $val); } // -------------------------------------------------------------------- /** * Valid URL * * @param string $str * @return bool */ public function valid_url($str) { if (empty($str)) { return FALSE; } elseif (preg_match('/^(?:([^:]*)\:)?\/\/(.+)$/', $str, $matches)) { if (empty($matches[2])) { return FALSE; } elseif ( ! in_array($matches[1], array('http', 'https'), TRUE)) { return FALSE; } $str = $matches[2]; } $str = 'http://'.$str; // There's a bug affecting PHP 5.2.13, 5.3.2 that considers the // underscore to be a valid hostname character instead of a dash. // Reference: https://bugs.php.net/bug.php?id=51192 if (version_compare(PHP_VERSION, '5.2.13', '==') OR version_compare(PHP_VERSION, '5.3.2', '==')) { sscanf($str, 'http://%[^/]', $host); $str = substr_replace($str, strtr($host, array('_' => '-', '-' => '_')), 7, strlen($host)); } return (filter_var($str, FILTER_VALIDATE_URL) !== FALSE); } // -------------------------------------------------------------------- /** * Valid Email * * @param string * @return bool */ public function valid_email($str) { if (function_exists('idn_to_ascii') && $atpos = strpos($str, '@')) { $str = substr($str, 0, ++$atpos).idn_to_ascii(substr($str, $atpos)); } return (bool) filter_var($str, FILTER_VALIDATE_EMAIL); } // -------------------------------------------------------------------- /** * Valid Emails * * @param string * @return bool */ public function valid_emails($str) { if (strpos($str, ',') === FALSE) { return $this->valid_email(trim($str)); } foreach (explode(',', $str) as $email) { if (trim($email) !== '' && $this->valid_email(trim($email)) === FALSE) { return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * Validate IP Address * * @param string * @param string 'ipv4' or 'ipv6' to validate a specific IP format * @return bool */ public function valid_ip($ip, $which = '') { return $this->CI->input->valid_ip($ip, $which); } // -------------------------------------------------------------------- /** * Alpha * * @param string * @return bool */ public function alpha($str) { return ctype_alpha($str); } // -------------------------------------------------------------------- /** * Alpha-numeric * * @param string * @return bool */ public function alpha_numeric($str) { return ctype_alnum((string) $str); } // -------------------------------------------------------------------- /** * Alpha-numeric w/ spaces * * @param string * @return bool */ public function alpha_numeric_spaces($str) { return (bool) preg_match('/^[A-Z0-9 ]+$/i', $str); } // -------------------------------------------------------------------- /** * Alpha-numeric with underscores and dashes * * @param string * @return bool */ public function alpha_dash($str) { return (bool) preg_match('/^[a-z0-9_-]+$/i', $str); } // -------------------------------------------------------------------- /** * Numeric * * @param string * @return bool */ public function numeric($str) { return (bool) preg_match('/^[\-+]?[0-9]*\.?[0-9]+$/', $str); } // -------------------------------------------------------------------- /** * Integer * * @param string * @return bool */ public function integer($str) { return (bool) preg_match('/^[\-+]?[0-9]+$/', $str); } // -------------------------------------------------------------------- /** * Decimal number * * @param string * @return bool */ public function decimal($str) { return (bool) preg_match('/^[\-+]?[0-9]+\.[0-9]+$/', $str); } // -------------------------------------------------------------------- /** * Greater than * * @param string * @param int * @return bool */ public function greater_than($str, $min) { return is_numeric($str) ? ($str > $min) : FALSE; } // -------------------------------------------------------------------- /** * Equal to or Greater than * * @param string * @param int * @return bool */ public function greater_than_equal_to($str, $min) { return is_numeric($str) ? ($str >= $min) : FALSE; } // -------------------------------------------------------------------- /** * Less than * * @param string * @param int * @return bool */ public function less_than($str, $max) { return is_numeric($str) ? ($str < $max) : FALSE; } // -------------------------------------------------------------------- /** * Equal to or Less than * * @param string * @param int * @return bool */ public function less_than_equal_to($str, $max) { return is_numeric($str) ? ($str <= $max) : FALSE; } // -------------------------------------------------------------------- /** * Value should be within an array of values * * @param string * @param string * @return bool */ public function in_list($value, $list) { return in_array($value, explode(',', $list), TRUE); } // -------------------------------------------------------------------- /** * Is a Natural number (0,1,2,3, etc.) * * @param string * @return bool */ public function is_natural($str) { return ctype_digit((string) $str); } // -------------------------------------------------------------------- /** * Is a Natural number, but not a zero (1,2,3, etc.) * * @param string * @return bool */ public function is_natural_no_zero($str) { return ($str != 0 && ctype_digit((string) $str)); } // -------------------------------------------------------------------- /** * Valid Base64 * * Tests a string for characters outside of the Base64 alphabet * as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045 * * @param string * @return bool */ public function valid_base64($str) { return (base64_encode(base64_decode($str)) === $str); } // -------------------------------------------------------------------- /** * Prep data for form * * This function allows HTML to be safely shown in a form. * Special characters are converted. * * @param string * @return string */ public function prep_for_form($data = '') { if ($this->_safe_form_data === FALSE OR empty($data)) { return $data; } if (is_array($data)) { foreach ($data as $key => $val) { $data[$key] = $this->prep_for_form($val); } return $data; } return str_replace(array("'", '"', '<', '>'), array('&#39;', '&quot;', '&lt;', '&gt;'), stripslashes($data)); } // -------------------------------------------------------------------- /** * Prep URL * * @param string * @return string */ public function prep_url($str = '') { if ($str === 'http://' OR $str === '') { return ''; } if (strpos($str, 'http://') !== 0 && strpos($str, 'https://') !== 0) { return 'http://'.$str; } return $str; } // -------------------------------------------------------------------- /** * Strip Image Tags * * @param string * @return string */ public function strip_image_tags($str) { return $this->CI->security->strip_image_tags($str); } // -------------------------------------------------------------------- /** * Convert PHP tags to entities * * @param string * @return string */ public function encode_php_tags($str) { return str_replace(array('<?', '?>'), array('&lt;?', '?&gt;'), $str); } // -------------------------------------------------------------------- /** * Reset validation vars * * Prevents subsequent validation routines from being affected by the * results of any previous validation routine due to the CI singleton. * * @return CI_Form_validation */ public function reset_validation() { $this->_field_data = array(); $this->_config_rules = array(); $this->_error_array = array(); $this->_error_messages = array(); $this->error_string = ''; return $this; } }
{ "content_hash": "435fc1d6745e779dd0ee4416600e875f", "timestamp": "", "source": "github", "line_count": 1564, "max_line_length": 111, "avg_line_length": 23.706521739130434, "alnum_prop": 0.4891981551905494, "repo_name": "sygcom/rhsports", "id": "7b7d733a2c7905087c2f8797c2c875d241759700", "size": "38770", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "system/libraries/Form_validation.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "43125" }, { "name": "CSS", "bytes": "2688285" }, { "name": "HTML", "bytes": "5616695" }, { "name": "JavaScript", "bytes": "83801" }, { "name": "PHP", "bytes": "6572631" }, { "name": "Shell", "bytes": "238" }, { "name": "XSLT", "bytes": "11420" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; #if !SILVERLIGHT using System.Data; #endif using System.Globalization; using System.IO; using System.Reflection; using System.Reflection.Emit; namespace fastJSON { public delegate string Serialize(object data); public delegate object Deserialize(string data); public sealed class JSONParameters { /// <summary> /// Use the optimized fast Dataset Schema format (default = True) /// </summary> public bool UseOptimizedDatasetSchema = true; /// <summary> /// Use the fast GUID format (default = True) /// </summary> public bool UseFastGuid = true; /// <summary> /// Serialize null values to the output (default = True) /// </summary> public bool SerializeNullValues = true; /// <summary> /// Use the UTC date format (default = True) /// </summary> public bool UseUTCDateTime = true; /// <summary> /// Show the readonly properties of types in the output (default = False) /// </summary> public bool ShowReadOnlyProperties = false; /// <summary> /// Use the $types extension to optimise the output json (default = True) /// </summary> public bool UsingGlobalTypes = true; /// <summary> /// ** work in progress /// </summary> public bool IgnoreCaseOnDeserialize = false; /// <summary> /// Anonymous types have read only properties /// </summary> public bool EnableAnonymousTypes = false; /// <summary> /// Enable fastJSON extensions $types, $type, $map (default = True) /// </summary> public bool UseExtensions = true; /// <summary> /// Use escaped unicode i.e. \uXXXX format for non ASCII characters (default = True) /// </summary> public bool UseEscapedUnicode = true; public void FixValues() { if (UseExtensions == false) // disable conflicting params { UsingGlobalTypes = false; } } } public sealed class JSON { //public readonly static JSON Instance = new JSON(); [ThreadStatic] private static JSON _instance; public static JSON Instance { get { return _instance ?? (_instance = new JSON()); } } private JSON() { } /// <summary> /// You can set these paramters globally for all calls /// </summary> public JSONParameters Parameters = new JSONParameters(); private JSONParameters _params; public string ToJSON(object obj) { _params = Parameters; _params.FixValues(); Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties; return ToJSON(obj, Parameters); } public string ToJSON(object obj, JSONParameters param) { _params = param; _params.FixValues(); Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties; Type t = null; if (obj == null) return "null"; if (obj.GetType().IsGenericType) t = obj.GetType().GetGenericTypeDefinition(); if (t == typeof(Dictionary<,>) || t == typeof(List<>)) _params.UsingGlobalTypes = false; // FEATURE : enable extensions when you can deserialize anon types if (_params.EnableAnonymousTypes) { _params.UseExtensions = false; _params.UsingGlobalTypes = false; Reflection.Instance.ShowReadOnlyProperties = true; } _usingglobals = _params.UsingGlobalTypes; return new JSONSerializer(_params).ConvertToJSON(obj); } public object Parse(string json) { _params = Parameters; Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties; return new JsonParser(json, _params.IgnoreCaseOnDeserialize).Decode(); } public T ToObject<T>(string json) { return (T)ToObject(json, typeof(T)); } public object ToObject(string json) { return ToObject(json, null); } public object ToObject(string json, Type type) { _params = Parameters; _params.FixValues(); Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties; Type t = null; if (type != null && type.IsGenericType) t = type.GetGenericTypeDefinition(); if (t == typeof(Dictionary<,>) || t == typeof(List<>)) _params.UsingGlobalTypes = false; _usingglobals = _params.UsingGlobalTypes; object o = new JsonParser(json, Parameters.IgnoreCaseOnDeserialize).Decode(); if (o == null) return null; #if !SILVERLIGHT if (type != null && type == typeof(DataSet)) return CreateDataset(o as Dictionary<string, object>, null); if (type != null && type == typeof(DataTable)) return CreateDataTable(o as Dictionary<string, object>, null); #endif if (o is IDictionary) { if (type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) // deserialize a dictionary return RootDictionary(o, type); else // deserialize an object return ParseDictionary(o as Dictionary<string, object>, null, type, null); } if (o is List<object>) { if (type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) // kv format return RootDictionary(o, type); if (type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) // deserialize to generic list return RootList(o, type); else return (o as List<object>).ToArray(); } if (type != null && o.GetType() != type) return ChangeType(o, type); return o; } public string Beautify(string input) { return Formatter.PrettyPrint(input); } public object FillObject(object input, string json) { _params = Parameters; _params.FixValues(); Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties; Dictionary<string, object> ht = new JsonParser(json, Parameters.IgnoreCaseOnDeserialize).Decode() as Dictionary<string, object>; if (ht == null) return null; return ParseDictionary(ht, null, input.GetType(), input); } public object DeepCopy(object obj) { return ToObject(ToJSON(obj)); } public T DeepCopy<T>(T obj) { return ToObject<T>(ToJSON(obj)); } internal SafeDictionary<Type, Serialize> _customSerializer = new SafeDictionary<Type, Serialize>(); internal SafeDictionary<Type, Deserialize> _customDeserializer = new SafeDictionary<Type, Deserialize>(); public void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { if (type != null && serializer != null && deserializer != null) { _customSerializer.Add(type, serializer); _customDeserializer.Add(type, deserializer); // reset property cache _propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>(); } } internal bool IsTypeRegistered(Type t) { if (_customSerializer.Count == 0) return false; Serialize s; return _customSerializer.TryGetValue(t, out s); } #region [ JSON specific reflection ] private enum myPropInfoType { Int, Long, String, Bool, DateTime, Enum, Guid, Array, ByteArray, Dictionary, StringDictionary, #if !SILVERLIGHT Hashtable, DataSet, DataTable, #endif Custom, Unknown, } [Flags] private enum myPropInfoFlags { Filled = 1 << 0, CanWrite = 1 << 1 } private struct myPropInfo { public Type pt; public Type bt; public Type changeType; public Reflection.GenericSetter setter; public Reflection.GenericGetter getter; public Type[] GenericTypes; public string Name; public myPropInfoType Type; public myPropInfoFlags Flags; public bool IsClass; public bool IsValueType; public bool IsGenericType; } SafeDictionary<string, SafeDictionary<string, myPropInfo>> _propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>(); private SafeDictionary<string, myPropInfo> Getproperties(Type type, string typename) { SafeDictionary<string, myPropInfo> sd = null; if (_propertycache.TryGetValue(typename, out sd)) { return sd; } else { sd = new SafeDictionary<string, myPropInfo>(); PropertyInfo[] pr = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in pr) { myPropInfo d = CreateMyProp(p.PropertyType, p.Name); d.Flags |= myPropInfoFlags.CanWrite; d.setter = Reflection.CreateSetMethod(type, p); d.getter = Reflection.CreateGetMethod(type, p); sd.Add(p.Name, d); } FieldInfo[] fi = type.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo f in fi) { myPropInfo d = CreateMyProp(f.FieldType, f.Name); d.setter = Reflection.CreateSetField(type, f); d.getter = Reflection.CreateGetField(type, f); sd.Add(f.Name, d); } _propertycache.Add(typename, sd); return sd; } } private myPropInfo CreateMyProp(Type t, string name) { myPropInfo d = new myPropInfo(); myPropInfoType d_type = myPropInfoType.Unknown; myPropInfoFlags d_flags = myPropInfoFlags.Filled | myPropInfoFlags.CanWrite; if (t == typeof(int) || t == typeof(int?)) d_type = myPropInfoType.Int; else if (t == typeof(long) || t == typeof(long?)) d_type = myPropInfoType.Long; else if (t == typeof(string)) d_type = myPropInfoType.String; else if (t == typeof(bool) || t == typeof(bool?)) d_type = myPropInfoType.Bool; else if (t == typeof(DateTime) || t == typeof(DateTime?)) d_type = myPropInfoType.DateTime; else if (t.IsEnum) d_type = myPropInfoType.Enum; else if (t == typeof(Guid) || t == typeof(Guid?)) d_type = myPropInfoType.Guid; else if (t.IsArray) { d.bt = t.GetElementType(); if (t == typeof(byte[])) d_type = myPropInfoType.ByteArray; else d_type = myPropInfoType.Array; } else if (t.Name.Contains("Dictionary")) { d.GenericTypes = t.GetGenericArguments(); if (d.GenericTypes.Length > 0 && d.GenericTypes[0] == typeof(string)) d_type = myPropInfoType.StringDictionary; else d_type = myPropInfoType.Dictionary; } #if !SILVERLIGHT else if (t == typeof(Hashtable)) d_type = myPropInfoType.Hashtable; else if (t == typeof(DataSet)) d_type = myPropInfoType.DataSet; else if (t == typeof(DataTable)) d_type = myPropInfoType.DataTable; #endif else if (IsTypeRegistered(t)) d_type = myPropInfoType.Custom; d.IsClass = t.IsClass; d.IsValueType = t.IsValueType; if (t.IsGenericType) { d.IsGenericType = true; d.bt = t.GetGenericArguments()[0]; } d.pt = t; d.Name = name; d.changeType = GetChangeType(t); d.Type = d_type; d.Flags = d_flags; return d; } private object ChangeType(object value, Type conversionType) { if (conversionType == typeof(int)) return (int)((long)value); else if (conversionType == typeof(long)) return (long)value; else if (conversionType == typeof(string)) return (string)value; else if (conversionType == typeof(Guid)) return CreateGuid((string)value); else if (conversionType.IsEnum) return CreateEnum(conversionType, (string)value); else if (IsTypeRegistered(conversionType)) return CreateCustom((string)value, conversionType); return Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture); } #endregion #region [ p r i v a t e m e t h o d s ] private object RootList(object parse, Type type) { Type[] gtypes = type.GetGenericArguments(); IList o = (IList)Reflection.Instance.FastCreateInstance(type); foreach (var k in (IList)parse) { _usingglobals = false; object v = k; if (k is Dictionary<string, object>) v = ParseDictionary(k as Dictionary<string, object>, null, gtypes[0], null); else v = ChangeType(k, gtypes[0]); o.Add(v); } return o; } private object RootDictionary(object parse, Type type) { Type[] gtypes = type.GetGenericArguments(); if (parse is Dictionary<string, object>) { IDictionary o = (IDictionary)Reflection.Instance.FastCreateInstance(type); foreach (var kv in (Dictionary<string, object>)parse) { object v; object k = ChangeType(kv.Key, gtypes[0]); if (kv.Value is Dictionary<string, object>) v = ParseDictionary(kv.Value as Dictionary<string, object>, null, gtypes[1], null); else if (kv.Value is List<object>) v = CreateArray(kv.Value as List<object>, typeof(object), typeof(object), null); else v = ChangeType(kv.Value, gtypes[1]); o.Add(k, v); } return o; } if (parse is List<object>) return CreateDictionary(parse as List<object>, type, gtypes, null); return null; } bool _usingglobals = false; private object ParseDictionary(Dictionary<string, object> d, Dictionary<string, object> globaltypes, Type type, object input) { object tn = ""; if (d.TryGetValue("$types", out tn)) { _usingglobals = true; globaltypes = new Dictionary<string, object>(); foreach (var kv in (Dictionary<string, object>)tn) { globaltypes.Add((string)kv.Value, kv.Key); } } bool found = d.TryGetValue("$type", out tn); #if !SILVERLIGHT if (found == false && type == typeof(System.Object)) { return CreateDataset(d, globaltypes); } #endif if (found) { if (_usingglobals) { object tname = ""; if (globaltypes.TryGetValue((string)tn, out tname)) tn = tname; } type = Reflection.Instance.GetTypeFromCache((string)tn); } if (type == null) throw new Exception("Cannot determine type"); string typename = type.FullName; object o = input; if (o == null) o = Reflection.Instance.FastCreateInstance(type); SafeDictionary<string, myPropInfo> props = Getproperties(type, typename); foreach (string n in d.Keys) { string name = n; if (_params.IgnoreCaseOnDeserialize) name = name.ToLower(); if (name == "$map") { ProcessMap(o, props, (Dictionary<string, object>)d[name]); continue; } myPropInfo pi; if (props.TryGetValue(name, out pi) == false) continue; if ((pi.Flags & (myPropInfoFlags.Filled | myPropInfoFlags.CanWrite)) != 0) { object v = d[name]; if (v != null) { object oset = null; switch (pi.Type) { case myPropInfoType.Int: oset = (int)((long)v); break; case myPropInfoType.Long: oset = (long)v; break; case myPropInfoType.String: oset = (string)v; break; case myPropInfoType.Bool: oset = (bool)v; break; case myPropInfoType.DateTime: oset = CreateDateTime((string)v); break; case myPropInfoType.Enum: oset = CreateEnum(pi.pt, (string)v); break; case myPropInfoType.Guid: oset = CreateGuid((string)v); break; case myPropInfoType.Array: if (!pi.IsValueType) oset = CreateArray((List<object>)v, pi.pt, pi.bt, globaltypes); // what about 'else'? break; case myPropInfoType.ByteArray: oset = Convert.FromBase64String((string)v); break; #if !SILVERLIGHT case myPropInfoType.DataSet: oset = CreateDataset((Dictionary<string, object>)v, globaltypes); break; case myPropInfoType.DataTable: oset = this.CreateDataTable((Dictionary<string, object>)v, globaltypes); break; case myPropInfoType.Hashtable: // same case as Dictionary #endif case myPropInfoType.Dictionary: oset = CreateDictionary((List<object>)v, pi.pt, pi.GenericTypes, globaltypes); break; case myPropInfoType.StringDictionary: oset = CreateStringKeyDictionary((Dictionary<string, object>)v, pi.pt, pi.GenericTypes, globaltypes); break; case myPropInfoType.Custom: oset = CreateCustom((string)v, pi.pt); break; default: { if (pi.IsGenericType && pi.IsValueType == false && v is List<object>) oset = CreateGenericList((List<object>)v, pi.pt, pi.bt, globaltypes); else if (pi.IsClass && v is Dictionary<string, object>) oset = ParseDictionary((Dictionary<string, object>)v, globaltypes, pi.pt, pi.getter(o)); else if (v is List<object>) oset = CreateArray((List<object>)v, pi.pt, typeof(object), globaltypes); else if (pi.IsValueType) oset = ChangeType(v, pi.changeType); else oset = v; } break; } o = pi.setter(o, oset); } } } return o; } private object CreateCustom(string v, Type type) { Deserialize d; _customDeserializer.TryGetValue(type, out d); return d(v); } private void ProcessMap(object obj, SafeDictionary<string, JSON.myPropInfo> props, Dictionary<string, object> dic) { foreach (KeyValuePair<string, object> kv in dic) { myPropInfo p = props[kv.Key]; object o = p.getter(obj); Type t = Type.GetType((string)kv.Value); if (t == typeof(Guid)) p.setter(obj, CreateGuid((string)o)); } } static int CreateInteger(out int num, string s, int index, int count) { num = 0; bool neg = false; for (int x = 0; x < count; x++, index++) { char cc = s[index]; if (cc == '-') neg = true; else if (cc == '+') neg = false; else { num *= 10; num += (int)(cc - '0'); } } if (neg) num = -num; return num; } internal static long CreateLong(out long num, char[] s, int index, int count) { num = 0; bool neg = false; for (int x = 0; x < count; x++, index++) { char cc = s[index]; if (cc == '-') neg = true; else if (cc == '+') neg = false; else { num *= 10; num += (int)(cc - '0'); } } if (neg) num = -num; return num; } private object CreateEnum(Type pt, string v) { // TODO : optimize create enum #if !SILVERLIGHT return Enum.Parse(pt, v); #else return Enum.Parse(pt, v, true); #endif } private Guid CreateGuid(string s) { if (s.Length > 30) return new Guid(s); else return new Guid(Convert.FromBase64String(s)); } private DateTime CreateDateTime(string value) { bool utc = false; // 0123456789012345678 // datetime format = yyyy-MM-dd HH:mm:ss int year;// = (int)CreateLong(value.Substring(0, 4)); int month;// = (int)CreateLong(value.Substring(5, 2)); int day;// = (int)CreateLong(value.Substring(8, 2)); int hour;// = (int)CreateLong(value.Substring(11, 2)); int min;// = (int)CreateLong(value.Substring(14, 2)); int sec;// = (int)CreateLong(value.Substring(17, 2)); CreateInteger(out year, value, 0, 4); CreateInteger(out month, value, 5, 2); CreateInteger(out day, value, 8, 2); CreateInteger(out hour, value, 11, 2); CreateInteger(out min, value, 14, 2); CreateInteger(out sec, value, 17, 2); //if (value.EndsWith("Z")) if (value[value.Length - 1] == 'Z') utc = true; if (_params.UseUTCDateTime == false && utc == false) return new DateTime(year, month, day, hour, min, sec); else return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime(); } private object CreateArray(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes) { Array col = Array.CreateInstance(bt, data.Count); // create an array of objects for (int i = 0; i < data.Count; i++)// each (object ob in data) { object ob = data[i]; if (ob is IDictionary) //col.SetValue(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt, null), i); // Original line col.SetValue(RootDictionary(ob, typeof(Dictionary<string,object>)), i); // Change for UE4 else col.SetValue(ChangeType(ob, bt), i); } return col; } private object CreateGenericList(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes) { IList col = (IList)Reflection.Instance.FastCreateInstance(pt); // create an array of objects foreach (object ob in data) { if (ob is IDictionary) col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt, null)); else if (ob is List<object>) col.Add(((List<object>)ob).ToArray()); else col.Add(ChangeType(ob, bt)); } return col; } private object CreateStringKeyDictionary(Dictionary<string, object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes) { var col = (IDictionary)Reflection.Instance.FastCreateInstance(pt); //Type t1 = null; Type t2 = null; if (types != null) { //t1 = types[0]; t2 = types[1]; } foreach (KeyValuePair<string, object> values in reader) { var key = values.Key;//ChangeType(values.Key, t1); object val = null; if (values.Value is Dictionary<string, object>) val = ParseDictionary((Dictionary<string, object>)values.Value, globalTypes, t2, null); else val = ChangeType(values.Value, t2); col.Add(key, val); } return col; } private object CreateDictionary(List<object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes) { IDictionary col = (IDictionary)Reflection.Instance.FastCreateInstance(pt); Type t1 = null; Type t2 = null; if (types != null) { t1 = types[0]; t2 = types[1]; } foreach (Dictionary<string, object> values in reader) { object key = values["k"]; object val = values["v"]; if (key is Dictionary<string, object>) key = ParseDictionary((Dictionary<string, object>)key, globalTypes, t1, null); else key = ChangeType(key, t1); if (val is Dictionary<string, object>) val = ParseDictionary((Dictionary<string, object>)val, globalTypes, t2, null); else val = ChangeType(val, t2); col.Add(key, val); } return col; } private Type GetChangeType(Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) return conversionType.GetGenericArguments()[0]; return conversionType; } #if !SILVERLIGHT private DataSet CreateDataset(Dictionary<string, object> reader, Dictionary<string, object> globalTypes) { DataSet ds = new DataSet(); ds.EnforceConstraints = false; ds.BeginInit(); // read dataset schema here ReadSchema(reader, ds, globalTypes); foreach (KeyValuePair<string, object> pair in reader) { if (pair.Key == "$type" || pair.Key == "$schema") continue; List<object> rows = (List<object>)pair.Value; if (rows == null) continue; DataTable dt = ds.Tables[pair.Key]; ReadDataTable(rows, dt); } ds.EndInit(); return ds; } private void ReadSchema(Dictionary<string, object> reader, DataSet ds, Dictionary<string, object> globalTypes) { var schema = reader["$schema"]; if (schema is string) { TextReader tr = new StringReader((string)schema); ds.ReadXmlSchema(tr); } else { DatasetSchema ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema), null); ds.DataSetName = ms.Name; for (int i = 0; i < ms.Info.Count; i += 3) { if (ds.Tables.Contains(ms.Info[i]) == false) ds.Tables.Add(ms.Info[i]); ds.Tables[ms.Info[i]].Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2])); } } } private void ReadDataTable(List<object> rows, DataTable dt) { dt.BeginInit(); dt.BeginLoadData(); List<int> guidcols = new List<int>(); List<int> datecol = new List<int>(); foreach (DataColumn c in dt.Columns) { if (c.DataType == typeof(Guid) || c.DataType == typeof(Guid?)) guidcols.Add(c.Ordinal); if (_params.UseUTCDateTime && (c.DataType == typeof(DateTime) || c.DataType == typeof(DateTime?))) datecol.Add(c.Ordinal); } foreach (List<object> row in rows) { object[] v = new object[row.Count]; row.CopyTo(v, 0); foreach (int i in guidcols) { string s = (string)v[i]; if (s != null && s.Length < 36) v[i] = new Guid(Convert.FromBase64String(s)); } if (_params.UseUTCDateTime) { foreach (int i in datecol) { string s = (string)v[i]; if (s != null) v[i] = CreateDateTime(s); } } dt.Rows.Add(v); } dt.EndLoadData(); dt.EndInit(); } DataTable CreateDataTable(Dictionary<string, object> reader, Dictionary<string, object> globalTypes) { var dt = new DataTable(); // read dataset schema here var schema = reader["$schema"]; if (schema is string) { TextReader tr = new StringReader((string)schema); dt.ReadXmlSchema(tr); } else { var ms = (DatasetSchema)this.ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema), null); dt.TableName = ms.Info[0]; for (int i = 0; i < ms.Info.Count; i += 3) { dt.Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2])); } } foreach (var pair in reader) { if (pair.Key == "$type" || pair.Key == "$schema") continue; var rows = (List<object>)pair.Value; if (rows == null) continue; if (!dt.TableName.Equals(pair.Key, StringComparison.InvariantCultureIgnoreCase)) continue; ReadDataTable(rows, dt); } return dt; } #endif #endregion } }
{ "content_hash": "ea17ecc7039c833d0bdab6ee43fa9dd1", "timestamp": "", "source": "github", "line_count": 898, "max_line_length": 174, "avg_line_length": 36.34632516703786, "alnum_prop": 0.4976255399981617, "repo_name": "PopCap/GameIdea", "id": "b31cdaa028986883f3b4452319822e792ae0ea9c", "size": "32641", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Engine/Source/Programs/UnrealDocTool/APIDocTool/APIDocTool/fastJSON/JSON.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "238055" }, { "name": "Assembly", "bytes": "184134" }, { "name": "Batchfile", "bytes": "116983" }, { "name": "C", "bytes": "84264210" }, { "name": "C#", "bytes": "9612596" }, { "name": "C++", "bytes": "242290999" }, { "name": "CMake", "bytes": "548754" }, { "name": "CSS", "bytes": "134910" }, { "name": "GLSL", "bytes": "96780" }, { "name": "HLSL", "bytes": "124014" }, { "name": "HTML", "bytes": "4097051" }, { "name": "Java", "bytes": "757767" }, { "name": "JavaScript", "bytes": "2742822" }, { "name": "Makefile", "bytes": "1976144" }, { "name": "Objective-C", "bytes": "75778979" }, { "name": "Objective-C++", "bytes": "312592" }, { "name": "PAWN", "bytes": "2029" }, { "name": "PHP", "bytes": "10309" }, { "name": "PLSQL", "bytes": "130426" }, { "name": "Pascal", "bytes": "23662" }, { "name": "Perl", "bytes": "218656" }, { "name": "Python", "bytes": "21593012" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "2889614" }, { "name": "Tcl", "bytes": "1452" } ], "symlink_target": "" }
Docker file using the latest CentOS to install MariaDB from mariadb.org's yum repo. It follows much of the path as the official [MariaDB repo](https://registry.hub.docker.com/_/mariadb/) except it's on CentOS and it offers support for creating multiple databases on intial creation. To specify multiple databases list them as a comma delimited string in the environment variable MYSQL_DATABASE, e.g. `MYSQL_DATABASE=database-1,database-2`. At this stage any user you set up (with MYSQL_USER and MYSQL_PASSWORD) will have access to all the databases that are created. Otherwise uses the same environment variables as the official MariaDB dockerfile. - MYSQL_ROOT_PASSWORD - MYSQL_USER - MYSQL_PASSWORD - MYSQL_DATABASE **NB**. If you want to run mysql in the container for testing, you'll need to set the term environment variable first, `export TERM=dumb` then run `mysql` as discussed [here](https://github.com/dockerfile/mariadb/issues/3)
{ "content_hash": "1399e4ec0e9681a3707746b6880bf281", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 283, "avg_line_length": 78.75, "alnum_prop": 0.7862433862433862, "repo_name": "ardinor/dockerfiles", "id": "42e4e39eba3babcecb6af94e1e20a2a52097f7a3", "size": "967", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CentOS-MariaDB/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "9881" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hi_IN" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About NiceCoin</source> <translation>बिटकोइन के संबंध में</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;NiceCoin&lt;/b&gt; version</source> <translation>बिटकोइन वर्सन</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>कापीराइट</translation> </message> <message> <location line="+0"/> <source>The NiceCoin (undergravity.club.vip) Developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>पता पुस्तक</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>दो बार क्लिक करे पता या लेबल संपादन करने के लिए !</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>नया पता लिखिए !</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;नया पता</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your NiceCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a NiceCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified NiceCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;मिटाए !!</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your NiceCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>&amp;लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;एडिट</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>पता पुस्तक का डेटा एक्सपोर्ट (निर्यात) करे !</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>फाइल में लिख नही सके %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>नया पहचान शब्द/अक्षर वॉलेट मे डालिए ! &lt;br/&gt; कृपा करके पहचान शब्द में &lt;br&gt; 10 से ज़्यादा अक्षॉरों का इस्तेमाल करे &lt;/b&gt;,या &lt;b&gt;आठ या उससे से ज़्यादा शब्दो का इस्तेमाल करे&lt;/b&gt; !</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>एनक्रिप्ट वॉलेट !</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>वॉलेट खोलिए</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation> डीक्रिप्ट वॉलेट</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>पहचान शब्द/अक्षर बदलिये !</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>कृपा करके पुराना एवं नया पहचान शब्द/अक्षर वॉलेट में डालिए !</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR MASTERNICE&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>वॉलेट एनक्रिप्ट हो गया !</translation> </message> <message> <location line="-56"/> <source>NiceCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your nicecoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>वॉलेट एनक्रिप्ट नही हुआ!</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>वॉलेट का लॉक नही खुला !</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;विवरण</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>वॉलेट का सामानया विवरण दिखाए !</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp; लेन-देन </translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>देखिए पुराने लेन-देन के विवरण !</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>स्टोर किए हुए पते और लेबलओ को बदलिए !</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>पते की सूची दिखाए जिन्हे भुगतान करना है !</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>बाहर जायें</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>अप्लिकेशन से बाहर निकलना !</translation> </message> <message> <location line="+4"/> <source>Show information about NiceCoin</source> <translation>बीटकोइन के बारे में जानकारी !</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;विकल्प</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;बैकप वॉलेट</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a NiceCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for NiceCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>NiceCoin</source> <translation>बीटकोइन</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About NiceCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your NiceCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified NiceCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;फाइल</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;सेट्टिंग्स</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;मदद</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>टैबस टूलबार</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[टेस्टनेट]</translation> </message> <message> <location line="+47"/> <source>NiceCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to NiceCoin network</source> <translation><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n घंटा</numerusform><numerusform>%n घंटे</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n दिन</numerusform><numerusform>%n दिनो</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n हफ़्ता</numerusform><numerusform>%n हफ्ते</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 पीछे</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>भूल</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>जानकारी</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>नवीनतम</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>भेजी ट्रांजक्शन</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>प्राप्त हुई ट्रांजक्शन</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>तारीख: %1\n राशि: %2\n टाइप: %3\n पता:%4\n</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid NiceCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. NiceCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>पता एडिट करना</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;लेबल</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>इस एड्रेस बुक से जुड़ा एड्रेस</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;पता</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>इस एड्रेस बुक से जुड़ी प्रविष्टि केवल भेजने वाले addresses के लिए बदली जा सकती है|</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>नया स्वीकार्य पता</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>नया भेजने वाला पता</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>एडिट स्वीकार्य पता </translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>एडिट भेजने वाला पता</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>डाला गया पता &quot;%1&quot; एड्रेस बुक में पहले से ही मोजूद है|</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid NiceCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>वॉलेट को unlock नहीं किया जा सकता|</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>नयी कुंजी का निर्माण असफल रहा|</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>NiceCoin-Qt</source> <translation>बीटकोइन-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>संस्करण</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>खपत :</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>विकल्प</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start NiceCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start NiceCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the NiceCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the NiceCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting NiceCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show NiceCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;ओके</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;कैन्सल</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting NiceCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>फार्म</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the NiceCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>अपुष्ट :</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;हाल का लेन-देन&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>आपका चालू बॅलेन्स</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>लेन देन की पुष्टि अभी नहीं हुई है, इसलिए इन्हें अभी मोजुदा बैलेंस में गिना नहीं गया है|</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start nicecoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>भुगतान का अनुरोध</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>लेबल :</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>लागू नही </translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the NiceCoin-Qt help message to get a list with possible NiceCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>NiceCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>NiceCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the NiceCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the NiceCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>भेजने की पुष्टि करें</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; से %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>सिक्के भेजने की पुष्टि करें</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>क्या आप %1 भेजना चाहते हैं?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>और</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>फार्म</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>अमाउंट:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>प्राप्तकर्ता:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>प्राप्तकर्ता हटायें</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a NiceCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>NiceCoin एड्रेस लिखें (उदाहरण: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation>हस्ताक्षर</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this NiceCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified NiceCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a NiceCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>NiceCoin एड्रेस लिखें (उदाहरण: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter NiceCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The NiceCoin (undergravity.club.vip) Developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/अपुष्ट</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 पुष्टियाँ</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>सही</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>ग़लत</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>अज्ञात</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>लेन-देन का विवरण</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>राशि</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>ऑफलाइन ( %1 पक्का करना)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>अपुष्ट ( %1 मे %2 पक्के )</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>पक्के ( %1 पक्का करना)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>स्वीकारा गया</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>स्वीकार्य ओर से</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>भेजा खुद को भुगतान</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(लागू नहीं)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>ट्रांसेक्शन का प्रकार|</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>ट्रांसेक्शन की मंजिल का पता|</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>सभी</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>आज</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>इस हफ्ते</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>इस महीने</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>पिछले महीने</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>इस साल</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>विस्तार...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>अपनेआप को</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>अन्य</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>लघुत्तम राशि</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>एडिट लेबल</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>लेन-देन का डेटा निर्यात करे !</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>फाइल में लिख नही सके %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>विस्तार:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>तक</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>बैकप वॉलेट</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>वॉलेट डेटा (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>बैकप असफल</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>बैकप सफल</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>NiceCoin version</source> <translation>बीटकोइन संस्करण</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>खपत :</translation> </message> <message> <location line="-29"/> <source>Send command to -server or nicecoind</source> <translation>-server या NiceCoind को कमांड भेजें</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>commands की लिस्ट बनाएं</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>किसी command के लिए मदद लें</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>विकल्प:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: nicecoin.conf)</source> <translation>configuraion की फाइल का विवरण दें (default: nicecoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: nicecoind.pid)</source> <translation>pid फाइल का विवरण दें (default: Mana.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 10333 or testnet: 11333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 10332 or testnet: 11332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: nicecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;NiceCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. NiceCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong NiceCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>ब्लॉक्स जाँचे जा रहा है...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>वॉलेट जाँचा जा रहा है...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>जानकारी</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the NiceCoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>पता पुस्तक आ रही है...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of NiceCoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart NiceCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>राशि ग़लत है</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>ब्लॉक इंडेक्स आ रहा है...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. NiceCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>वॉलेट आ रहा है...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>रि-स्केनी-इंग...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>लोड हो गया|</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>भूल</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
{ "content_hash": "b89136744dd40a0fcb4439df44201fd4", "timestamp": "", "source": "github", "line_count": 2922, "max_line_length": 395, "avg_line_length": 34.21081451060917, "alnum_prop": 0.5825997359049258, "repo_name": "nicecoinx/nicecoin", "id": "48af8a50ce6f72a3c243744cf286127f730191d4", "size": "106382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_hi_IN.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "31815" }, { "name": "C++", "bytes": "12334199" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18289" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "19654" }, { "name": "NSIS", "bytes": "5943" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "69722" }, { "name": "QMake", "bytes": "15116" }, { "name": "Shell", "bytes": "9702" } ], "symlink_target": "" }
using System; using System.Text; namespace ServiceStack.Logging { /// <summary> /// StringBuilderLog writes to shared StringBuffer. /// Made public so its testable /// </summary> public class StringBuilderLogFactory : ILogFactory { private StringBuilder sb; public StringBuilderLogFactory() { sb = new StringBuilder(); } public ILog GetLogger(Type type) { return new StringBuilderLog(type, sb); } public ILog GetLogger(string typeName) { return new StringBuilderLog(typeName, sb); } public string GetLogs() { lock (sb) return sb.ToString(); } public void ClearLogs() { lock (sb) sb.Remove(0, sb.Length - 1); } } public class StringBuilderLog : ILog { const string DEBUG = "DEBUG: "; const string ERROR = "ERROR: "; const string FATAL = "FATAL: "; const string INFO = "INFO: "; const string WARN = "WARN: "; private readonly StringBuilder logs; public StringBuilderLog(string type, StringBuilder logs) { this.logs = logs; } public StringBuilderLog(Type type, StringBuilder logs) { this.logs = logs; } public bool IsDebugEnabled { get { return true; } } /// <summary> /// Logs the specified message. /// </summary> private void Log(object message, Exception exception) { string msg = message == null ? string.Empty : message.ToString(); if (exception != null) { msg += ", Exception: " + exception.Message; } lock (logs) logs.AppendLine(msg); } /// <summary> /// Logs the format. /// </summary> private void LogFormat(object message, params object[] args) { string msg = message == null ? string.Empty : message.ToString(); lock (logs) { logs.AppendFormat(msg, args); logs.AppendLine(); } } /// <summary> /// Logs the specified message. /// </summary> /// <param name="message">The message.</param> private void Log(object message) { string msg = message == null ? string.Empty : message.ToString(); lock (logs) { logs.AppendLine(msg); } } public void Debug(object message, Exception exception) { Log(DEBUG + message, exception); } public void Debug(object message) { Log(DEBUG + message); } public void DebugFormat(string format, params object[] args) { LogFormat(DEBUG + format, args); } public void Error(object message, Exception exception) { Log(ERROR + message, exception); } public void Error(object message) { Log(ERROR + message); } public void ErrorFormat(string format, params object[] args) { LogFormat(ERROR + format, args); } public void Fatal(object message, Exception exception) { Log(FATAL + message, exception); } public void Fatal(object message) { Log(FATAL + message); } public void FatalFormat(string format, params object[] args) { LogFormat(FATAL + format, args); } public void Info(object message, Exception exception) { Log(INFO + message, exception); } public void Info(object message) { Log(INFO + message); } public void InfoFormat(string format, params object[] args) { LogFormat(INFO + format, args); } public void Warn(object message, Exception exception) { Log(WARN + message, exception); } public void Warn(object message) { Log(WARN + message); } public void WarnFormat(string format, params object[] args) { LogFormat(WARN + format, args); } } } #endif
{ "content_hash": "cb40fe26b83df7463b326b69584fa1c4", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 77, "avg_line_length": 24.748603351955307, "alnum_prop": 0.5033860045146726, "repo_name": "mexxanit/YAFNET", "id": "c8edde3af0dcbad9fffcb5fc35f492bcf1d7009b", "size": "4446", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "yafsrc/ServiceStack.OrmLite/src/ServiceStack.Interfaces/Logging/StringBuilderLog.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "925955" }, { "name": "Batchfile", "bytes": "3655" }, { "name": "C#", "bytes": "9517540" }, { "name": "CSS", "bytes": "1271582" }, { "name": "HTML", "bytes": "3753" }, { "name": "JavaScript", "bytes": "1847345" }, { "name": "SQLPL", "bytes": "1474" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Testing; using NUnit.Framework; namespace Grpc.IntegrationTesting { /// <summary> /// Test SSL credentials where server authenticates client /// and client authenticates the server. /// </summary> public class SslCredentialsTest { const string Host = "localhost"; Server server; Channel channel; TestService.TestServiceClient client; [TestFixtureSetUp] public void Init() { var rootCert = File.ReadAllText(TestCredentials.ClientCertAuthorityPath); var keyCertPair = new KeyCertificatePair( File.ReadAllText(TestCredentials.ServerCertChainPath), File.ReadAllText(TestCredentials.ServerPrivateKeyPath)); var serverCredentials = new SslServerCredentials(new[] { keyCertPair }, rootCert, true); var clientCredentials = new SslCredentials(rootCert, keyCertPair); server = new Server { Services = { TestService.BindService(new TestServiceImpl()) }, Ports = { { Host, ServerPort.PickUnused, serverCredentials } } }; server.Start(); var options = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride) }; channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options); client = TestService.NewClient(channel); } [TestFixtureTearDown] public void Cleanup() { channel.ShutdownAsync().Wait(); server.ShutdownAsync().Wait(); } [Test] public void AuthenticatedClientAndServer() { var response = client.UnaryCall(new SimpleRequest { ResponseSize = 10 }); Assert.AreEqual(10, response.Payload.Body.Length); } } }
{ "content_hash": "89fa2442515e0028cc43fc300e21586b", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 108, "avg_line_length": 32.21212121212121, "alnum_prop": 0.625587958607714, "repo_name": "goldenbull/grpc", "id": "3df45b5f7084f5748a587e8f2b2ecd5b3adbdf86", "size": "3738", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/csharp/Grpc.IntegrationTesting/SslCredentialsTest.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "9986" }, { "name": "C", "bytes": "4768389" }, { "name": "C#", "bytes": "1029724" }, { "name": "C++", "bytes": "1274782" }, { "name": "DTrace", "bytes": "147" }, { "name": "JavaScript", "bytes": "262872" }, { "name": "Makefile", "bytes": "549711" }, { "name": "Objective-C", "bytes": "255265" }, { "name": "PHP", "bytes": "127110" }, { "name": "Protocol Buffer", "bytes": "95971" }, { "name": "Python", "bytes": "1578367" }, { "name": "Ruby", "bytes": "460190" }, { "name": "Shell", "bytes": "47892" }, { "name": "Swift", "bytes": "5279" } ], "symlink_target": "" }
layout: post title: Must Research Papers tags: - News - Tags - Blog - Post --- 1) The FORTRAN Automatic Coding System https://people.cs.umass.edu/~emery/classes/cmpsci691st/readings/PL/FORTRAN-102663113.05.01.acc.pdf 2) Recursive Functions of Symbolic Expressions and Their Computation by Machine https://people.cs.umass.edu/~emery/classes/cmpsci691st/readings/PL/LISP.pdf 3) An Introduction to programming with Threads https://people.cs.umass.edu/~emery/classes/cmpsci691st/readings/Conc/birrel89introduction.pdf 4) The Unix Time Sharing System https://people.cs.umass.edu/~emery/classes/cmpsci691st/readings/OS/The-UNIX-Time-Sharing-System-BSTJ.pdf
{ "content_hash": "46bcc704bec36afa23ad43209f14b7fe", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 104, "avg_line_length": 38.88235294117647, "alnum_prop": 0.789712556732224, "repo_name": "sandeep06011991/sandeep06011991.github.io", "id": "f90b5bf32c04149f7faefc7aaa9a8eebf926d144", "size": "665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_drafts/research papers.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "12390" }, { "name": "HTML", "bytes": "20948" }, { "name": "JavaScript", "bytes": "980" }, { "name": "OCaml", "bytes": "26936" }, { "name": "Ruby", "bytes": "53" } ], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _eventListsSkeletonEventList = require("../eventLists/SkeletonEventList"); var _eventListsSkeletonEventList2 = _interopRequireDefault(_eventListsSkeletonEventList); var _utilsEventHandlerCreator = require("../utils/eventHandlerCreator"); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = require("../utils/defaultPropsCreator"); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = require("../utils/composeOptions"); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = require("../utils/componentLifecycleDecorator"); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = require("./GoogleMapHolder"); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var skeletonControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference animation: _react.PropTypes.any }; exports.skeletonControlledPropTypes = skeletonControlledPropTypes; var skeletonDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(skeletonControlledPropTypes); exports.skeletonDefaultPropTypes = skeletonDefaultPropTypes; var skeletonUpdaters = { animation: function animation(_animation, component) { component.getSkeleton().setAnimation(_animation); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsSkeletonEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var skeletonEventPropTypes = eventPropTypes; exports.skeletonEventPropTypes = skeletonEventPropTypes; var SkeletonCreator = (function (_Component) { _inherits(SkeletonCreator, _Component); function SkeletonCreator() { _classCallCheck(this, _SkeletonCreator); _get(Object.getPrototypeOf(_SkeletonCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(SkeletonCreator, [{ key: "getSkeleton", value: function getSkeleton() { return this.props.skeleton; } }, { key: "render", value: function render() { var children = this.props.children; if (_react.Children.count(children) > 0) { return _react2["default"].createElement( "div", null, children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "_createSkeleton", value: function _createSkeleton(skeletonProps) { var mapHolderRef = skeletonProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference var skeleton = new google.maps.Skeleton((0, _utilsComposeOptions2["default"])(skeletonProps, skeletonControlledPropTypes)); skeleton.setMap(mapHolderRef.getMap()); return skeleton; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, skeleton: _react.PropTypes.object.isRequired }, enumerable: true }]); var _SkeletonCreator = SkeletonCreator; SkeletonCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getSkeleton", updaters: skeletonUpdaters })(SkeletonCreator) || SkeletonCreator; return SkeletonCreator; })(_react.Component); exports["default"] = SkeletonCreator;
{ "content_hash": "515bab9c70ec1f426e7032113ea8301e", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 658, "avg_line_length": 45.07518796992481, "alnum_prop": 0.7271059216013345, "repo_name": "wojtczat/WeatherApp", "id": "19b772c31a75edb2dc208008aa79a0a68ede9679", "size": "5995", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "node_modules/react-google-maps/lib/creators/_SkeletonCreator.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "160" }, { "name": "HTML", "bytes": "363" }, { "name": "JavaScript", "bytes": "7350" } ], "symlink_target": "" }
//created by Joseph Rioux, 22 October 2013 //This class will serve the main functions of the player. // Specific powers and abilities will build off of this. //Modified by James Vanderhyde, 21 May 2014 // Refactored specialty movement code into subclasses //Modified by Joseph Rioux, 6 June 2014 // Commented to eliminate errors due to altering Scene package edu.benedictine.game.engine; import edu.benedictine.game.media.ImageSource; import edu.benedictine.game.engine.collision.BoundingBox; import edu.benedictine.game.util.AdvancedForce; import edu.benedictine.game.gui.Scene; public class Player extends GameObject { int life; int maxLife; int invincible; int gotHit; int jump; int jumpSwitch; boolean run = false; boolean runLeft = false; boolean runRight = false; boolean slowingDown = false; int sliding = -10; double xAcc = 0.0; double yAcc = 0.0; int weaponType = 3; int weaponUp = 1; int strike = 0; int locked = 0; boolean reelLock; int airLockX = 0; boolean onEdge, atEdge; int weaponPointing; int airControl = 0; int xLock, yLock, xControlLock, yControlLock; //locks for a certain number of frames boolean xAirLock, yAirLock, xAirConLock, yAirConLock; //locks until you hit the ground boolean leftAirLock, rightAirLock; int falling = 128; double shotgunDown; int dasher, dashDirection; //jump project vars boolean big = true; int gems = 0; //hard code a lot of the player's attributes (e.g img, head, left, etc.) public Player(Scene scn, double xLoc, double yLoc, double xCng, double yCng) { super(scn, 5, 8, xLoc, yLoc, xCng, yCng, scn.store.heroStatic, -40.0, 16.0, -8.0, 8.0); if (!big) this.setTerrainLimits(-8, 8, -12, 16); box = new BoundingBox(scn, this, 1, new int[]{0, 2, 3}, 15, 0.0, 6.0, 8.0, 10.0); yForce = new AdvancedForce(0.0, 0.0, 0.0, -600.0, 600.0, 1); xForce = new AdvancedForce(0.0, 0.0, 60.0, -120.0, 120.0, 1); forceOn = true; maxLife = 10; life = 10; //switchSize(); } public void update() { //large or small /*if (scn.d && scn.downPressed <= 0 && onGround) switchSize(); onEdge = false; atEdge = false; if (onGround && (getEdge(true) > -8 || getEdge(false) < 8)) onEdge = true; if ((!flipX && getEdge(true) > -8) || (flipX && getEdge(false) < 8)) atEdge = true; if ((locked < 1) && (!reelLock)) { walk(); jump(); } if (life < 1) die(); if (life > maxLife) life = maxLife; //die off bottom of screen if (y > scn.screenBoundB+256.0) life = 0; if (y < -960) { y = -960; yForce.value = 0.0; } super.update();*/ } public void switchSize() { /*if (big) { big = false; this.setTerrainLimits(-8, 8, -12, 16); y -= 4; } else { boolean under = false; for (int i=0; i<scn.collisionManager.walls[2].size(); i++) if (x < scn.collisionManager.walls[2].get(i).x0+16) if (x > scn.collisionManager.walls[2].get(i).x1-16) if (y > scn.collisionManager.walls[2].get(i).y0-16) if (y < scn.collisionManager.walls[2].get(i).y0+32) under = true; if (!under) { big = true; this.setTerrainLimits(-8, 8, -40, 16); y -= 4; } }*/ } //This is still accessing the JumpSimulator interface, // but for the game engine there should be some default implementation. public void walk() { /*xForce.upper = scn.mn.xSpeed; xForce.lower = -scn.mn.xSpeed; xForce.accel = 30.0; if (scn.l) { if (xForce.value > scn.mn.xSpeed*scn.mn.airDecel) xForce.value = scn.mn.xSpeed*scn.mn.airDecel; xForce.accel = -xForce.accel; setFlipX(false); } if (scn.r) { if (xForce.value < -scn.mn.xSpeed*scn.mn.airDecel) xForce.value = -scn.mn.xSpeed*scn.mn.airDecel; setFlipX(true); } if ((!scn.l) && (!scn.r)) { xForce.upper = scn.mn.xSpeed*scn.mn.airDecel; xForce.lower = -scn.mn.xSpeed*scn.mn.airDecel; xForce.accel = 0.0; xForce.decel = 30.0; //basic if (onGround) { xForce.upper = 0.0; xForce.lower = 0.0; xForce.decel = 30.0; } }*/ } public void jump() { /* if ((scn.a) && (scn.aPressed <= 0) && (onGround)) { yForce.value = -scn.mn.jumpPower; } if (!scn.a && yForce.value < 0.0) { if (scn.mn.cancelType.equals("full")) yForce.value = 0.0; if (scn.mn.cancelType.equals("double")) yForce.value += scn.mn.gravity; } if (!onGround) { yForce.value += scn.mn.gravity; } */ } private void setAnimations() { /* ImageSource walk, stat, air; if (big) { walk = scn.store.heroWalk; stat = scn.store.heroStatic; air = scn.store.heroAir; } else { walk = scn.store.heroEmptyWalk; stat = scn.store.heroEmptyStatic; air = scn.store.heroEmptyAir; } //animations if (onTerrain == null) { if (imageTime != 1) { setImage(air); } } else { if (xSpeed == 0.0) { setImage(stat); } else { changeImage(walk); } } //setImage(scn.store.heroHit); */ } public void checkCollision() { //So, currently the player gets stopped by walls before landing on floors too much //e.g. if he's falling along a sheer wall and there is a 1-square tall opening //in the wall he will not land in that opening. I'd like to make it so that he does. //How? //What I could do is make the endpoints of side walls a bit "fuzzy". This means that, //if the player hits a side wall near the corner and is going fast enough in the //direction of the corner (up for an upper corner, etc.) he will pass through that //wall. //E.g. if the player jumps at a left wall and gets to the upper corner of a ledge. If //his current upward speed would take him up to the level of the ledge, he goes through //the wall and lands on the ledge. //Dangerous. If the player were to rapidly change velocity when traveling through the wall, //he would break through the collision boundary of the terrain and ironclad collision would //be broken. Possible solution: lock the player's ySpeed when passing through a fuzzy corner //so that he must get to the level of the ledge before changing ySpeed. ??? //make two checks for sides, one at the proper width of the player (16 pixels), //another at the center of the player //Don't assume this is all good. Written on 3/27/13 //initial check /* checkLeft(); checkRight(); checkCeiling(); checkFloor(); //make sure nothing slips through if ((onTerrain != null) || (atCeiling != null)) { if (atLeftWall == null) checkLeft(); if (atRightWall == null) checkRight(); } //finally, adjust if in a wall a bit (which is supposed to happen sometimes //to make things look smoother) //wallAdjust(); if (onTerrain != null) hitTerrain(onTerrain); if (atRightWall != null) hitTerrain(atRightWall); if (atCeiling != null) hitTerrain(atCeiling); if (atLeftWall != null) hitTerrain(atLeftWall); */ } public void checkFloor() { /* double xL = -1.0; double xR = 1.0; if (Math.abs(xSpeed) <= 8.0) { xL = -Math.abs(xSpeed*1.25); xR = Math.abs(xSpeed*1.25); } if (xL > -1.0) xL = -1.0; if (xR < 1.0) xR = 1.0; //check if the player was on the platform before the collision check //if so, the player is walking off a platform and variable skid should be //set to the direction that the player is walking int skid = 0; if (onTerrain != null) if (flipX) skid = 1; else skid = -1; onGround = false; Terrain floor = scn.collisionManager.collideFloor(this, head, feet, left, right); if ((floor != null) && (floor.suppressForPlayer <= 0)) { if (ySpeed > 0.0) { //setImage(scn.store.heroWalk); //imageTime = 3; } y = floor.y0-feet; //if (yForce.value > 30.0) //System.out.println("hit floor: "+(System.currentTimeMillis()-start)); falling = 128; shotgunDown = -240; jump = 0; yForce.value = 0.0; leftAirLock = false; rightAirLock = false; yAirLock = false; } if ((onTerrain != atCeiling) || (atCeiling == null)) { onTerrain = floor; onGround = true; } //check skid to see if we must slide off the platform //(it looks weird to walk off a platform and be right against the wall) if (!onGround && xSpeed == 0.0 && skid != 0 && ySpeed >= 0.0) xSpeed = skid; */ } public void checkRight() { /* double priorSpeed = xSpeed; atRightWall = scn.collisionManager.collideRightWall(this, head, feet, left, right); if (atRightWall != null) { x = atRightWall.x0-left; xForce.value = 0.0; } else { atRightWall = scn.collisionManager.collideRightWall(this, head, feet, 0.0, 0.0); if (atRightWall != null) { x = atRightWall.x0; xForce.value = 0.0; } } */ } public void checkCeiling() { /* atCeiling = scn.collisionManager.collideCeiling(this, head, feet, left, right); if (atCeiling != null) { y = atCeiling.y0-head; if (ySpeed < -4.0) { yForce.value = -4.0; } } */ } public void checkLeft() { /* atLeftWall = scn.collisionManager.collideLeftWall(this, head, feet, left, right); if (atLeftWall != null) { x = atLeftWall.x0-right; xForce.value = 0.0; } else { atLeftWall = scn.collisionManager.collideLeftWall(this, head, feet, 0.0, 0.0); if (atLeftWall != null) { x = atLeftWall.x0; xForce.value = 0.0; } } * */ } public void wallAdjust() { /* Terrain wall = scn.collisionManager.basicCollideLeftWall(this, head, feet, left, right); if (wall != null) { double speed = -4.0; if (speed < wall.x0 - (x+right)) speed = wall.x0 - (x+right); x += speed; } wall = scn.collisionManager.basicCollideRightWall(this, head, feet, left, right); if (wall != null) { double speed = 4.0; if (speed > wall.x0 - (x+left)) speed = wall.x0 - (x+left); x += speed; } * */ } public void cleanUp() { /* super.cleanUp(); if (gotHit < 1) invincible--; if (onTerrain != null) gotHit--; xLock--; yLock--; xControlLock--; yControlLock--; locked--; //invincible flashing if ((invincible > 0) && (invincible % 2 == 0) && (gotHit < 1)) { if (visible == true) visible = false; else if (visible == false) visible = true; } if (invincible < 1) visible = true; setAnimations(); //update save manager values //scn.mn.state.playerLife = life; //scn.mn.state.playerMaxLife = maxLife; //scn.cameraX = x-512.0; //scn.cameraY = y-320.0; boolean standingStill = true; //set components - can't alter things while moving if (!onGround || yForce.value != 0.0 || xForce.value != 0.0) { standingStill = false; scn.mn.custom.setEnabled(false); scn.mn.mario.setEnabled(false); scn.mn.samus.setEnabled(false); scn.mn.zeetee.setEnabled(false); } else { scn.mn.custom.setEnabled(true); scn.mn.mario.setEnabled(true); scn.mn.samus.setEnabled(true); scn.mn.zeetee.setEnabled(true); } //disable the sliders when using preset jumps if (!scn.mn.custom.isSelected() || !standingStill) { scn.mn.s.setEnabled(false); scn.mn.s2.setEnabled(false); scn.mn.s3.setEnabled(false); scn.mn.s4.setEnabled(false); //scn.mn.s5.setEnabled(false); scn.mn.noCancel.setEnabled(false); scn.mn.doubleGravity.setEnabled(false); scn.mn.fullCancel.setEnabled(false); } else { scn.mn.s.setEnabled(true); scn.mn.s2.setEnabled(true); scn.mn.s3.setEnabled(true); scn.mn.s4.setEnabled(true); //scn.mn.s5.setEnabled(true); scn.mn.noCancel.setEnabled(true); scn.mn.doubleGravity.setEnabled(true); scn.mn.fullCancel.setEnabled(true); }*/ } public void takeDamage(GameObject foe, BoundingBox box, int damage) { /* if (invincible < 1) { life -= damage; //find direction to the box int hitDirection = direction; double xDifference = priorX - foe.x+box.xOffset; if (xDifference != 0) hitDirection = (int)(xDifference/Math.abs(xDifference)); //ySpeed = -6.0; //xSpeed = 16.0*hitDirection; //xForce.value = 4.0*hitDirection; //if (yForce.value > -180.0) //yForce.value = -180.0; //direction = -hitDirection; sliding = -10; flipY = false; //if (direction > 0) // flipX = true; //else // flipX = false; //scn.spEffects.radialParticles(7, scn.store.beamHook, x, y, 4.0, 6.0, 3, 5, 5, 16, 0, 0, 0); onTerrain = null; //is this too dangerous? //gotHit = 25; //timer for recovering from a hit invincible = 80; //invincibility frames } * */ } public void die() { //scn.spEffects.radialParticles(50, scn.store.jetStream, x, y, 240.0, 480.0, 20, 50, 16, 16, 1.0, 30.0, 480.0); //reload //scn.mn.state.load(); //System.out.println("reloading game "+scn.mn.state.savedLevel); //scn.swapper.mark(scn.mn.state.savedLevel, 150, scn.mn.state.saveX, scn.mn.state.saveY); super.die(); } public int getNumGems() { return gems; } }
{ "content_hash": "86d022a34230f033b58cd8ee78d46de6", "timestamp": "", "source": "github", "line_count": 576, "max_line_length": 113, "avg_line_length": 22.630208333333332, "alnum_prop": 0.6248561565017261, "repo_name": "jvanderhyde/JumpSimulator", "id": "a9ecc7f07026408211bdee373a409568f592ca49", "size": "13035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JumpSimulator/src/edu/benedictine/game/engine/Player.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "199788" } ], "symlink_target": "" }
import logging from django.utils import timezone from quickstats.models import Widget logger = logging.getLogger(__name__) def quick_record(owner, value, **kwargs): labels = kwargs.pop("labels", {}) defaults = kwargs.setdefault("defaults", {}) defaults.setdefault("type", "chart") defaults.setdefault("value", value) # If we get a metric, we both want to set it # as one of our labels, but also default it to # the title we use for our widget if "metric" in kwargs: metric = kwargs.pop("metric") labels.setdefault("__name__", metric) defaults.setdefault("title", metric) if "timestamp" in kwargs: timestamp = kwargs.pop("timestamp") defaults.setdefault("timestamp", timestamp) else: timestamp = defaults.setdefault("timestamp", timezone.now()) widget, _ = Widget.objects.lookup_or_create(owner=owner, labels=labels, **kwargs) sample = widget.sample_set.create(timestamp=timestamp, value=value) logger.debug("Created sample %r" % sample) return sample
{ "content_hash": "fb73951745b84979a412a802c0f09c6c", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 85, "avg_line_length": 32.21212121212121, "alnum_prop": 0.6698024459078081, "repo_name": "kfdm/django-simplestats", "id": "fecaeed496706b2bc426e571ff8629325ff811e2", "size": "1063", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quickstats/shortcuts.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "563" }, { "name": "HTML", "bytes": "22307" }, { "name": "Makefile", "bytes": "177" }, { "name": "Python", "bytes": "90170" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE617_Reachable_Assertion__connect_socket_81_bad.cpp Label Definition File: CWE617_Reachable_Assertion.label.xml Template File: sources-sink-81_bad.tmpl.cpp */ /* * @description * CWE: 617 Reachable Assertion * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Number greater than ASSERT_VALUE * Sinks: * BadSink : Assert if n is less than or equal to ASSERT_VALUE * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE617_Reachable_Assertion__connect_socket_81.h" namespace CWE617_Reachable_Assertion__connect_socket_81 { void CWE617_Reachable_Assertion__connect_socket_81_bad::action(int data) const { /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */ assert(data > ASSERT_VALUE); } } #endif /* OMITBAD */
{ "content_hash": "57cb025f794955d44efaaea15d3bf02c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 101, "avg_line_length": 31.548387096774192, "alnum_prop": 0.721881390593047, "repo_name": "maurer/tiamat", "id": "3220c99b7fad1b4166d093d834a4900c0fa2818c", "size": "978", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE617_Reachable_Assertion/CWE617_Reachable_Assertion__connect_socket_81_bad.cpp", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- DataSource Configuration --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="initialSize" value="30"/> <property name="maxTotal" value="30"/> <property name="maxIdle" value="30"/> <property name="minIdle" value="30"/> <property name="maxWaitMillis" value="3000"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <property name="timeBetweenEvictionRunsMillis" value="30000"/> <property name="numTestsPerEvictionRun" value="6"/> <property name="minEvictableIdleTimeMillis" value="-1"/> <property name="validationQuery" value="SELECT 1"/> <!-- use cache or not for preparedStatement--> <property name="poolPreparedStatements" value="true"/> <property name="maxOpenPreparedStatements" value="50"/> </bean> <bean id="metaDataDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="initialSize" value="30"/> <property name="maxTotal" value="30"/> <property name="maxIdle" value="30"/> <property name="minIdle" value="30"/> <property name="maxWaitMillis" value="3000"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <property name="timeBetweenEvictionRunsMillis" value="30000"/> <property name="numTestsPerEvictionRun" value="6"/> <property name="minEvictableIdleTimeMillis" value="-1"/> <property name="validationQuery" value="SELECT 1"/> <!-- use cache or not for preparedStatement--> <property name="poolPreparedStatements" value="true"/> <property name="maxOpenPreparedStatements" value="50"/> </bean> </beans>
{ "content_hash": "4a2a67e6659be238e4d426422614725b", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 133, "avg_line_length": 46.813559322033896, "alnum_prop": 0.6480811006517017, "repo_name": "chenguoxi1985/pinpoint", "id": "7483559a285ef99a3d0212c98e85d3a536695c70", "size": "2762", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "web/src/main/resources/applicationContext-datasource.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "27926" }, { "name": "CSS", "bytes": "156512" }, { "name": "CoffeeScript", "bytes": "10124" }, { "name": "Groovy", "bytes": "1423" }, { "name": "HTML", "bytes": "631701" }, { "name": "Java", "bytes": "13132756" }, { "name": "JavaScript", "bytes": "4813332" }, { "name": "Makefile", "bytes": "5246" }, { "name": "PLSQL", "bytes": "4156" }, { "name": "Python", "bytes": "3523" }, { "name": "Ruby", "bytes": "943" }, { "name": "Shell", "bytes": "37985" }, { "name": "Thrift", "bytes": "14690" } ], "symlink_target": "" }
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highstock]] */ package com.highstock.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>series&lt;heatmap&gt;-states-hover</code> */ @js.annotation.ScalaJSDefined class SeriesHeatmapStatesHover extends com.highcharts.HighchartsGenericObject { /** * <p>How much to brighten the point on interaction. Requires the main * color to be defined in hex or rgb(a) format.</p> * <p>In styled mode, the hover brightening is by default replaced * with a fill-opacity set in the <code>.highcharts-point:hover</code> rule.</p> */ val brightness: js.UndefOr[Double] = js.undefined /** * <p>Animation setting for hovering the graph in line-type series.</p> * @since 5.0.8 */ val animation: js.UndefOr[Boolean | js.Object] = js.undefined /** * <p>The additional line width for the graph of a hovered series.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-linewidthplus/">5 pixels wider</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-linewidthplus/">5 pixels wider</a> * @since 4.0.3 */ val lineWidthPlus: js.UndefOr[Double] = js.undefined /** * <p>In Highcharts 1.0, the appearance of all markers belonging to the * hovered series. For settings on the hover state of the individual * point, see * <a href="#plotOptions.series.marker.states.hover">marker.states.hover</a>.</p> */ val marker: js.UndefOr[CleanJsObject[SeriesHeatmapStatesHoverMarker]] = js.undefined /** * <p>Options for the halo appearing around the hovered point in line- * type series as well as outside the hovered slice in pie charts. * By default the halo is filled by the current point or series * color with an opacity of 0.25. The halo can be disabled by * setting the <code>halo</code> option to <code>false</code>.</p> * <p>In styled mode, the halo is styled with the <code>.highcharts-halo</code> * class, with colors inherited from <code>.highcharts-color-{n}</code>.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/halo/">Halo options</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/halo/">Halo options</a> * @since 4.0 */ val halo: js.Any = js.undefined /** * <p>Enable separate styles for the hovered series to visualize that * the user hovers either the series itself or the legend. .</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-enabled/">Line</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-enabled-column/">Column</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-enabled-pie/">Pie</a> * @since 1.2 */ val enabled: js.UndefOr[Boolean] = js.undefined /** * <p>Pixel width of the graph line. By default this property is * undefined, and the <code>lineWidthPlus</code> property dictates how much * to increase the linewidth from normal state.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-linewidth/">5px line on hover</a> */ val lineWidth: js.UndefOr[Double] = js.undefined /** * <p>The color of the shape in this state</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-states-hover/">Hover options</a> */ val color: js.UndefOr[String | js.Object] = js.undefined /** * <p>The border color of the point in this state.</p> */ val borderColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>The border width of the point in this state</p> */ val borderWidth: js.UndefOr[Double] = js.undefined } object SeriesHeatmapStatesHover { /** * @param brightness <p>How much to brighten the point on interaction. Requires the main. color to be defined in hex or rgb(a) format.</p>. <p>In styled mode, the hover brightening is by default replaced. with a fill-opacity set in the <code>.highcharts-point:hover</code> rule.</p> * @param animation <p>Animation setting for hovering the graph in line-type series.</p> * @param lineWidthPlus <p>The additional line width for the graph of a hovered series.</p> * @param marker <p>In Highcharts 1.0, the appearance of all markers belonging to the. hovered series. For settings on the hover state of the individual. point, see. <a href="#plotOptions.series.marker.states.hover">marker.states.hover</a>.</p> * @param halo <p>Options for the halo appearing around the hovered point in line-. type series as well as outside the hovered slice in pie charts.. By default the halo is filled by the current point or series. color with an opacity of 0.25. The halo can be disabled by. setting the <code>halo</code> option to <code>false</code>.</p>. <p>In styled mode, the halo is styled with the <code>.highcharts-halo</code>. class, with colors inherited from <code>.highcharts-color-{n}</code>.</p> * @param enabled <p>Enable separate styles for the hovered series to visualize that. the user hovers either the series itself or the legend. .</p> * @param lineWidth <p>Pixel width of the graph line. By default this property is. undefined, and the <code>lineWidthPlus</code> property dictates how much. to increase the linewidth from normal state.</p> * @param color <p>The color of the shape in this state</p> * @param borderColor <p>The border color of the point in this state.</p> * @param borderWidth <p>The border width of the point in this state</p> */ def apply(brightness: js.UndefOr[Double] = js.undefined, animation: js.UndefOr[Boolean | js.Object] = js.undefined, lineWidthPlus: js.UndefOr[Double] = js.undefined, marker: js.UndefOr[CleanJsObject[SeriesHeatmapStatesHoverMarker]] = js.undefined, halo: js.UndefOr[js.Any] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, borderColor: js.UndefOr[String | js.Object] = js.undefined, borderWidth: js.UndefOr[Double] = js.undefined): SeriesHeatmapStatesHover = { val brightnessOuter: js.UndefOr[Double] = brightness val animationOuter: js.UndefOr[Boolean | js.Object] = animation val lineWidthPlusOuter: js.UndefOr[Double] = lineWidthPlus val markerOuter: js.UndefOr[CleanJsObject[SeriesHeatmapStatesHoverMarker]] = marker val haloOuter: js.Any = halo val enabledOuter: js.UndefOr[Boolean] = enabled val lineWidthOuter: js.UndefOr[Double] = lineWidth val colorOuter: js.UndefOr[String | js.Object] = color val borderColorOuter: js.UndefOr[String | js.Object] = borderColor val borderWidthOuter: js.UndefOr[Double] = borderWidth com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesHeatmapStatesHover { override val brightness: js.UndefOr[Double] = brightnessOuter override val animation: js.UndefOr[Boolean | js.Object] = animationOuter override val lineWidthPlus: js.UndefOr[Double] = lineWidthPlusOuter override val marker: js.UndefOr[CleanJsObject[SeriesHeatmapStatesHoverMarker]] = markerOuter override val halo: js.Any = haloOuter override val enabled: js.UndefOr[Boolean] = enabledOuter override val lineWidth: js.UndefOr[Double] = lineWidthOuter override val color: js.UndefOr[String | js.Object] = colorOuter override val borderColor: js.UndefOr[String | js.Object] = borderColorOuter override val borderWidth: js.UndefOr[Double] = borderWidthOuter }) } }
{ "content_hash": "8f7c30caff116824e045179c86c0d39b", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 573, "avg_line_length": 61.582089552238806, "alnum_prop": 0.7266117304895783, "repo_name": "Karasiq/scalajs-highcharts", "id": "7f8f88c8eeb76f726464fb417afe18a1b67f25b1", "size": "8252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/highstock/config/SeriesHeatmapStatesHover.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "131509301" } ], "symlink_target": "" }
<?php defined('BX_DOL') or die('hack attempt'); /** * All queries related to account */ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton { protected function __construct() { if (isset($GLOBALS['bxDolClasses'][get_class($this)])) trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR); parent::__construct(); } /** * Prevent cloning the instance */ public function __clone() { if (isset($GLOBALS['bxDolClasses'][get_class($this)])) trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR); } /** * Get singleton instance of the class */ public static function getInstance() { if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolAccountQuery(); return $GLOBALS['bxDolClasses'][__CLASS__]; } public function getOperators () { $sSql = $this->prepare("SELECT `id` FROM `sys_accounts` WHERE `role`&" . BX_DOL_ROLE_ADMIN); return $this->getColumn($sSql); } /** * Get account by specified field name and value. * It is for internal usage only. * Use other funtions to get account info, like getInfoById, etc. * @param string $sField database field name * @param mixed $sValue database field value * @return array with porfile info */ protected function _getDataByField ($sField, $sValue) { $sSql = $this->prepare("SELECT * FROM `sys_accounts` WHERE `$sField` = ? LIMIT 1", $sValue); return $this->getRow($sSql); } /** * Get account info by id * @param int $iID account id * @return array with account info */ public function getInfoById( $iID ) { return $this->_getDataByField('id', (int)$iID); } /** * get account id by emial */ public function getIdByEmail($sEmail) { return (int)$this->_getFieldByField('id', 'email', $sEmail); } /** * get account id by id */ public function getIdById($iId) { return (int)$this->_getFieldByField('id', 'id', $iId); } /** * get first studio operator id */ public function getStudioOperatorId() { return (int)$this->_getFieldByField('id', 'role', 3); } /** * Get account email by id * @param string $s search account by this id * @return account email */ public function getEmail($iID) { return $this->_getFieldByField('email', 'id', (int)$iID); } /** * Get account password by id * @param string $s search account by this id * @return account password */ public function getPassword($iID) { return $this->_getFieldByField('password', 'id', (int)$iID); } /** * Is account online by id * @param int $iId account id * @return account online status */ public function isOnline($iId) { $sSql = $this->prepare("SELECT `ta`.`id` FROM `sys_accounts` AS `ta` INNER JOIN `sys_sessions` AS `ts` ON `ta`.`id`=`ts`.`user_id` WHERE `ta`.`id` = ? AND `ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?) LIMIT 1", $iId, (int)getParam('sys_account_online_time')); return (int)$this->getOne($sSql) > 0; } /** * Update last logged in time * @param $sPasswordHash - password hash * @param $sSalt - pasword salt * @param $iAccountId - account id to update password for * @return number of affected rows */ public function updatePassword($sPasswordHash, $sSalt, $iAccountId) { $sQuery = $this->prepare("UPDATE `sys_accounts` SET `password` = ?, `salt` = ? WHERE `id`= ?", $sPasswordHash, $sSalt, $iAccountId); return $this->query($sQuery); } /** * Update last logged in time * @param int $iID account id * @return number of affected rows */ public function updateLoggedIn($iID) { return $this->_updateField ($iID, 'logged', time()); } /** * Update language * @param int $iID account id * @return number of affected rows */ public function updateLanguage($iID, $iLangId) { return $this->_updateField ($iID, 'lang_id', $iLangId); } /** * Update current profile id associated with account * @param int $iID account id * @param int $iProfileId set current profile id to this value * @return number of affected rows */ public function updateCurrentProfile($iID, $iProfileId) { return $this->_updateField ($iID, 'profile_id', $iProfileId); } /** * Update 'email_confirmed' field. * @param int $isConfirmed - 0: mark email as unconfirmed, 1: as confirmed * @param int $iID - account id * @return number of affected rows */ public function updateEmailConfirmed($isConfirmed, $iID) { return $this->_updateField ($iID, 'email_confirmed', $isConfirmed ? 1 : 0); } /** * Get account field by specified field name and value. * In most cases it is for internal usage only. * Use other funtions to get account info, like getIdByEmail, etc. * @param string $sFieldRequested database field name to return * @param string $sFieldSearch database field name to search for * @param mixed $sValue database field value * @return specified account field value */ protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue) { $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_accounts` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue); return $this->getOne($sSql); } /** * Update some field by account id * In most cases it is for internal usage only. * Use other funtions to get account info, like updateLogged, etc. * @param string $sFieldRequested database field name to return * @param string $sFieldSearch database field name to search for * @param mixed $sValue database field value * @return specified account field value */ protected function _updateField ($iId, $sFieldForUpdate, $sValue) { $sSql = $this->prepare("UPDATE `sys_accounts` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId); return $this->query($sSql); } /** * Delete account info by id * @param int $iID profile id * @return affected rows */ public function delete($iID) { $sSql = $this->prepare("DELETE FROM `sys_accounts` WHERE `id` = ? LIMIT 1", $iID); return $this->query($sSql); } /** * Get account(s) by params * @param array $aParams browse params * @return array with account(s) */ public function getAccounts($aParams) { $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query')); $sFieldsClause = "`ta`.*"; $sJoinClause = $sWhereClause = $sGroupClause = $sOrderClause = ""; switch($aParams['type']) { case 'by_join_date': $aMethod['params'][1] = array( 'date' => $aParams['date'] ); $sWhereClause = " AND `ta`.`added` > :date AND `ta`.`added` < UNIX_TIMESTAMP()"; break; } $sGroupClause = $sGroupClause ? "GROUP BY " . $sGroupClause : ""; $sOrderClause = $sOrderClause ? "ORDER BY " . $sOrderClause : ""; $aMethod['params'][0] = "SELECT " . $sFieldsClause . " FROM `sys_accounts` AS `ta`" . $sJoinClause . " WHERE 1" . $sWhereClause . " " . $sGroupClause . " " . $sOrderClause; return call_user_func_array(array($this, $aMethod['name']), $aMethod['params']); } /** * Search account profile by keyword */ public function searchByTerm($sTerm, $iLimit) { $aBindings = array( 'system' => 'system', 'status' => BX_PROFILE_STATUS_ACTIVE, 'limit' => (int)$iLimit ); $sWhere = ''; $aFieldsQuickSearch = array('name', 'email'); foreach ($aFieldsQuickSearch as $sField) { $aBindings[$sField] = '%' . $sTerm . '%'; $sWhere .= " OR `c`.`$sField` LIKE :$sField "; } $sQuery = "SELECT `c`.`id` AS `content_id`, `p`.`account_id`, `p`.`id` AS `profile_id`, `p`.`status` AS `profile_status` FROM `sys_accounts` AS `c` INNER JOIN `sys_profiles` AS `p` ON (`p`.`content_id` = `c`.`id` AND `p`.`type` = :system) WHERE `p`.`status` = :status AND (0 $sWhere) ORDER BY `added` DESC LIMIT :limit"; return $this->getAll($sQuery, $aBindings); } } /** @} */
{ "content_hash": "7479304dc41a69b0527eb840d40f6b6c", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 328, "avg_line_length": 31.329787234042552, "alnum_prop": 0.5723825693265422, "repo_name": "camperjz/trident", "id": "0197d04abbfd0d5f2d3f8500224e1363c487fc9e", "size": "8980", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "upgrade/files/9.0.0.B5-9.0.0.RC1/files/inc/classes/BxDolAccountQuery.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1763" }, { "name": "CSS", "bytes": "1481231" }, { "name": "HTML", "bytes": "690596" }, { "name": "JavaScript", "bytes": "4916309" }, { "name": "PHP", "bytes": "28451148" }, { "name": "Shell", "bytes": "1265" } ], "symlink_target": "" }
/** * @file * This file provides defines non-public portion of NLGenericUpdatableDataSink interface. * This is WEAVE_CONFIG_DATA_MANAGEMENT_EXPERIMENTAL feature. * */ #include <Weave/Core/WeaveCore.h> #include <WeaveDataManagementClient.h> #import "NLGenericTraitUpdatableDataSink.h" #if WEAVE_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL @interface NLGenericTraitUpdatableDataSink () - (instancetype)init:(NSString *)name weaveWorkQueue:(dispatch_queue_t)weaveWorkQueue appCallbackQueue:(dispatch_queue_t)appCallbackQueue genericTraitUpdatableDataSinkPtr:(nl::Weave::DeviceManager::GenericTraitUpdatableDataSink *)dataSinkPtr nlWdmClient:(NLWdmClient *)nlWdmClient NS_DESIGNATED_INITIALIZER; - (NSString *)statusReportToString:(NSUInteger)profileId statusCode:(NSInteger)statusCode; /** * @brief Forcifully release all resources and destroy all references. * */ - (void)close; @end #endif // WEAVE_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL
{ "content_hash": "8f142b905d43e6149d78690d0be40217", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 107, "avg_line_length": 35.793103448275865, "alnum_prop": 0.7408477842003853, "repo_name": "openweave/openweave-core", "id": "b286ed3709a154e07c177f0eeb5ebe68a4cdf6d9", "size": "1696", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/device-manager/cocoa/NLGenericTraitUpdatableDataSink_Protected.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "664311" }, { "name": "C++", "bytes": "13369518" }, { "name": "Java", "bytes": "300780" }, { "name": "M4", "bytes": "115889" }, { "name": "Makefile", "bytes": "354863" }, { "name": "Objective-C", "bytes": "126850" }, { "name": "Objective-C++", "bytes": "302756" }, { "name": "Perl", "bytes": "12136" }, { "name": "Python", "bytes": "2029596" }, { "name": "Shell", "bytes": "122005" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using UnityEngine.UI.Windows.Plugins.Flow; using UnityEngine.UI.Windows.Plugins.Heatmap.Events; namespace UnityEngine.UI.Windows.Plugins.Heatmap.Core { public class HeatmapSettings : ScriptableObject { [System.Serializable] public struct Point { [System.Serializable] public struct ComponentInfo { [Header("Tag")] public LayoutTag tag; [Header("Coords (Absolute)")] public float x; public float y; public float w; public float h; public ComponentInfo(LayoutTag tag, WindowComponent component) { this.tag = tag; this.x = 0f; this.y = 0f; this.w = 0f; this.h = 0f; //var rect = (component.transform as RectTransform).rect; var corners = new Vector3[4]; (component.transform as RectTransform).GetWorldCorners(corners); var leftBottom = this.GetScreenPoint(component, corners[0]); var topRight = this.GetScreenPoint(component, corners[2]); this.x = leftBottom.x; this.y = leftBottom.y; this.w = topRight.x - leftBottom.x; this.h = topRight.y - leftBottom.y; } private Vector3 GetScreenPoint(WindowComponent component, Vector3 worldPoint) { return component.GetWindow().workCamera.WorldToScreenPoint(worldPoint); } } [Header("Coords (Normalized)")] // Normalized (x, y) coords public float x; public float y; [Header("Container")] public ComponentInfo componentInfo; public Point(Vector2 point, LayoutTag tag, WindowComponent component) { this.x = point.x; this.y = point.y; this.componentInfo = new ComponentInfo(tag, component); } public float GetAbsoluteX(float screenWidth) { // Container offset + unnormalized current point (x, y) return this.componentInfo.x + this.x * this.componentInfo.w; } public float GetAbsoluteY(float screenHeight) { // Container offset + unnormalized current point (x, y) return this.componentInfo.y + this.y * this.componentInfo.h; } }; [System.Serializable] public class WindowsData { [System.Serializable] public class Window { public enum Status { NoData = 0, Loading = 1, Loaded = 2, } public int id; public Status status = Status.NoData; public Texture2D texture = null; public Vector2 size; public List<Point> points = new List<Point>(); public bool changed = false; public Window(FlowWindow source) { this.id = source.id; } public void AddPoint(Vector2 point, LayoutTag tag, WindowComponent component) { this.points.Add(new Point(point, tag, component)); this.changed = true; this.UpdateMap(); } public List<Point> GetPoints() { return this.points; } public void Serialize() { } public void Deserialize() { } public void UpdateMap() { if (this.texture == null) this.texture = new Texture2D((int)this.size.x, (int)this.size.y, TextureFormat.ARGB32, false); if (this.changed == false) return; this.texture = HeatmapVisualizer.Create(this.texture, this.GetPoints(), this.size); this.changed = false; } public void SetChanged() { this.changed = true; } } public List<Window> list = new List<Window>(); public Window Get(FlowWindow window) { Window result = null; this.list.RemoveAll((info) => { var w = Flow.FlowSystem.GetWindow(info.id); return w == null; }); foreach (var item in this.list) { if (item.id == window.id) { result = item; break; } } if (result == null) { result = new Window(window); this.list.Add(result); } return result; } public void SetChanged() { foreach (var item in this.list) item.SetChanged(); } } public bool show; public string key; public WindowsData data; public void SetChanged() { this.data.SetChanged(); } #if UNITY_EDITOR [UnityEditor.MenuItem("Assets/Create/UI Windows/Heatmap/Settings")] public static void CreateInstance() { ME.EditorUtilities.CreateAsset<HeatmapSettings>(); } #endif } }
{ "content_hash": "d100dd0aae752048bfe7a239767d4031", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 125, "avg_line_length": 19.36725663716814, "alnum_prop": 0.6262280100525474, "repo_name": "zhaoluxyz/Unity3d.UI.Windows", "id": "1a3f2c8ba44e196de6c4ce843c8531b03bdd532d", "size": "4379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/UI.Windows/Addons/Heatmap/Core/HeatmapSettings.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1005686" }, { "name": "GLSL", "bytes": "12217" }, { "name": "HTML", "bytes": "14147" }, { "name": "JavaScript", "bytes": "3097" } ], "symlink_target": "" }
using NHS111.Utils.IoC; using StructureMap.Configuration.DSL; using StructureMap.Graph; namespace NHS111.Web.Presentation.IoC { public class WebPresentationRegistry : Registry { public WebPresentationRegistry() { IncludeRegistry<UtilsRegistry>(); Scan(scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); }); } } }
{ "content_hash": "c83b78f0bffdf5f04f892fbee09fc6f6", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 51, "avg_line_length": 22.4, "alnum_prop": 0.5848214285714286, "repo_name": "AndriaTurner/nhs111-dotnet-beta", "id": "f624df0a8a6a9e443ec82b31b08c924353742b9a", "size": "450", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "NHS111/NHS111.Web.Presentation/IoC/WebPresentationRegistry.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "678" }, { "name": "Batchfile", "bytes": "1026" }, { "name": "C#", "bytes": "562814" }, { "name": "CSS", "bytes": "245369" }, { "name": "HTML", "bytes": "62338" }, { "name": "JavaScript", "bytes": "90789" } ], "symlink_target": "" }
using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Insights.Models { public partial class ActivityLogAlertPatchBody : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsCollectionDefined(Tags)) { writer.WritePropertyName("tags"); writer.WriteStartObject(); foreach (var item in Tags) { writer.WritePropertyName(item.Key); writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsDefined(Enabled)) { writer.WritePropertyName("enabled"); writer.WriteBooleanValue(Enabled.Value); } writer.WriteEndObject(); writer.WriteEndObject(); } } }
{ "content_hash": "229b218898521a01ae8afc90141a8068", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 74, "avg_line_length": 32.09090909090909, "alnum_prop": 0.5486307837582625, "repo_name": "markcowl/azure-sdk-for-net", "id": "3469a65c4e9ec8895ed16a2b98b38b48a0e306ce", "size": "1197", "binary": false, "copies": "6", "ref": "refs/heads/ext-resource", "path": "sdk/insights/Azure.ResourceManager.Insights/src/Generated/Models/ActivityLogAlertPatchBody.Serialization.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "13482080" }, { "name": "PowerShell", "bytes": "3408" } ], "symlink_target": "" }
package org.elasticsearch.test; import com.carrotsearch.hppc.ObjectLongMap; import com.carrotsearch.randomizedtesting.RandomizedContext; import com.carrotsearch.randomizedtesting.annotations.TestGroup; import com.carrotsearch.randomizedtesting.generators.RandomNumbers; import com.carrotsearch.randomizedtesting.generators.RandomPicks; import org.apache.http.HttpHost; import org.apache.lucene.search.Sort; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.action.admin.indices.flush.FlushResponse; import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeResponse; import org.elasticsearch.action.admin.indices.get.GetIndexResponse; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.admin.indices.segments.IndexSegments; import org.elasticsearch.action.admin.indices.segments.IndexShardSegments; import org.elasticsearch.action.admin.indices.segments.IndicesSegmentResponse; import org.elasticsearch.action.admin.indices.segments.ShardSegments; import org.elasticsearch.action.admin.indices.stats.IndexShardStats; import org.elasticsearch.action.admin.indices.stats.IndexStats; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.admin.indices.stats.ShardStats; import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequestBuilder; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.ClearScrollResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.AdminClient; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings; import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Priority; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.network.NetworkAddress; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.discovery.Discovery; import org.elasticsearch.discovery.zen.ElectMasterService; import org.elasticsearch.discovery.zen.ZenDiscovery; import org.elasticsearch.env.Environment; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexModule; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.MergePolicyConfig; import org.elasticsearch.index.MergeSchedulerConfig; import org.elasticsearch.index.MockEngineFactoryPlugin; import org.elasticsearch.index.codec.CodecService; import org.elasticsearch.index.engine.Segment; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.MockFieldFilterPlugin; import org.elasticsearch.index.seqno.SeqNoStats; import org.elasticsearch.index.seqno.SequenceNumbers; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.indices.IndicesQueryCache; import org.elasticsearch.indices.IndicesRequestCache; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.store.IndicesStore; import org.elasticsearch.node.NodeMocksPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.MockSearchService; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchService; import org.elasticsearch.test.client.RandomizingClient; import org.elasticsearch.test.discovery.TestZenDiscovery; import org.elasticsearch.test.disruption.NetworkDisruption; import org.elasticsearch.test.disruption.ServiceDisruptionScheme; import org.elasticsearch.test.store.MockFSIndexStore; import org.elasticsearch.test.transport.MockTransportService; import org.elasticsearch.transport.AssertingTransportInterceptor; import org.hamcrest.Matchers; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.elasticsearch.client.Requests.syncedFlushRequest; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.util.CollectionUtils.eagerPartition; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.test.XContentTestUtils.convertToMap; import static org.elasticsearch.test.XContentTestUtils.differenceBetweenMapsIgnoringArrayOrder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoTimeout; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.emptyArray; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; /** * {@link ESIntegTestCase} is an abstract base class to run integration * tests against a JVM private Elasticsearch Cluster. The test class supports 2 different * cluster scopes. * <ul> * <li>{@link Scope#TEST} - uses a new cluster for each individual test method.</li> * <li>{@link Scope#SUITE} - uses a cluster shared across all test methods in the same suite</li> * </ul> * <p> * The most common test scope is {@link Scope#SUITE} which shares a cluster per test suite. * <p> * If the test methods need specific node settings or change persistent and/or transient cluster settings {@link Scope#TEST} * should be used. To configure a scope for the test cluster the {@link ClusterScope} annotation * should be used, here is an example: * <pre> * * {@literal @}NodeScope(scope=Scope.TEST) public class SomeIT extends ESIntegTestCase { * public void testMethod() {} * } * </pre> * <p> * If no {@link ClusterScope} annotation is present on an integration test the default scope is {@link Scope#SUITE} * <p> * A test cluster creates a set of nodes in the background before the test starts. The number of nodes in the cluster is * determined at random and can change across tests. The {@link ClusterScope} allows configuring the initial number of nodes * that are created before the tests start. * <pre> * {@literal @}NodeScope(scope=Scope.SUITE, numDataNodes=3) * public class SomeIT extends ESIntegTestCase { * public void testMethod() {} * } * </pre> * <p> * Note, the {@link ESIntegTestCase} uses randomized settings on a cluster and index level. For instance * each test might use different directory implementation for each test or will return a random client to one of the * nodes in the cluster for each call to {@link #client()}. Test failures might only be reproducible if the correct * system properties are passed to the test execution environment. * <p> * This class supports the following system properties (passed with -Dkey=value to the application) * <ul> * <li>-D{@value #TESTS_CLIENT_RATIO} - a double value in the interval [0..1] which defines the ration between node and transport clients used</li> * <li>-D{@value #TESTS_ENABLE_MOCK_MODULES} - a boolean value to enable or disable mock modules. This is * useful to test the system without asserting modules that to make sure they don't hide any bugs in production.</li> * <li> - a random seed used to initialize the index random context. * </ul> */ @LuceneTestCase.SuppressFileSystems("ExtrasFS") // doesn't work with potential multi data path from test cluster yet public abstract class ESIntegTestCase extends ESTestCase { /** * Property that controls whether ThirdParty Integration tests are run (not the default). */ public static final String SYSPROP_THIRDPARTY = "tests.thirdparty"; /** * Annotation for third-party integration tests. * <p> * These are tests the require a third-party service in order to run. They * may require the user to manually configure an external process (such as rabbitmq), * or may additionally require some external configuration (e.g. AWS credentials) * via the {@code tests.config} system property. */ @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @TestGroup(enabled = false, sysProperty = ESIntegTestCase.SYSPROP_THIRDPARTY) public @interface ThirdParty { } /** node names of the corresponding clusters will start with these prefixes */ public static final String SUITE_CLUSTER_NODE_PREFIX = "node_s"; public static final String TEST_CLUSTER_NODE_PREFIX = "node_t"; /** * Key used to set the transport client ratio via the commandline -D{@value #TESTS_CLIENT_RATIO} */ public static final String TESTS_CLIENT_RATIO = "tests.client.ratio"; /** * Key used to eventually switch to using an external cluster and provide its transport addresses */ public static final String TESTS_CLUSTER = "tests.cluster"; /** * Key used to retrieve the index random seed from the index settings on a running node. * The value of this seed can be used to initialize a random context for a specific index. * It's set once per test via a generic index template. */ public static final Setting<Long> INDEX_TEST_SEED_SETTING = Setting.longSetting("index.tests.seed", 0, Long.MIN_VALUE, Property.IndexScope); /** * A boolean value to enable or disable mock modules. This is useful to test the * system without asserting modules that to make sure they don't hide any bugs in * production. * * @see ESIntegTestCase */ public static final String TESTS_ENABLE_MOCK_MODULES = "tests.enable_mock_modules"; private static final boolean MOCK_MODULES_ENABLED = "true".equals(System.getProperty(TESTS_ENABLE_MOCK_MODULES, "true")); /** * Threshold at which indexing switches from frequently async to frequently bulk. */ private static final int FREQUENT_BULK_THRESHOLD = 300; /** * Threshold at which bulk indexing will always be used. */ private static final int ALWAYS_BULK_THRESHOLD = 3000; /** * Maximum number of async operations that indexRandom will kick off at one time. */ private static final int MAX_IN_FLIGHT_ASYNC_INDEXES = 150; /** * Maximum number of documents in a single bulk index request. */ private static final int MAX_BULK_INDEX_REQUEST_SIZE = 1000; /** * Default minimum number of shards for an index */ protected static final int DEFAULT_MIN_NUM_SHARDS = 1; /** * Default maximum number of shards for an index */ protected static final int DEFAULT_MAX_NUM_SHARDS = 10; /** * The current cluster depending on the configured {@link Scope}. * By default if no {@link ClusterScope} is configured this will hold a reference to the suite cluster. */ private static TestCluster currentCluster; private static RestClient restClient = null; private static final double TRANSPORT_CLIENT_RATIO = transportClientRatio(); private static final Map<Class<?>, TestCluster> clusters = new IdentityHashMap<>(); private static ESIntegTestCase INSTANCE = null; // see @SuiteScope private static Long SUITE_SEED = null; @BeforeClass public static void beforeClass() throws Exception { SUITE_SEED = randomLong(); initializeSuiteScope(); } @Override protected final boolean enableWarningsCheck() { //In an integ test it doesn't make sense to keep track of warnings: if the cluster is external the warnings are in another jvm, //if the cluster is internal the deprecation logger is shared across all nodes return false; } protected final void beforeInternal() throws Exception { final Scope currentClusterScope = getCurrentClusterScope(); switch (currentClusterScope) { case SUITE: assert SUITE_SEED != null : "Suite seed was not initialized"; currentCluster = buildAndPutCluster(currentClusterScope, SUITE_SEED); break; case TEST: currentCluster = buildAndPutCluster(currentClusterScope, randomLong()); break; default: fail("Unknown Scope: [" + currentClusterScope + "]"); } cluster().beforeTest(random(), getPerTestTransportClientRatio()); cluster().wipe(excludeTemplates()); randomIndexTemplate(); } private void printTestMessage(String message) { if (isSuiteScopedTest(getClass()) && (getTestName().equals("<unknown>"))) { logger.info("[{}]: {} suite", getTestClass().getSimpleName(), message); } else { logger.info("[{}#{}]: {} test", getTestClass().getSimpleName(), getTestName(), message); } } /** * Creates a randomized index template. This template is used to pass in randomized settings on a * per index basis. Allows to enable/disable the randomization for number of shards and replicas */ public void randomIndexTemplate() throws IOException { // TODO move settings for random directory etc here into the index based randomized settings. if (cluster().size() > 0) { Settings.Builder randomSettingsBuilder = setRandomIndexSettings(random(), Settings.builder()); if (isInternalCluster()) { // this is only used by mock plugins and if the cluster is not internal we just can't set it randomSettingsBuilder.put(INDEX_TEST_SEED_SETTING.getKey(), random().nextLong()); } randomSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, numberOfShards()) .put(SETTING_NUMBER_OF_REPLICAS, numberOfReplicas()); // if the test class is annotated with SuppressCodecs("*"), it means don't use lucene's codec randomization // otherwise, use it, it has assertions and so on that can find bugs. SuppressCodecs annotation = getClass().getAnnotation(SuppressCodecs.class); if (annotation != null && annotation.value().length == 1 && "*".equals(annotation.value()[0])) { randomSettingsBuilder.put("index.codec", randomFrom(CodecService.DEFAULT_CODEC, CodecService.BEST_COMPRESSION_CODEC)); } else { randomSettingsBuilder.put("index.codec", CodecService.LUCENE_DEFAULT_CODEC); } for (String setting : randomSettingsBuilder.keys()) { assertThat("non index. prefix setting set on index template, its a node setting...", setting, startsWith("index.")); } // always default delayed allocation to 0 to make sure we have tests are not delayed randomSettingsBuilder.put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), 0); if (randomBoolean()) { randomSettingsBuilder.put(IndexModule.INDEX_QUERY_CACHE_ENABLED_SETTING.getKey(), randomBoolean()); } if (randomBoolean()) { randomSettingsBuilder.put(IndexModule.INDEX_QUERY_CACHE_EVERYTHING_SETTING.getKey(), randomBoolean()); } PutIndexTemplateRequestBuilder putTemplate = client().admin().indices() .preparePutTemplate("random_index_template") .setPatterns(Collections.singletonList("*")) .setOrder(0) .setSettings(randomSettingsBuilder); assertAcked(putTemplate.execute().actionGet()); } } protected Settings.Builder setRandomIndexSettings(Random random, Settings.Builder builder) { setRandomIndexMergeSettings(random, builder); setRandomIndexTranslogSettings(random, builder); if (random.nextBoolean()) { builder.put(MergeSchedulerConfig.AUTO_THROTTLE_SETTING.getKey(), false); } if (random.nextBoolean()) { builder.put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), random.nextBoolean()); } if (random.nextBoolean()) { builder.put(IndexSettings.INDEX_CHECK_ON_STARTUP.getKey(), randomFrom("false", "checksum", "true")); } if (randomBoolean()) { // keep this low so we don't stall tests builder.put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), RandomNumbers.randomIntBetween(random, 1, 15) + "ms"); } return builder; } private static Settings.Builder setRandomIndexMergeSettings(Random random, Settings.Builder builder) { if (random.nextBoolean()) { builder.put(MergePolicyConfig.INDEX_COMPOUND_FORMAT_SETTING.getKey(), (random.nextBoolean() ? random.nextDouble() : random.nextBoolean()).toString()); } switch (random.nextInt(4)) { case 3: final int maxThreadCount = RandomNumbers.randomIntBetween(random, 1, 4); final int maxMergeCount = RandomNumbers.randomIntBetween(random, maxThreadCount, maxThreadCount + 4); builder.put(MergeSchedulerConfig.MAX_MERGE_COUNT_SETTING.getKey(), maxMergeCount); builder.put(MergeSchedulerConfig.MAX_THREAD_COUNT_SETTING.getKey(), maxThreadCount); break; } return builder; } private static Settings.Builder setRandomIndexTranslogSettings(Random random, Settings.Builder builder) { if (random.nextBoolean()) { builder.put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), new ByteSizeValue(RandomNumbers.randomIntBetween(random, 1, 300), ByteSizeUnit.MB)); } if (random.nextBoolean()) { builder.put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), new ByteSizeValue(1, ByteSizeUnit.PB)); // just don't flush } if (random.nextBoolean()) { builder.put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), RandomPicks.randomFrom(random, Translog.Durability.values())); } if (random.nextBoolean()) { builder.put(IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING.getKey(), RandomNumbers.randomIntBetween(random, 100, 5000), TimeUnit.MILLISECONDS); } return builder; } private TestCluster buildWithPrivateContext(final Scope scope, final long seed) throws Exception { return RandomizedContext.current().runWithPrivateRandomness(seed, new Callable<TestCluster>() { @Override public TestCluster call() throws Exception { return buildTestCluster(scope, seed); } }); } private TestCluster buildAndPutCluster(Scope currentClusterScope, long seed) throws Exception { final Class<?> clazz = this.getClass(); TestCluster testCluster = clusters.remove(clazz); // remove this cluster first clearClusters(); // all leftovers are gone by now... this is really just a double safety if we miss something somewhere switch (currentClusterScope) { case SUITE: if (testCluster == null) { // only build if it's not there yet testCluster = buildWithPrivateContext(currentClusterScope, seed); } break; case TEST: // close the previous one and create a new one IOUtils.closeWhileHandlingException(testCluster); testCluster = buildTestCluster(currentClusterScope, seed); break; } clusters.put(clazz, testCluster); return testCluster; } private static void clearClusters() throws IOException { if (!clusters.isEmpty()) { IOUtils.close(clusters.values()); clusters.clear(); } if (restClient != null) { restClient.close(); restClient = null; } } protected final void afterInternal(boolean afterClass) throws Exception { boolean success = false; try { final Scope currentClusterScope = getCurrentClusterScope(); clearDisruptionScheme(); try { if (cluster() != null) { if (currentClusterScope != Scope.TEST) { MetaData metaData = client().admin().cluster().prepareState().execute().actionGet().getState().getMetaData(); final Set<String> persistent = metaData.persistentSettings().keySet(); assertThat("test leaves persistent cluster metadata behind: " + persistent, persistent.size(), equalTo(0)); final Set<String> transientSettings = new HashSet<>(metaData.transientSettings().keySet()); if (isInternalCluster() && internalCluster().getAutoManageMinMasterNode()) { // this is set by the test infra transientSettings.remove(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey()); } assertThat("test leaves transient cluster metadata behind: " + transientSettings, transientSettings, empty()); } ensureClusterSizeConsistency(); ensureClusterStateConsistency(); if (isInternalCluster()) { // check no pending cluster states are leaked for (Discovery discovery : internalCluster().getInstances(Discovery.class)) { if (discovery instanceof ZenDiscovery) { final ZenDiscovery zenDiscovery = (ZenDiscovery) discovery; assertBusy(() -> { final ClusterState[] states = zenDiscovery.pendingClusterStates(); assertThat(zenDiscovery.clusterState().nodes().getLocalNode().getName() + " still having pending states:\n" + Stream.of(states).map(ClusterState::toString).collect(Collectors.joining("\n")), states, emptyArray()); }); } } } beforeIndexDeletion(); cluster().wipe(excludeTemplates()); // wipe after to make sure we fail in the test that didn't ack the delete if (afterClass || currentClusterScope == Scope.TEST) { cluster().close(); } cluster().assertAfterTest(); } } finally { if (currentClusterScope == Scope.TEST) { clearClusters(); // it is ok to leave persistent / transient cluster state behind if scope is TEST } } success = true; } finally { if (!success) { // if we failed here that means that something broke horribly so we should clear all clusters // TODO: just let the exception happen, WTF is all this horseshit // afterTestRule.forceFailure(); } } } /** * @return An exclude set of index templates that will not be removed in between tests. */ protected Set<String> excludeTemplates() { return Collections.emptySet(); } protected void beforeIndexDeletion() throws Exception { cluster().beforeIndexDeletion(); } public static TestCluster cluster() { return currentCluster; } public static boolean isInternalCluster() { return (currentCluster instanceof InternalTestCluster); } public static InternalTestCluster internalCluster() { if (!isInternalCluster()) { throw new UnsupportedOperationException("current test cluster is immutable"); } return (InternalTestCluster) currentCluster; } public ClusterService clusterService() { return internalCluster().clusterService(); } public static Client client() { return client(null); } public static Client client(@Nullable String node) { if (node != null) { return internalCluster().client(node); } Client client = cluster().client(); if (frequently()) { client = new RandomizingClient(client, random()); } return client; } public static Client dataNodeClient() { Client client = internalCluster().dataNodeClient(); if (frequently()) { client = new RandomizingClient(client, random()); } return client; } public static Iterable<Client> clients() { return cluster().getClients(); } protected int minimumNumberOfShards() { return DEFAULT_MIN_NUM_SHARDS; } protected int maximumNumberOfShards() { return DEFAULT_MAX_NUM_SHARDS; } protected int numberOfShards() { return between(minimumNumberOfShards(), maximumNumberOfShards()); } protected int minimumNumberOfReplicas() { return 0; } protected int maximumNumberOfReplicas() { //use either 0 or 1 replica, yet a higher amount when possible, but only rarely int maxNumReplicas = Math.max(0, cluster().numDataNodes() - 1); return frequently() ? Math.min(1, maxNumReplicas) : maxNumReplicas; } protected int numberOfReplicas() { return between(minimumNumberOfReplicas(), maximumNumberOfReplicas()); } public void setDisruptionScheme(ServiceDisruptionScheme scheme) { internalCluster().setDisruptionScheme(scheme); } public void clearDisruptionScheme() { if (isInternalCluster()) { internalCluster().clearDisruptionScheme(); } } /** * Returns a settings object used in {@link #createIndex(String...)} and {@link #prepareCreate(String)} and friends. * This method can be overwritten by subclasses to set defaults for the indices that are created by the test. * By default it returns a settings object that sets a random number of shards. Number of shards and replicas * can be controlled through specific methods. */ public Settings indexSettings() { Settings.Builder builder = Settings.builder(); int numberOfShards = numberOfShards(); if (numberOfShards > 0) { builder.put(SETTING_NUMBER_OF_SHARDS, numberOfShards).build(); } int numberOfReplicas = numberOfReplicas(); if (numberOfReplicas >= 0) { builder.put(SETTING_NUMBER_OF_REPLICAS, numberOfReplicas).build(); } // 30% of the time if (randomInt(9) < 3) { final String dataPath = randomAlphaOfLength(10); logger.info("using custom data_path for index: [{}]", dataPath); builder.put(IndexMetaData.SETTING_DATA_PATH, dataPath); } // always default delayed allocation to 0 to make sure we have tests are not delayed builder.put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), 0); return builder.build(); } /** * Creates one or more indices and asserts that the indices are acknowledged. If one of the indices * already exists this method will fail and wipe all the indices created so far. */ public final void createIndex(String... names) { List<String> created = new ArrayList<>(); for (String name : names) { boolean success = false; try { assertAcked(prepareCreate(name)); created.add(name); success = true; } finally { if (!success && !created.isEmpty()) { cluster().wipeIndices(created.toArray(new String[created.size()])); } } } } /** * creates an index with the given setting */ public final void createIndex(String name, Settings indexSettings) { assertAcked(prepareCreate(name).setSettings(indexSettings)); } /** * Creates a new {@link CreateIndexRequestBuilder} with the settings obtained from {@link #indexSettings()}. */ public final CreateIndexRequestBuilder prepareCreate(String index) { return prepareCreate(index, -1); } /** * Creates a new {@link CreateIndexRequestBuilder} with the settings obtained from {@link #indexSettings()}. * The index that is created with this builder will only be allowed to allocate on the number of nodes passed to this * method. * <p> * This method uses allocation deciders to filter out certain nodes to allocate the created index on. It defines allocation * rules based on <code>index.routing.allocation.exclude._name</code>. * </p> */ public final CreateIndexRequestBuilder prepareCreate(String index, int numNodes) { return prepareCreate(index, numNodes, Settings.builder()); } /** * Creates a new {@link CreateIndexRequestBuilder} with the settings obtained from {@link #indexSettings()}, augmented * by the given builder */ public CreateIndexRequestBuilder prepareCreate(String index, Settings.Builder settingsBuilder) { return prepareCreate(index, -1, settingsBuilder); } /** * Creates a new {@link CreateIndexRequestBuilder} with the settings obtained from {@link #indexSettings()}. * The index that is created with this builder will only be allowed to allocate on the number of nodes passed to this * method. * <p> * This method uses allocation deciders to filter out certain nodes to allocate the created index on. It defines allocation * rules based on <code>index.routing.allocation.exclude._name</code>. * </p> */ public CreateIndexRequestBuilder prepareCreate(String index, int numNodes, Settings.Builder settingsBuilder) { Settings.Builder builder = Settings.builder().put(indexSettings()).put(settingsBuilder.build()); if (numNodes > 0) { internalCluster().ensureAtLeastNumDataNodes(numNodes); getExcludeSettings(index, numNodes, builder); } return client().admin().indices().prepareCreate(index).setSettings(builder.build()); } private Settings.Builder getExcludeSettings(String index, int num, Settings.Builder builder) { String exclude = String.join(",", internalCluster().allDataNodesButN(num)); builder.put("index.routing.allocation.exclude._name", exclude); return builder; } /** * Waits until all nodes have no pending tasks. */ public void waitNoPendingTasksOnAll() throws Exception { assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).get()); assertBusy(() -> { for (Client client : clients()) { ClusterHealthResponse clusterHealth = client.admin().cluster().prepareHealth().setLocal(true).get(); assertThat("client " + client + " still has in flight fetch", clusterHealth.getNumberOfInFlightFetch(), equalTo(0)); PendingClusterTasksResponse pendingTasks = client.admin().cluster().preparePendingClusterTasks().setLocal(true).get(); assertThat("client " + client + " still has pending tasks " + pendingTasks, pendingTasks, Matchers.emptyIterable()); clusterHealth = client.admin().cluster().prepareHealth().setLocal(true).get(); assertThat("client " + client + " still has in flight fetch", clusterHealth.getNumberOfInFlightFetch(), equalTo(0)); } }); assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).get()); } /** * Waits till a (pattern) field name mappings concretely exists on all nodes. Note, this waits for the current * started shards and checks for concrete mappings. */ public void assertConcreteMappingsOnAll(final String index, final String type, final String... fieldNames) throws Exception { Set<String> nodes = internalCluster().nodesInclude(index); assertThat(nodes, Matchers.not(Matchers.emptyIterable())); for (String node : nodes) { IndicesService indicesService = internalCluster().getInstance(IndicesService.class, node); IndexService indexService = indicesService.indexService(resolveIndex(index)); assertThat("index service doesn't exists on " + node, indexService, notNullValue()); DocumentMapper documentMapper = indexService.mapperService().documentMapper(type); assertThat("document mapper doesn't exists on " + node, documentMapper, notNullValue()); for (String fieldName : fieldNames) { Collection<String> matches = documentMapper.mappers().simpleMatchToFullName(fieldName); assertThat("field " + fieldName + " doesn't exists on " + node, matches, Matchers.not(emptyIterable())); } } assertMappingOnMaster(index, type, fieldNames); } /** * Waits for the given mapping type to exists on the master node. */ public void assertMappingOnMaster(final String index, final String type, final String... fieldNames) throws Exception { GetMappingsResponse response = client().admin().indices().prepareGetMappings(index).setTypes(type).get(); ImmutableOpenMap<String, MappingMetaData> mappings = response.getMappings().get(index); assertThat(mappings, notNullValue()); MappingMetaData mappingMetaData = mappings.get(type); assertThat(mappingMetaData, notNullValue()); Map<String, Object> mappingSource = mappingMetaData.getSourceAsMap(); assertFalse(mappingSource.isEmpty()); assertTrue(mappingSource.containsKey("properties")); for (String fieldName : fieldNames) { Map<String, Object> mappingProperties = (Map<String, Object>) mappingSource.get("properties"); if (fieldName.indexOf('.') != -1) { fieldName = fieldName.replace(".", ".properties."); } assertThat("field " + fieldName + " doesn't exists in mapping " + mappingMetaData.source().string(), XContentMapValues.extractValue(fieldName, mappingProperties), notNullValue()); } } /** Ensures the result counts are as expected, and logs the results if different */ public void assertResultsAndLogOnFailure(long expectedResults, SearchResponse searchResponse) { if (searchResponse.getHits().getTotalHits() != expectedResults) { StringBuilder sb = new StringBuilder("search result contains ["); sb.append(searchResponse.getHits().getTotalHits()).append("] results. expected [").append(expectedResults).append("]"); String failMsg = sb.toString(); for (SearchHit hit : searchResponse.getHits().getHits()) { sb.append("\n-> _index: [").append(hit.getIndex()).append("] type [").append(hit.getType()) .append("] id [").append(hit.getId()).append("]"); } logger.warn("{}", sb); fail(failMsg); } } /** * Restricts the given index to be allocated on <code>n</code> nodes using the allocation deciders. * Yet if the shards can't be allocated on any other node shards for this index will remain allocated on * more than <code>n</code> nodes. */ public void allowNodes(String index, int n) { assert index != null; internalCluster().ensureAtLeastNumDataNodes(n); Settings.Builder builder = Settings.builder(); if (n > 0) { getExcludeSettings(index, n, builder); } Settings build = builder.build(); if (!build.isEmpty()) { logger.debug("allowNodes: updating [{}]'s setting to [{}]", index, build.toDelimitedString(';')); client().admin().indices().prepareUpdateSettings(index).setSettings(build).execute().actionGet(); } } /** * Ensures the cluster has a green state via the cluster health API. This method will also wait for relocations. * It is useful to ensure that all action on the cluster have finished and all shards that were currently relocating * are now allocated and started. */ public ClusterHealthStatus ensureGreen(String... indices) { return ensureGreen(TimeValue.timeValueSeconds(30), indices); } /** * Ensures the cluster has a green state via the cluster health API. This method will also wait for relocations. * It is useful to ensure that all action on the cluster have finished and all shards that were currently relocating * are now allocated and started. * * @param timeout time out value to set on {@link org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest} */ public ClusterHealthStatus ensureGreen(TimeValue timeout, String... indices) { return ensureColor(ClusterHealthStatus.GREEN, timeout, indices); } /** * Ensures the cluster has a yellow state via the cluster health API. */ public ClusterHealthStatus ensureYellow(String... indices) { return ensureColor(ClusterHealthStatus.YELLOW, TimeValue.timeValueSeconds(30), indices); } private ClusterHealthStatus ensureColor(ClusterHealthStatus clusterHealthStatus, TimeValue timeout, String... indices) { String color = clusterHealthStatus.name().toLowerCase(Locale.ROOT); String method = "ensure" + Strings.capitalize(color); ClusterHealthRequest healthRequest = Requests.clusterHealthRequest(indices) .timeout(timeout) .waitForStatus(clusterHealthStatus) .waitForEvents(Priority.LANGUID) .waitForNoRelocatingShards(true) // We currently often use ensureGreen or ensureYellow to check whether the cluster is back in a good state after shutting down // a node. If the node that is stopped is the master node, another node will become master and publish a cluster state where it // is master but where the node that was stopped hasn't been removed yet from the cluster state. It will only subsequently // publish a second state where the old master is removed. If the ensureGreen/ensureYellow is timed just right, it will get to // execute before the second cluster state update removes the old master and the condition ensureGreen / ensureYellow will // trivially hold if it held before the node was shut down. The following "waitForNodes" condition ensures that the node has // been removed by the master so that the health check applies to the set of nodes we expect to be part of the cluster. .waitForNodes(Integer.toString(cluster().size())); ClusterHealthResponse actionGet = client().admin().cluster().health(healthRequest).actionGet(); if (actionGet.isTimedOut()) { logger.info("{} timed out, cluster state:\n{}\n{}", method, client().admin().cluster().prepareState().get().getState(), client().admin().cluster().preparePendingClusterTasks().get()); fail("timed out waiting for " + color + " state"); } assertThat("Expected at least " + clusterHealthStatus + " but got " + actionGet.getStatus(), actionGet.getStatus().value(), lessThanOrEqualTo(clusterHealthStatus.value())); logger.debug("indices {} are {}", indices.length == 0 ? "[_all]" : indices, color); return actionGet.getStatus(); } /** * Waits for all relocating shards to become active using the cluster health API. */ public ClusterHealthStatus waitForRelocation() { return waitForRelocation(null); } /** * Waits for all relocating shards to become active and the cluster has reached the given health status * using the cluster health API. */ public ClusterHealthStatus waitForRelocation(ClusterHealthStatus status) { ClusterHealthRequest request = Requests.clusterHealthRequest().waitForNoRelocatingShards(true); if (status != null) { request.waitForStatus(status); } ClusterHealthResponse actionGet = client().admin().cluster() .health(request).actionGet(); if (actionGet.isTimedOut()) { logger.info("waitForRelocation timed out (status={}), cluster state:\n{}\n{}", status, client().admin().cluster().prepareState().get().getState(), client().admin().cluster().preparePendingClusterTasks().get()); assertThat("timed out waiting for relocation", actionGet.isTimedOut(), equalTo(false)); } if (status != null) { assertThat(actionGet.getStatus(), equalTo(status)); } return actionGet.getStatus(); } /** * Waits until at least a give number of document is visible for searchers * * @param numDocs number of documents to wait for. * @return the actual number of docs seen. */ public long waitForDocs(final long numDocs) throws InterruptedException { return waitForDocs(numDocs, null); } /** * Waits until at least a give number of document is visible for searchers * * @param numDocs number of documents to wait for * @param indexer a {@link org.elasticsearch.test.BackgroundIndexer}. If supplied it will be first checked for documents indexed. * This saves on unneeded searches. * @return the actual number of docs seen. */ public long waitForDocs(final long numDocs, @Nullable final BackgroundIndexer indexer) throws InterruptedException { // indexing threads can wait for up to ~1m before retrying when they first try to index into a shard which is not STARTED. return waitForDocs(numDocs, 90, TimeUnit.SECONDS, indexer); } /** * Waits until at least a give number of document is visible for searchers * * @param numDocs number of documents to wait for * @param maxWaitTime if not progress have been made during this time, fail the test * @param maxWaitTimeUnit the unit in which maxWaitTime is specified * @param indexer a {@link org.elasticsearch.test.BackgroundIndexer}. If supplied it will be first checked for documents indexed. * This saves on unneeded searches. * @return the actual number of docs seen. */ public long waitForDocs(final long numDocs, int maxWaitTime, TimeUnit maxWaitTimeUnit, @Nullable final BackgroundIndexer indexer) throws InterruptedException { final AtomicLong lastKnownCount = new AtomicLong(-1); long lastStartCount = -1; BooleanSupplier testDocs = () -> { if (indexer != null) { lastKnownCount.set(indexer.totalIndexedDocs()); } if (lastKnownCount.get() >= numDocs) { try { long count = client().prepareSearch().setSize(0).setQuery(matchAllQuery()).execute().actionGet().getHits().getTotalHits(); if (count == lastKnownCount.get()) { // no progress - try to refresh for the next time client().admin().indices().prepareRefresh().get(); } lastKnownCount.set(count); } catch (Exception e) { // count now acts like search and barfs if all shards failed... logger.debug("failed to executed count", e); return false; } logger.debug("[{}] docs visible for search. waiting for [{}]", lastKnownCount.get(), numDocs); } else { logger.debug("[{}] docs indexed. waiting for [{}]", lastKnownCount.get(), numDocs); } return lastKnownCount.get() >= numDocs; }; while (!awaitBusy(testDocs, maxWaitTime, maxWaitTimeUnit)) { if (lastStartCount == lastKnownCount.get()) { // we didn't make any progress fail("failed to reach " + numDocs + "docs"); } lastStartCount = lastKnownCount.get(); } return lastKnownCount.get(); } /** * Sets the cluster's minimum master node and make sure the response is acknowledge. * Note: this doesn't guarantee that the new setting has taken effect, just that it has been received by all nodes. */ public void setMinimumMasterNodes(int n) { assertTrue(client().admin().cluster().prepareUpdateSettings().setTransientSettings( Settings.builder().put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), n)) .get().isAcknowledged()); } /** * Prints the current cluster state as debug logging. */ public void logClusterState() { logger.debug("cluster state:\n{}\n{}", client().admin().cluster().prepareState().get().getState(), client().admin().cluster().preparePendingClusterTasks().get()); } /** * Prints the segments info for the given indices as debug logging. */ public void logSegmentsState(String... indices) throws Exception { IndicesSegmentResponse segsRsp = client().admin().indices().prepareSegments(indices).get(); logger.debug("segments {} state: \n{}", indices.length == 0 ? "[_all]" : indices, segsRsp.toXContent(JsonXContent.contentBuilder().prettyPrint(), ToXContent.EMPTY_PARAMS).string()); } /** * Prints current memory stats as info logging. */ public void logMemoryStats() { logger.info("memory: {}", Strings.toString(client().admin().cluster().prepareNodesStats().clear().setJvm(true).get(), true, true)); } protected void ensureClusterSizeConsistency() { if (cluster() != null && cluster().size() > 0) { // if static init fails the cluster can be null logger.trace("Check consistency for [{}] nodes", cluster().size()); assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForNodes(Integer.toString(cluster().size())).get()); } } /** * Verifies that all nodes that have the same version of the cluster state as master have same cluster state */ protected void ensureClusterStateConsistency() throws IOException { if (cluster() != null && cluster().size() > 0) { final NamedWriteableRegistry namedWriteableRegistry = cluster().getNamedWriteableRegistry(); ClusterState masterClusterState = client().admin().cluster().prepareState().all().get().getState(); byte[] masterClusterStateBytes = ClusterState.Builder.toBytes(masterClusterState); // remove local node reference masterClusterState = ClusterState.Builder.fromBytes(masterClusterStateBytes, null, namedWriteableRegistry); Map<String, Object> masterStateMap = convertToMap(masterClusterState); int masterClusterStateSize = ClusterState.Builder.toBytes(masterClusterState).length; String masterId = masterClusterState.nodes().getMasterNodeId(); for (Client client : cluster().getClients()) { ClusterState localClusterState = client.admin().cluster().prepareState().all().setLocal(true).get().getState(); byte[] localClusterStateBytes = ClusterState.Builder.toBytes(localClusterState); // remove local node reference localClusterState = ClusterState.Builder.fromBytes(localClusterStateBytes, null, namedWriteableRegistry); final Map<String, Object> localStateMap = convertToMap(localClusterState); final int localClusterStateSize = ClusterState.Builder.toBytes(localClusterState).length; // Check that the non-master node has the same version of the cluster state as the master and // that the master node matches the master (otherwise there is no requirement for the cluster state to match) if (masterClusterState.version() == localClusterState.version() && masterId.equals(localClusterState.nodes().getMasterNodeId())) { try { assertEquals("clusterstate UUID does not match", masterClusterState.stateUUID(), localClusterState.stateUUID()); // We cannot compare serialization bytes since serialization order of maps is not guaranteed // but we can compare serialization sizes - they should be the same assertEquals("clusterstate size does not match", masterClusterStateSize, localClusterStateSize); // Compare JSON serialization assertNull("clusterstate JSON serialization does not match", differenceBetweenMapsIgnoringArrayOrder(masterStateMap, localStateMap)); } catch (AssertionError error) { logger.error("Cluster state from master:\n{}\nLocal cluster state:\n{}", masterClusterState.toString(), localClusterState.toString()); throw error; } } } } } /** * Ensures the cluster is in a searchable state for the given indices. This means a searchable copy of each * shard is available on the cluster. */ protected ClusterHealthStatus ensureSearchable(String... indices) { // this is just a temporary thing but it's easier to change if it is encapsulated. return ensureGreen(indices); } protected void ensureStableCluster(int nodeCount) { ensureStableCluster(nodeCount, TimeValue.timeValueSeconds(30)); } protected void ensureStableCluster(int nodeCount, TimeValue timeValue) { ensureStableCluster(nodeCount, timeValue, false, null); } protected void ensureStableCluster(int nodeCount, @Nullable String viaNode) { ensureStableCluster(nodeCount, TimeValue.timeValueSeconds(30), false, viaNode); } protected void ensureStableCluster(int nodeCount, TimeValue timeValue, boolean local, @Nullable String viaNode) { if (viaNode == null) { viaNode = randomFrom(internalCluster().getNodeNames()); } logger.debug("ensuring cluster is stable with [{}] nodes. access node: [{}]. timeout: [{}]", nodeCount, viaNode, timeValue); ClusterHealthResponse clusterHealthResponse = client(viaNode).admin().cluster().prepareHealth() .setWaitForEvents(Priority.LANGUID) .setWaitForNodes(Integer.toString(nodeCount)) .setTimeout(timeValue) .setLocal(local) .setWaitForNoRelocatingShards(true) .get(); if (clusterHealthResponse.isTimedOut()) { ClusterStateResponse stateResponse = client(viaNode).admin().cluster().prepareState().get(); fail("failed to reach a stable cluster of [" + nodeCount + "] nodes. Tried via [" + viaNode + "]. last cluster state:\n" + stateResponse.getState()); } assertThat(clusterHealthResponse.isTimedOut(), is(false)); ensureFullyConnectedCluster(); } /** * Ensures that all nodes in the cluster are connected to each other. * * Some network disruptions may leave nodes that are not the master disconnected from each other. * {@link org.elasticsearch.cluster.NodeConnectionsService} will eventually reconnect but it's * handy to be able to ensure this happens faster */ protected void ensureFullyConnectedCluster() { NetworkDisruption.ensureFullyConnectedCluster(internalCluster()); } /** * Syntactic sugar for: * <pre> * client().prepareIndex(index, type).setSource(source).execute().actionGet(); * </pre> */ protected final IndexResponse index(String index, String type, XContentBuilder source) { return client().prepareIndex(index, type).setSource(source).execute().actionGet(); } /** * Syntactic sugar for: * <pre> * client().prepareIndex(index, type).setSource(source).execute().actionGet(); * </pre> */ protected final IndexResponse index(String index, String type, String id, Map<String, Object> source) { return client().prepareIndex(index, type, id).setSource(source).execute().actionGet(); } /** * Syntactic sugar for: * <pre> * client().prepareGet(index, type, id).execute().actionGet(); * </pre> */ protected final GetResponse get(String index, String type, String id) { return client().prepareGet(index, type, id).execute().actionGet(); } /** * Syntactic sugar for: * <pre> * return client().prepareIndex(index, type, id).setSource(source).execute().actionGet(); * </pre> */ protected final IndexResponse index(String index, String type, String id, XContentBuilder source) { return client().prepareIndex(index, type, id).setSource(source).execute().actionGet(); } /** * Syntactic sugar for: * <pre> * return client().prepareIndex(index, type, id).setSource(source).execute().actionGet(); * </pre> */ protected final IndexResponse index(String index, String type, String id, Object... source) { return client().prepareIndex(index, type, id).setSource(source).execute().actionGet(); } /** * Syntactic sugar for: * <pre> * return client().prepareIndex(index, type, id).setSource(source).execute().actionGet(); * </pre> * <p> * where source is a JSON String. */ protected final IndexResponse index(String index, String type, String id, String source) { return client().prepareIndex(index, type, id).setSource(source, XContentType.JSON).execute().actionGet(); } /** * Waits for relocations and refreshes all indices in the cluster. * * @see #waitForRelocation() */ protected final RefreshResponse refresh(String... indices) { waitForRelocation(); // TODO RANDOMIZE with flush? RefreshResponse actionGet = client().admin().indices().prepareRefresh(indices).execute().actionGet(); assertNoFailures(actionGet); return actionGet; } /** * Flushes and refreshes all indices in the cluster */ protected final void flushAndRefresh(String... indices) { flush(indices); refresh(indices); } /** * Flush some or all indices in the cluster. */ protected final FlushResponse flush(String... indices) { waitForRelocation(); FlushResponse actionGet = client().admin().indices().prepareFlush(indices).execute().actionGet(); for (ShardOperationFailedException failure : actionGet.getShardFailures()) { assertThat("unexpected flush failure " + failure.reason(), failure.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE)); } return actionGet; } /** * Waits for all relocations and force merge all indices in the cluster to 1 segment. */ protected ForceMergeResponse forceMerge() { waitForRelocation(); ForceMergeResponse actionGet = client().admin().indices().prepareForceMerge().setMaxNumSegments(1).execute().actionGet(); assertNoFailures(actionGet); return actionGet; } /** * Returns <code>true</code> iff the given index exists otherwise <code>false</code> */ protected boolean indexExists(String index) { IndicesExistsResponse actionGet = client().admin().indices().prepareExists(index).execute().actionGet(); return actionGet.isExists(); } /** * Syntactic sugar for enabling allocation for <code>indices</code> */ protected final void enableAllocation(String... indices) { client().admin().indices().prepareUpdateSettings(indices).setSettings(Settings.builder().put( EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), "all" )).get(); } /** * Syntactic sugar for disabling allocation for <code>indices</code> */ protected final void disableAllocation(String... indices) { client().admin().indices().prepareUpdateSettings(indices).setSettings(Settings.builder().put( EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), "none" )).get(); } /** * Returns a random admin client. This client can either be a node or a transport client pointing to any of * the nodes in the cluster. */ protected AdminClient admin() { return client().admin(); } /** * Convenience method that forwards to {@link #indexRandom(boolean, List)}. */ public void indexRandom(boolean forceRefresh, IndexRequestBuilder... builders) throws InterruptedException, ExecutionException { indexRandom(forceRefresh, Arrays.asList(builders)); } public void indexRandom(boolean forceRefresh, boolean dummyDocuments, IndexRequestBuilder... builders) throws InterruptedException, ExecutionException { indexRandom(forceRefresh, dummyDocuments, Arrays.asList(builders)); } /** * Indexes the given {@link IndexRequestBuilder} instances randomly. It shuffles the given builders and either * indexes them in a blocking or async fashion. This is very useful to catch problems that relate to internal document * ids or index segment creations. Some features might have bug when a given document is the first or the last in a * segment or if only one document is in a segment etc. This method prevents issues like this by randomizing the index * layout. * * @param forceRefresh if <tt>true</tt> all involved indices are refreshed once the documents are indexed. Additionally if <tt>true</tt> * some empty dummy documents are may be randomly inserted into the document list and deleted once all documents are indexed. * This is useful to produce deleted documents on the server side. * @param builders the documents to index. * @see #indexRandom(boolean, boolean, java.util.List) */ public void indexRandom(boolean forceRefresh, List<IndexRequestBuilder> builders) throws InterruptedException, ExecutionException { indexRandom(forceRefresh, forceRefresh, builders); } /** * Indexes the given {@link IndexRequestBuilder} instances randomly. It shuffles the given builders and either * indexes them in a blocking or async fashion. This is very useful to catch problems that relate to internal document * ids or index segment creations. Some features might have bug when a given document is the first or the last in a * segment or if only one document is in a segment etc. This method prevents issues like this by randomizing the index * layout. * * @param forceRefresh if <tt>true</tt> all involved indices are refreshed once the documents are indexed. * @param dummyDocuments if <tt>true</tt> some empty dummy documents may be randomly inserted into the document list and deleted once * all documents are indexed. This is useful to produce deleted documents on the server side. * @param builders the documents to index. */ public void indexRandom(boolean forceRefresh, boolean dummyDocuments, List<IndexRequestBuilder> builders) throws InterruptedException, ExecutionException { indexRandom(forceRefresh, dummyDocuments, true, builders); } /** * Indexes the given {@link IndexRequestBuilder} instances randomly. It shuffles the given builders and either * indexes them in a blocking or async fashion. This is very useful to catch problems that relate to internal document * ids or index segment creations. Some features might have bug when a given document is the first or the last in a * segment or if only one document is in a segment etc. This method prevents issues like this by randomizing the index * layout. * * @param forceRefresh if <tt>true</tt> all involved indices are refreshed once the documents are indexed. * @param dummyDocuments if <tt>true</tt> some empty dummy documents may be randomly inserted into the document list and deleted once * all documents are indexed. This is useful to produce deleted documents on the server side. * @param maybeFlush if <tt>true</tt> this method may randomly execute full flushes after index operations. * @param builders the documents to index. */ public void indexRandom(boolean forceRefresh, boolean dummyDocuments, boolean maybeFlush, List<IndexRequestBuilder> builders) throws InterruptedException, ExecutionException { Random random = random(); Map<String, Set<String>> indicesAndTypes = new HashMap<>(); for (IndexRequestBuilder builder : builders) { final Set<String> types = indicesAndTypes.computeIfAbsent(builder.request().index(), index -> new HashSet<>()); types.add(builder.request().type()); } Set<List<String>> bogusIds = new HashSet<>(); // (index, type, id) if (random.nextBoolean() && !builders.isEmpty() && dummyDocuments) { builders = new ArrayList<>(builders); // inject some bogus docs final int numBogusDocs = scaledRandomIntBetween(1, builders.size() * 2); final int unicodeLen = between(1, 10); for (int i = 0; i < numBogusDocs; i++) { String id = "bogus_doc_" + randomRealisticUnicodeOfLength(unicodeLen) + Integer.toString(dummmyDocIdGenerator.incrementAndGet()); Map.Entry<String, Set<String>> indexAndTypes = RandomPicks.randomFrom(random, indicesAndTypes.entrySet()); String index = indexAndTypes.getKey(); String type = RandomPicks.randomFrom(random, indexAndTypes.getValue()); bogusIds.add(Arrays.asList(index, type, id)); // We configure a routing key in case the mapping requires it builders.add(client().prepareIndex(index, type, id).setSource("{}", XContentType.JSON).setRouting(id)); } } Collections.shuffle(builders, random()); final CopyOnWriteArrayList<Tuple<IndexRequestBuilder, Exception>> errors = new CopyOnWriteArrayList<>(); List<CountDownLatch> inFlightAsyncOperations = new ArrayList<>(); // If you are indexing just a few documents then frequently do it one at a time. If many then frequently in bulk. final String[] indices = indicesAndTypes.keySet().toArray(new String[0]); if (builders.size() < FREQUENT_BULK_THRESHOLD ? frequently() : builders.size() < ALWAYS_BULK_THRESHOLD ? rarely() : false) { if (frequently()) { logger.info("Index [{}] docs async: [{}] bulk: [{}]", builders.size(), true, false); for (IndexRequestBuilder indexRequestBuilder : builders) { indexRequestBuilder.execute(new PayloadLatchedActionListener<IndexResponse, IndexRequestBuilder>(indexRequestBuilder, newLatch(inFlightAsyncOperations), errors)); postIndexAsyncActions(indices, inFlightAsyncOperations, maybeFlush); } } else { logger.info("Index [{}] docs async: [{}] bulk: [{}]", builders.size(), false, false); for (IndexRequestBuilder indexRequestBuilder : builders) { indexRequestBuilder.execute().actionGet(); postIndexAsyncActions(indices, inFlightAsyncOperations, maybeFlush); } } } else { List<List<IndexRequestBuilder>> partition = eagerPartition(builders, Math.min(MAX_BULK_INDEX_REQUEST_SIZE, Math.max(1, (int) (builders.size() * randomDouble())))); logger.info("Index [{}] docs async: [{}] bulk: [{}] partitions [{}]", builders.size(), false, true, partition.size()); for (List<IndexRequestBuilder> segmented : partition) { BulkRequestBuilder bulkBuilder = client().prepareBulk(); for (IndexRequestBuilder indexRequestBuilder : segmented) { bulkBuilder.add(indexRequestBuilder); } BulkResponse actionGet = bulkBuilder.execute().actionGet(); assertThat(actionGet.hasFailures() ? actionGet.buildFailureMessage() : "", actionGet.hasFailures(), equalTo(false)); } } for (CountDownLatch operation : inFlightAsyncOperations) { operation.await(); } final List<Exception> actualErrors = new ArrayList<>(); for (Tuple<IndexRequestBuilder, Exception> tuple : errors) { if (ExceptionsHelper.unwrapCause(tuple.v2()) instanceof EsRejectedExecutionException) { tuple.v1().execute().actionGet(); // re-index if rejected } else { actualErrors.add(tuple.v2()); } } assertThat(actualErrors, emptyIterable()); if (!bogusIds.isEmpty()) { // delete the bogus types again - it might trigger merges or at least holes in the segments and enforces deleted docs! for (List<String> doc : bogusIds) { assertEquals("failed to delete a dummy doc [" + doc.get(0) + "][" + doc.get(2) + "]", DocWriteResponse.Result.DELETED, client().prepareDelete(doc.get(0), doc.get(1), doc.get(2)).setRouting(doc.get(2)).get().getResult()); } } if (forceRefresh) { assertNoFailures(client().admin().indices().prepareRefresh(indices).setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute().get()); } } private AtomicInteger dummmyDocIdGenerator = new AtomicInteger(); /** Disables an index block for the specified index */ public static void disableIndexBlock(String index, String block) { Settings settings = Settings.builder().put(block, false).build(); client().admin().indices().prepareUpdateSettings(index).setSettings(settings).get(); } /** Enables an index block for the specified index */ public static void enableIndexBlock(String index, String block) { Settings settings = Settings.builder().put(block, true).build(); client().admin().indices().prepareUpdateSettings(index).setSettings(settings).get(); } /** Sets or unsets the cluster read_only mode **/ public static void setClusterReadOnly(boolean value) { Settings settings = value ? Settings.builder().put(MetaData.SETTING_READ_ONLY_SETTING.getKey(), value).build() : Settings.builder().putNull(MetaData.SETTING_READ_ONLY_SETTING.getKey()).build() ; assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(settings).get()); } private static CountDownLatch newLatch(List<CountDownLatch> latches) { CountDownLatch l = new CountDownLatch(1); latches.add(l); return l; } /** * Maybe refresh, force merge, or flush then always make sure there aren't too many in flight async operations. */ private void postIndexAsyncActions(String[] indices, List<CountDownLatch> inFlightAsyncOperations, boolean maybeFlush) throws InterruptedException { if (rarely()) { if (rarely()) { client().admin().indices().prepareRefresh(indices).setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute( new LatchedActionListener<>(newLatch(inFlightAsyncOperations))); } else if (maybeFlush && rarely()) { if (randomBoolean()) { client().admin().indices().prepareFlush(indices).setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute( new LatchedActionListener<>(newLatch(inFlightAsyncOperations))); } else { client().admin().indices().syncedFlush(syncedFlushRequest(indices).indicesOptions(IndicesOptions.lenientExpandOpen()), new LatchedActionListener<>(newLatch(inFlightAsyncOperations))); } } else if (rarely()) { client().admin().indices().prepareForceMerge(indices).setIndicesOptions(IndicesOptions.lenientExpandOpen()).setMaxNumSegments(between(1, 10)).setFlush(maybeFlush && randomBoolean()).execute( new LatchedActionListener<>(newLatch(inFlightAsyncOperations))); } } while (inFlightAsyncOperations.size() > MAX_IN_FLIGHT_ASYNC_INDEXES) { int waitFor = between(0, inFlightAsyncOperations.size() - 1); inFlightAsyncOperations.remove(waitFor).await(); } } /** * The scope of a test cluster used together with * {@link ESIntegTestCase.ClusterScope} annotations on {@link ESIntegTestCase} subclasses. */ public enum Scope { /** * A cluster shared across all method in a single test suite */ SUITE, /** * A test exclusive test cluster */ TEST } /** * Defines a cluster scope for a {@link ESIntegTestCase} subclass. * By default if no {@link ClusterScope} annotation is present {@link ESIntegTestCase.Scope#SUITE} is used * together with randomly chosen settings like number of nodes etc. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ClusterScope { /** * Returns the scope. {@link ESIntegTestCase.Scope#SUITE} is default. */ Scope scope() default Scope.SUITE; /** * Returns the number of nodes in the cluster. Default is <tt>-1</tt> which means * a random number of nodes is used, where the minimum and maximum number of nodes * are either the specified ones or the default ones if not specified. */ int numDataNodes() default -1; /** * Returns the minimum number of data nodes in the cluster. Default is <tt>-1</tt>. * Ignored when {@link ClusterScope#numDataNodes()} is set. */ int minNumDataNodes() default -1; /** * Returns the maximum number of data nodes in the cluster. Default is <tt>-1</tt>. * Ignored when {@link ClusterScope#numDataNodes()} is set. */ int maxNumDataNodes() default -1; /** * Indicates whether the cluster can have dedicated master nodes. If <tt>false</tt> means data nodes will serve as master nodes * and there will be no dedicated master (and data) nodes. Default is <tt>true</tt> which means * dedicated master nodes will be randomly used. */ boolean supportsDedicatedMasters() default true; /** * The cluster automatically manages the {@link ElectMasterService#DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING} by default * as nodes are started and stopped. Set this to false to manage the setting manually. */ boolean autoMinMasterNodes() default true; /** * Returns the number of client nodes in the cluster. Default is {@link InternalTestCluster#DEFAULT_NUM_CLIENT_NODES}, a * negative value means that the number of client nodes will be randomized. */ int numClientNodes() default InternalTestCluster.DEFAULT_NUM_CLIENT_NODES; /** * Returns the transport client ratio. By default this returns <code>-1</code> which means a random * ratio in the interval <code>[0..1]</code> is used. */ double transportClientRatio() default -1; } private class LatchedActionListener<Response> implements ActionListener<Response> { private final CountDownLatch latch; LatchedActionListener(CountDownLatch latch) { this.latch = latch; } @Override public final void onResponse(Response response) { latch.countDown(); } @Override public final void onFailure(Exception t) { try { logger.info("Action Failed", t); addError(t); } finally { latch.countDown(); } } protected void addError(Exception e) { } } private class PayloadLatchedActionListener<Response, T> extends LatchedActionListener<Response> { private final CopyOnWriteArrayList<Tuple<T, Exception>> errors; private final T builder; PayloadLatchedActionListener(T builder, CountDownLatch latch, CopyOnWriteArrayList<Tuple<T, Exception>> errors) { super(latch); this.errors = errors; this.builder = builder; } @Override protected void addError(Exception e) { errors.add(new Tuple<>(builder, e)); } } /** * Clears the given scroll Ids */ public void clearScroll(String... scrollIds) { ClearScrollResponse clearResponse = client().prepareClearScroll() .setScrollIds(Arrays.asList(scrollIds)).get(); assertThat(clearResponse.isSucceeded(), equalTo(true)); } private static <A extends Annotation> A getAnnotation(Class<?> clazz, Class<A> annotationClass) { if (clazz == Object.class || clazz == ESIntegTestCase.class) { return null; } A annotation = clazz.getAnnotation(annotationClass); if (annotation != null) { return annotation; } return getAnnotation(clazz.getSuperclass(), annotationClass); } private Scope getCurrentClusterScope() { return getCurrentClusterScope(this.getClass()); } private static Scope getCurrentClusterScope(Class<?> clazz) { ClusterScope annotation = getAnnotation(clazz, ClusterScope.class); // if we are not annotated assume suite! return annotation == null ? Scope.SUITE : annotation.scope(); } private boolean getSupportsDedicatedMasters() { ClusterScope annotation = getAnnotation(this.getClass(), ClusterScope.class); return annotation == null ? true : annotation.supportsDedicatedMasters(); } private boolean getAutoMinMasterNodes() { ClusterScope annotation = getAnnotation(this.getClass(), ClusterScope.class); return annotation == null ? true : annotation.autoMinMasterNodes(); } private int getNumDataNodes() { ClusterScope annotation = getAnnotation(this.getClass(), ClusterScope.class); return annotation == null ? -1 : annotation.numDataNodes(); } private int getMinNumDataNodes() { ClusterScope annotation = getAnnotation(this.getClass(), ClusterScope.class); return annotation == null || annotation.minNumDataNodes() == -1 ? InternalTestCluster.DEFAULT_MIN_NUM_DATA_NODES : annotation.minNumDataNodes(); } private int getMaxNumDataNodes() { ClusterScope annotation = getAnnotation(this.getClass(), ClusterScope.class); return annotation == null || annotation.maxNumDataNodes() == -1 ? InternalTestCluster.DEFAULT_MAX_NUM_DATA_NODES : annotation.maxNumDataNodes(); } private int getNumClientNodes() { ClusterScope annotation = getAnnotation(this.getClass(), ClusterScope.class); return annotation == null ? InternalTestCluster.DEFAULT_NUM_CLIENT_NODES : annotation.numClientNodes(); } /** * This method is used to obtain settings for the <tt>Nth</tt> node in the cluster. * Nodes in this cluster are associated with an ordinal number such that nodes can * be started with specific configurations. This method might be called multiple * times with the same ordinal and is expected to return the same value for each invocation. * In other words subclasses must ensure this method is idempotent. */ protected Settings nodeSettings(int nodeOrdinal) { Settings.Builder builder = Settings.builder() .put(NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING.getKey(), Integer.MAX_VALUE) // Default the watermarks to absurdly low to prevent the tests // from failing on nodes without enough disk space .put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING.getKey(), "1b") .put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING.getKey(), "1b") .put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_FLOOD_STAGE_WATERMARK_SETTING.getKey(), "1b") .put(ScriptService.SCRIPT_MAX_COMPILATIONS_RATE.getKey(), "2048/1m") // by default we never cache below 10k docs in a segment, // bypass this limit so that caching gets some testing in // integration tests that usually create few documents .put(IndicesQueryCache.INDICES_QUERIES_CACHE_ALL_SEGMENTS_SETTING.getKey(), nodeOrdinal % 2 == 0) // wait short time for other active shards before actually deleting, default 30s not needed in tests .put(IndicesStore.INDICES_STORE_DELETE_SHARD_TIMEOUT.getKey(), new TimeValue(1, TimeUnit.SECONDS)) // randomly enable low-level search cancellation to make sure it does not alter results .put(SearchService.LOW_LEVEL_CANCELLATION_SETTING.getKey(), randomBoolean()); if (rarely()) { // Sometimes adjust the minimum search thread pool size, causing // QueueResizingEsThreadPoolExecutor to be used instead of a regular // fixed thread pool builder.put("thread_pool.search.min_queue_size", 100); } return builder.build(); } protected Path nodeConfigPath(int nodeOrdinal) { return null; } /** * Returns a collection of plugins that should be loaded on each node. */ protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.emptyList(); } /** * Returns a collection of plugins that should be loaded when creating a transport client. */ protected Collection<Class<? extends Plugin>> transportClientPlugins() { return Collections.emptyList(); } /** * This method is used to obtain additional settings for clients created by the internal cluster. * These settings will be applied on the client in addition to some randomized settings defined in * the cluster. These settings will also override any other settings the internal cluster might * add by default. */ protected Settings transportClientSettings() { return Settings.EMPTY; } private ExternalTestCluster buildExternalCluster(String clusterAddresses) throws IOException { String[] stringAddresses = clusterAddresses.split(","); TransportAddress[] transportAddresses = new TransportAddress[stringAddresses.length]; int i = 0; for (String stringAddress : stringAddresses) { URL url = new URL("http://" + stringAddress); InetAddress inetAddress = InetAddress.getByName(url.getHost()); transportAddresses[i++] = new TransportAddress(new InetSocketAddress(inetAddress, url.getPort())); } return new ExternalTestCluster(createTempDir(), externalClusterClientSettings(), transportClientPlugins(), transportAddresses); } protected Settings externalClusterClientSettings() { return Settings.EMPTY; } protected boolean ignoreExternalCluster() { return false; } protected TestCluster buildTestCluster(Scope scope, long seed) throws IOException { String clusterAddresses = System.getProperty(TESTS_CLUSTER); if (Strings.hasLength(clusterAddresses) && ignoreExternalCluster() == false) { if (scope == Scope.TEST) { throw new IllegalArgumentException("Cannot run TEST scope test with " + TESTS_CLUSTER); } return buildExternalCluster(clusterAddresses); } final String nodePrefix; switch (scope) { case TEST: nodePrefix = TEST_CLUSTER_NODE_PREFIX; break; case SUITE: nodePrefix = SUITE_CLUSTER_NODE_PREFIX; break; default: throw new ElasticsearchException("Scope not supported: " + scope); } boolean supportsDedicatedMasters = getSupportsDedicatedMasters(); int numDataNodes = getNumDataNodes(); int minNumDataNodes; int maxNumDataNodes; if (numDataNodes >= 0) { minNumDataNodes = maxNumDataNodes = numDataNodes; } else { minNumDataNodes = getMinNumDataNodes(); maxNumDataNodes = getMaxNumDataNodes(); } Collection<Class<? extends Plugin>> mockPlugins = getMockPlugins(); final NodeConfigurationSource nodeConfigurationSource = getNodeConfigSource(); if (addMockTransportService()) { ArrayList<Class<? extends Plugin>> mocks = new ArrayList<>(mockPlugins); // add both mock plugins - local and tcp if they are not there // we do this in case somebody overrides getMockPlugins and misses to call super if (mockPlugins.contains(getTestTransportPlugin()) == false) { mocks.add(getTestTransportPlugin()); } mockPlugins = mocks; } return new InternalTestCluster(seed, createTempDir(), supportsDedicatedMasters, getAutoMinMasterNodes(), minNumDataNodes, maxNumDataNodes, InternalTestCluster.clusterName(scope.name(), seed) + "-cluster", nodeConfigurationSource, getNumClientNodes(), InternalTestCluster.DEFAULT_ENABLE_HTTP_PIPELINING, nodePrefix, mockPlugins, getClientWrapper()); } protected NodeConfigurationSource getNodeConfigSource() { Settings.Builder networkSettings = Settings.builder(); if (addMockTransportService()) { networkSettings.put(NetworkModule.TRANSPORT_TYPE_KEY, getTestTransportType()); } NodeConfigurationSource nodeConfigurationSource = new NodeConfigurationSource() { @Override public Settings nodeSettings(int nodeOrdinal) { return Settings.builder() .put(NetworkModule.HTTP_ENABLED.getKey(), false) .put(networkSettings.build()) .put(ESIntegTestCase.this.nodeSettings(nodeOrdinal)).build(); } @Override public Path nodeConfigPath(int nodeOrdinal) { return ESIntegTestCase.this.nodeConfigPath(nodeOrdinal); } @Override public Collection<Class<? extends Plugin>> nodePlugins() { return ESIntegTestCase.this.nodePlugins(); } @Override public Settings transportClientSettings() { return Settings.builder().put(networkSettings.build()) .put(ESIntegTestCase.this.transportClientSettings()).build(); } @Override public Collection<Class<? extends Plugin>> transportClientPlugins() { Collection<Class<? extends Plugin>> plugins = ESIntegTestCase.this.transportClientPlugins(); if (plugins.contains(getTestTransportPlugin()) == false) { plugins = new ArrayList<>(plugins); plugins.add(getTestTransportPlugin()); } return Collections.unmodifiableCollection(plugins); } }; return nodeConfigurationSource; } /** * Iff this returns true mock transport implementations are used for the test runs. Otherwise not mock transport impls are used. * The default is <tt>true</tt> */ protected boolean addMockTransportService() { return true; } /** * Iff this returns true test zen discovery implementations is used for the test runs. * The default is <tt>true</tt> */ protected boolean addTestZenDiscovery() { return true; } /** * Returns a function that allows to wrap / filter all clients that are exposed by the test cluster. This is useful * for debugging or request / response pre and post processing. It also allows to intercept all calls done by the test * framework. By default this method returns an identity function {@link Function#identity()}. */ protected Function<Client,Client> getClientWrapper() { return Function.identity(); } /** Return the mock plugins the cluster should use */ protected Collection<Class<? extends Plugin>> getMockPlugins() { final ArrayList<Class<? extends Plugin>> mocks = new ArrayList<>(); if (MOCK_MODULES_ENABLED && randomBoolean()) { // sometimes run without those completely if (randomBoolean() && addMockTransportService()) { mocks.add(MockTransportService.TestPlugin.class); } if (randomBoolean()) { mocks.add(MockFSIndexStore.TestPlugin.class); } if (randomBoolean()) { mocks.add(NodeMocksPlugin.class); } if (randomBoolean()) { mocks.add(MockEngineFactoryPlugin.class); } if (randomBoolean()) { mocks.add(MockSearchService.TestPlugin.class); } if (randomBoolean()) { mocks.add(AssertingTransportInterceptor.TestPlugin.class); } if (randomBoolean()) { mocks.add(MockFieldFilterPlugin.class); } } if (addMockTransportService()) { mocks.add(getTestTransportPlugin()); } if (addTestZenDiscovery()) { mocks.add(TestZenDiscovery.TestPlugin.class); } mocks.add(TestSeedPlugin.class); return Collections.unmodifiableList(mocks); } public static final class TestSeedPlugin extends Plugin { @Override public List<Setting<?>> getSettings() { return Arrays.asList(INDEX_TEST_SEED_SETTING); } } /** * Returns the client ratio configured via */ private static double transportClientRatio() { String property = System.getProperty(TESTS_CLIENT_RATIO); if (property == null || property.isEmpty()) { return Double.NaN; } return Double.parseDouble(property); } /** * Returns the transport client ratio from the class level annotation or via * {@link System#getProperty(String)} if available. If both are not available this will * return a random ratio in the interval <tt>[0..1]</tt> */ protected double getPerTestTransportClientRatio() { final ClusterScope annotation = getAnnotation(this.getClass(), ClusterScope.class); double perTestRatio = -1; if (annotation != null) { perTestRatio = annotation.transportClientRatio(); } if (perTestRatio == -1) { return Double.isNaN(TRANSPORT_CLIENT_RATIO) ? randomDouble() : TRANSPORT_CLIENT_RATIO; } assert perTestRatio >= 0.0 && perTestRatio <= 1.0; return perTestRatio; } /** * Returns path to a random directory that can be used to create a temporary file system repo */ public Path randomRepoPath() { if (currentCluster instanceof InternalTestCluster) { return randomRepoPath(((InternalTestCluster) currentCluster).getDefaultSettings()); } throw new UnsupportedOperationException("unsupported cluster type"); } /** * Returns path to a random directory that can be used to create a temporary file system repo */ public static Path randomRepoPath(Settings settings) { Environment environment = TestEnvironment.newEnvironment(settings); Path[] repoFiles = environment.repoFiles(); assert repoFiles.length > 0; Path path; do { path = repoFiles[0].resolve(randomAlphaOfLength(10)); } while (Files.exists(path)); return path; } protected NumShards getNumShards(String index) { MetaData metaData = client().admin().cluster().prepareState().get().getState().metaData(); assertThat(metaData.hasIndex(index), equalTo(true)); int numShards = Integer.valueOf(metaData.index(index).getSettings().get(SETTING_NUMBER_OF_SHARDS)); int numReplicas = Integer.valueOf(metaData.index(index).getSettings().get(SETTING_NUMBER_OF_REPLICAS)); return new NumShards(numShards, numReplicas); } /** * Asserts that all shards are allocated on nodes matching the given node pattern. */ public Set<String> assertAllShardsOnNodes(String index, String... pattern) { Set<String> nodes = new HashSet<>(); ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState(); for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) { for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) { for (ShardRouting shardRouting : indexShardRoutingTable) { if (shardRouting.currentNodeId() != null && index.equals(shardRouting.getIndexName())) { String name = clusterState.nodes().get(shardRouting.currentNodeId()).getName(); nodes.add(name); assertThat("Allocated on new node: " + name, Regex.simpleMatch(pattern, name), is(true)); } } } } return nodes; } /** * Asserts that all segments are sorted with the provided {@link Sort}. */ public void assertSortedSegments(String indexName, Sort expectedIndexSort) { IndicesSegmentResponse segmentResponse = client().admin().indices().prepareSegments(indexName).execute().actionGet(); IndexSegments indexSegments = segmentResponse.getIndices().get(indexName); for (IndexShardSegments indexShardSegments : indexSegments.getShards().values()) { for (ShardSegments shardSegments : indexShardSegments.getShards()) { for (Segment segment : shardSegments) { assertThat(expectedIndexSort, equalTo(segment.getSegmentSort())); } } } } protected static class NumShards { public final int numPrimaries; public final int numReplicas; public final int totalNumShards; public final int dataCopies; private NumShards(int numPrimaries, int numReplicas) { this.numPrimaries = numPrimaries; this.numReplicas = numReplicas; this.dataCopies = numReplicas + 1; this.totalNumShards = numPrimaries * dataCopies; } } private static boolean runTestScopeLifecycle() { return INSTANCE == null; } @Before public final void setupTestCluster() throws Exception { if (runTestScopeLifecycle()) { printTestMessage("setting up"); beforeInternal(); printTestMessage("all set up"); } } @After public final void cleanUpCluster() throws Exception { // Deleting indices is going to clear search contexts implicitly so we // need to check that there are no more in-flight search contexts before // we remove indices super.ensureAllSearchContextsReleased(); if (runTestScopeLifecycle()) { printTestMessage("cleaning up after"); afterInternal(false); printTestMessage("cleaned up after"); } } @AfterClass public static void afterClass() throws Exception { if (!runTestScopeLifecycle()) { try { INSTANCE.printTestMessage("cleaning up after"); INSTANCE.afterInternal(true); checkStaticState(true); } finally { INSTANCE = null; } } else { clearClusters(); } SUITE_SEED = null; currentCluster = null; } private static void initializeSuiteScope() throws Exception { Class<?> targetClass = getTestClass(); /** * Note we create these test class instance via reflection * since JUnit creates a new instance per test and that is also * the reason why INSTANCE is static since this entire method * must be executed in a static context. */ assert INSTANCE == null; if (isSuiteScopedTest(targetClass)) { // note we need to do this this way to make sure this is reproducible INSTANCE = (ESIntegTestCase) targetClass.getConstructor().newInstance(); boolean success = false; try { INSTANCE.printTestMessage("setup"); INSTANCE.beforeInternal(); INSTANCE.setupSuiteScopeCluster(); success = true; } finally { if (!success) { afterClass(); } } } else { INSTANCE = null; } } /** * Compute a routing key that will route documents to the <code>shard</code>-th shard * of the provided index. */ protected String routingKeyForShard(String index, int shard) { return internalCluster().routingKeyForShard(resolveIndex(index), shard, random()); } @Override protected NamedXContentRegistry xContentRegistry() { if (isInternalCluster() && cluster().size() > 0) { // If it's internal cluster - using existing registry in case plugin registered custom data return internalCluster().getInstance(NamedXContentRegistry.class); } else { // If it's external cluster - fall back to the standard set return new NamedXContentRegistry(ClusterModule.getNamedXWriteables()); } } /** * Returns an instance of {@link RestClient} pointing to the current test cluster. * Creates a new client if the method is invoked for the first time in the context of the current test scope. * The returned client gets automatically closed when needed, it shouldn't be closed as part of tests otherwise * it cannot be reused by other tests anymore. */ protected static synchronized RestClient getRestClient() { if (restClient == null) { restClient = createRestClient(null); } return restClient; } protected static RestClient createRestClient(RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback) { return createRestClient(httpClientConfigCallback, "http"); } protected static RestClient createRestClient(RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback, String protocol) { NodesInfoResponse nodesInfoResponse = client().admin().cluster().prepareNodesInfo().get(); assertFalse(nodesInfoResponse.hasFailures()); return createRestClient(nodesInfoResponse.getNodes(), httpClientConfigCallback, protocol); } protected static RestClient createRestClient(final List<NodeInfo> nodes, RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback, String protocol) { List<HttpHost> hosts = new ArrayList<>(); for (NodeInfo node : nodes) { if (node.getHttp() != null) { TransportAddress publishAddress = node.getHttp().address().publishAddress(); InetSocketAddress address = publishAddress.address(); hosts.add(new HttpHost(NetworkAddress.format(address.getAddress()), address.getPort(), protocol)); } } RestClientBuilder builder = RestClient.builder(hosts.toArray(new HttpHost[hosts.size()])); if (httpClientConfigCallback != null) { builder.setHttpClientConfigCallback(httpClientConfigCallback); } return builder.build(); } /** * This method is executed iff the test is annotated with {@link SuiteScopeTestCase} * before the first test of this class is executed. * * @see SuiteScopeTestCase */ protected void setupSuiteScopeCluster() throws Exception { } private static boolean isSuiteScopedTest(Class<?> clazz) { return clazz.getAnnotation(SuiteScopeTestCase.class) != null; } /** * If a test is annotated with {@link SuiteScopeTestCase} * the checks and modifications that are applied to the used test cluster are only done after all tests * of this class are executed. This also has the side-effect of a suite level setup method {@link #setupSuiteScopeCluster()} * that is executed in a separate test instance. Variables that need to be accessible across test instances must be static. */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target(ElementType.TYPE) public @interface SuiteScopeTestCase { } public static Index resolveIndex(String index) { GetIndexResponse getIndexResponse = client().admin().indices().prepareGetIndex().setIndices(index).get(); assertTrue("index " + index + " not found", getIndexResponse.getSettings().containsKey(index)); String uuid = getIndexResponse.getSettings().get(index).get(IndexMetaData.SETTING_INDEX_UUID); return new Index(index, uuid); } protected void assertSeqNos() throws Exception { assertBusy(() -> { IndicesStatsResponse stats = client().admin().indices().prepareStats().clear().get(); for (IndexStats indexStats : stats.getIndices().values()) { for (IndexShardStats indexShardStats : indexStats.getIndexShards().values()) { Optional<ShardStats> maybePrimary = Stream.of(indexShardStats.getShards()) .filter(s -> s.getShardRouting().active() && s.getShardRouting().primary()) .findFirst(); if (maybePrimary.isPresent() == false) { continue; } ShardStats primary = maybePrimary.get(); final SeqNoStats primarySeqNoStats = primary.getSeqNoStats(); final ShardRouting primaryShardRouting = primary.getShardRouting(); assertThat(primaryShardRouting + " should have set the global checkpoint", primarySeqNoStats.getGlobalCheckpoint(), not(equalTo(SequenceNumbers.UNASSIGNED_SEQ_NO))); final DiscoveryNode node = clusterService().state().nodes().get(primaryShardRouting.currentNodeId()); final IndicesService indicesService = internalCluster().getInstance(IndicesService.class, node.getName()); final IndexShard indexShard = indicesService.getShardOrNull(primaryShardRouting.shardId()); final ObjectLongMap<String> globalCheckpoints = indexShard.getInSyncGlobalCheckpoints(); for (ShardStats shardStats : indexShardStats) { final SeqNoStats seqNoStats = shardStats.getSeqNoStats(); assertThat(shardStats.getShardRouting() + " local checkpoint mismatch", seqNoStats.getLocalCheckpoint(), equalTo(primarySeqNoStats.getLocalCheckpoint())); assertThat(shardStats.getShardRouting() + " global checkpoint mismatch", seqNoStats.getGlobalCheckpoint(), equalTo(primarySeqNoStats.getGlobalCheckpoint())); assertThat(shardStats.getShardRouting() + " max seq no mismatch", seqNoStats.getMaxSeqNo(), equalTo(primarySeqNoStats.getMaxSeqNo())); // the local knowledge on the primary of the global checkpoint equals the global checkpoint on the shard assertThat( seqNoStats.getGlobalCheckpoint(), equalTo(globalCheckpoints.get(shardStats.getShardRouting().allocationId().getId()))); } } } }); } }
{ "content_hash": "0419192384e2d32fdadc98b691d3b6a7", "timestamp": "", "source": "github", "line_count": 2240, "max_line_length": 206, "avg_line_length": 47.31383928571429, "alnum_prop": 0.6609833652566921, "repo_name": "ThiagoGarciaAlves/elasticsearch", "id": "e633f5adb70af93b41f7019ca64ca2ff9c06c543", "size": "106771", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "10240" }, { "name": "Groovy", "bytes": "451" }, { "name": "HTML", "bytes": "1338" }, { "name": "Java", "bytes": "28645812" }, { "name": "Perl", "bytes": "13729" }, { "name": "Python", "bytes": "86811" }, { "name": "Ruby", "bytes": "17776" }, { "name": "Shell", "bytes": "93213" }, { "name": "XSLT", "bytes": "885" } ], "symlink_target": "" }
/* ChatObject_publisher.cs A publication of data of type ChatObject This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C# -example <arch> Chat.idl Example publication of type ChatObject automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs\<arch>${constructMap.nativeFQNameInModule}_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs\<arch>${constructMap.nativeFQNameInModule}_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: bin\<Debug|Release>\ChatObject_publisher <domain_id> <sample_count> bin\<Debug|Release>\ChatObject_subscriber <domain_id> <sample_count> */ using System; using System.Collections.Generic; using System.Text; namespace My{ public class ChatObjectPublisher { public static void Main(string[] args) { // --- Get domain ID --- // int domain_id = 0; if (args.Length >= 1) { domain_id = Int32.Parse(args[0]); } // --- Get max loop count; 0 means infinite loop --- // int sample_count = 0; if (args.Length >= 2) { sample_count = Int32.Parse(args[1]); } /* Uncomment this to turn on additional logging NDDS.ConfigLogger.get_instance().set_verbosity_by_category( NDDS.LogCategory.NDDS_CONFIG_LOG_CATEGORY_API, NDDS.LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ // --- Run --- // try { ChatObjectPublisher.publish( domain_id, sample_count); } catch(DDS.Exception) { Console.WriteLine("error in publisher"); } } static void publish(int domain_id, int sample_count) { // --- Create participant --- // /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.DomainParticipant participant = DDS.DomainParticipantFactory.get_instance().create_participant( domain_id, DDS.DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT, null /* listener */, DDS.StatusMask.STATUS_MASK_NONE); if (participant == null) { shutdown(participant); throw new ApplicationException("create_participant error"); } // --- Create publisher --- // /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.Publisher publisher = participant.create_publisher( DDS.DomainParticipant.PUBLISHER_QOS_DEFAULT, null /* listener */, DDS.StatusMask.STATUS_MASK_NONE); if (publisher == null) { shutdown(participant); throw new ApplicationException("create_publisher error"); } // --- Create topic --- // /* Register type before creating topic */ System.String type_name = ChatObjectTypeSupport.get_type_name(); try { ChatObjectTypeSupport.register_type( participant, type_name); } catch(DDS.Exception e) { Console.WriteLine("register_type error {0}", e); shutdown(participant); throw e; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.Topic topic = participant.create_topic( My.CHAT_TOPIC_NAME.VALUE, /*>>><<<*/ type_name, DDS.DomainParticipant.TOPIC_QOS_DEFAULT, null /* listener */, DDS.StatusMask.STATUS_MASK_NONE); if (topic == null) { shutdown(participant); throw new ApplicationException("create_topic error"); } // --- Create writer --- // /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.DataWriter writer = publisher.create_datawriter( topic, DDS.Publisher.DATAWRITER_QOS_DEFAULT, null /* listener */, DDS.StatusMask.STATUS_MASK_NONE); if (writer == null) { shutdown(participant); throw new ApplicationException("create_datawriter error"); } ChatObjectDataWriter ChatObject_writer = (ChatObjectDataWriter)writer; // --- Write --- // /* Create data sample for writing */ ChatObject instance = ChatObjectTypeSupport.create_data(); if (instance == null) { shutdown(participant); throw new ApplicationException( "ChatObjectTypeSupport.create_data error"); } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* >>> */ DDS.InstanceHandle_t instance_handle = DDS.InstanceHandle_t.HANDLE_NIL; instance.user = "Rajive"; // instance_handle = ChatObject_writer.register_instance(instance); /* <<< */ /* Main loop */ const System.Int32 send_period = 4000; // milliseconds for (int count=0; (sample_count == 0) || (count < sample_count); ++count) { Console.WriteLine("Writing ChatObject, count {0}", count); /* Modify the data to be sent here */ /* >>> */ instance.msg = "Hello " + count; /* <<< */ try { ChatObject_writer.write(instance, ref instance_handle); } catch(DDS.Exception e) { Console.WriteLine("write error {0}", e); } System.Threading.Thread.Sleep(send_period); } /* try { ChatObject_writer.unregister_instance( instance, ref instance_handle); } catch(DDS.Exception e) { Console.WriteLine("unregister instance error: {0}", e); } */ // --- Shutdown --- // /* Delete data sample */ try { ChatObjectTypeSupport.delete_data(instance); } catch(DDS.Exception e) { Console.WriteLine( "ChatObjectTypeSupport.delete_data error: {0}", e); } /* Delete all entities */ shutdown(participant); } static void shutdown( DDS.DomainParticipant participant) { /* Delete all entities */ if (participant != null) { participant.delete_contained_entities(); DDS.DomainParticipantFactory.get_instance().delete_participant( ref participant); } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* try { DDS.DomainParticipantFactory.finalize_instance(); } catch (DDS.Exception e) { Console.WriteLine("finalize_instance error: {0}", e); throw e; } */ } } } /* namespace My */
{ "content_hash": "e1951c92b7fbe9f5e3f40ca8cfef46aa", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 85, "avg_line_length": 34.6058091286307, "alnum_prop": 0.5414868105515588, "repo_name": "rajive/DDSChatApp", "id": "f8cc3fe64e92cc53938db35865a630539ac874f6", "size": "8340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cs/v2/waitset_cft/Chat_publisher.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "49655" }, { "name": "C#", "bytes": "37061" }, { "name": "C++", "bytes": "204214" }, { "name": "CMake", "bytes": "22972" }, { "name": "Lua", "bytes": "670" }, { "name": "Makefile", "bytes": "18984" }, { "name": "Python", "bytes": "3244" } ], "symlink_target": "" }
class Gradle < Formula desc "Open-source build automation tool based on the Groovy and Kotlin DSL" homepage "https://www.gradle.org/" url "https://services.gradle.org/distributions/gradle-6.3-all.zip" sha256 "0f316a67b971b7b571dac7215dcf2591a30994b3450e0629925ffcfe2c68cc5c" bottle :unneeded depends_on "openjdk" def install rm_f Dir["bin/*.bat"] libexec.install %w[bin docs lib src] (bin/"gradle").write_env_script libexec/"bin/gradle", :JAVA_HOME => "${JAVA_HOME:-#{Formula["openjdk"].opt_prefix}}" end test do assert_match version.to_s, shell_output("#{bin}/gradle --version") (testpath/"build.gradle").write <<~EOS println "gradle works!" EOS gradle_output = shell_output("#{bin}/gradle build --no-daemon") assert_includes gradle_output, "gradle works!" end end
{ "content_hash": "efcf044e9a315045edcee1008b583bb0", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 77, "avg_line_length": 30.925925925925927, "alnum_prop": 0.6910179640718563, "repo_name": "BrewTestBot/homebrew-core", "id": "234616228ee2c10212fa5c9d6697dca521df9525", "size": "835", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Formula/gradle.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Perl", "bytes": "628" }, { "name": "Ruby", "bytes": "8441524" } ], "symlink_target": "" }
// // eLongAnalyticsEventBaseModel.h // eLongAnalytics // // 用于自动打点配置文件转换,手动打点禁用 // // Created by zhaoyingze on 15/11/27. // Copyright © 2015年 elong. All rights reserved. // #import "JSONModel.h" @interface eLongAnalyticsEventBaseModel : JSONModel /** * 频道 */ @property (nonatomic, copy) NSString *ch; /** * 点位所在的类名 */ @property (nonatomic, copy) NSString *className; /** * 需要打点的方法 */ @property (nonatomic, copy) NSString *methodName; - (void)sendEventWithPageName:(NSString *)pageName; @end
{ "content_hash": "4fa05303361adf5539281d88600de65e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 51, "avg_line_length": 16.03125, "alnum_prop": 0.6900584795321637, "repo_name": "sky15179/Debug", "id": "218862a6412cbcf4af47cf1fe4482a450b345950", "size": "586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TestTabelController/elongframework/eLongFramework/eLongAnalytics/Models/eLongAnalyticsEventBaseModel.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1264019" }, { "name": "C++", "bytes": "372476" }, { "name": "DTrace", "bytes": "412" }, { "name": "Objective-C", "bytes": "6915265" }, { "name": "Objective-C++", "bytes": "172568" }, { "name": "Ruby", "bytes": "27537" }, { "name": "Shell", "bytes": "9017" }, { "name": "Swift", "bytes": "227386" } ], "symlink_target": "" }
/*! @file @author Albert Semenov @date 05/2008 */ /* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __MYGUI_RENDER_TARGET_INFO_H__ #define __MYGUI_RENDER_TARGET_INFO_H__ #include "MyGUI_Prerequest.h" namespace MyGUI { struct MYGUI_EXPORT RenderTargetInfo { public: RenderTargetInfo() : maximumDepth(0), pixScaleX(1), pixScaleY(1), hOffset(0), vOffset(0), aspectCoef(1), leftOffset(0), topOffset(0) { } void setOffset(int _left, int _top) const { leftOffset = _left; topOffset = _top; } public: float maximumDepth; float pixScaleX; float pixScaleY; float hOffset; float vOffset; float aspectCoef; mutable int leftOffset; mutable int topOffset; }; } // namespace MyGUI #endif // __MYGUI_RENDER_TARGET_INFO_H__
{ "content_hash": "91219e456b78d6a706944ecd9bd69fd8", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 76, "avg_line_length": 21.227272727272727, "alnum_prop": 0.7109207708779444, "repo_name": "wpbest/gui", "id": "8f55e798d374e7ee28eaf26e05a966fd29ed5ead", "size": "1401", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "source/testgui/MyGUI_RenderTargetInfo.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "897002" }, { "name": "C++", "bytes": "1534825" }, { "name": "Objective-C", "bytes": "26" }, { "name": "Shell", "bytes": "3798" } ], "symlink_target": "" }
<?php defined('SYSPATH') or die('No direct script access.'); abstract class Kohana_Sitemap_News implements Kohana_Sitemap_Interface { /** * @var array publication details */ protected $_publication = array ( 'publication' => NULL, 'lang' => NULL ); /** * @var array article attributes */ protected $_attributes = array ( 'access' => NULL, 'genres' => NULL, 'publication_date' => NULL, 'title' => NULL, 'keywords' => NULL, 'stock_tickers' => NULL, ); /** * @param string $publication name of the news publication. It must exactly * match the name as it appears on your articles in news.google.com, omitting * any trailing parentheticals. */ public function set_publication($publication) { $this->_publication['publication'] = $publication; return $this; } /** * @param string $lang hould be an ISO 639 Language Code (either 2 or 3 letters). * Exception: For Chinese, please use zh-cn for Simplified Chinese or zh-tw for * Traditional Chinese. * * @see http://www.loc.gov/standards/iso639-2/php/code_list.php */ public function set_lang($lang) { if ('zh-cn' !== $lang AND 'zh-tw' !== $lang) { if ( ! preg_match('/^[a-z]{2,3}$/', $lang)) { throw new InvalidArgumentException('Invalid language code'); } } $this->_publication['lang'] = $lang; return $this; } /** * @param string $access Possible values include "Subscription" or "Registration", * describing the accessibility of the article. If the article is accessible to * Google News readers without a registration or subscription, this tag should * be omitted. */ public function set_access($access) { if ('subscription' !== strtolower($access) AND 'registration' !== strtolower($access)) { throw new InvalidArgumentException('Invalid access string'); } $this->_attributes['access'] = $access; return $this; } /** * @param string $genres A comma-separated list of properties characterizing the * content of the article, such as "PressRelease" or "UserGenerated." See Google * News content properties for a list of possible values. Your content must be * labeled accurately, in order to provide a consistent experience for our users. * * @see http://www.google.com/support/webmasters/bin/answer.py?answer=93992 */ public function set_genres( array $genres) { $allowed = array('PressRelease', 'Satire', 'Blog', 'OpEd', 'Opinion', 'UserGenerated'); $difference = array_diff($genres, $allowed); if (count($difference) > 0) { throw new InvalidArgumentException('Invalid genre passed'); } $this->_attributes['genres'] = implode(',', $genres); return $this; } /** * @param integer $date Article publication date in unixtimestamp format */ public function set_publication_date($date) { $this->_attributes['publication_date'] = Sitemap::date_format($date); return $this; } /** * @param string $title The title of the news article. Note: The title may be * truncated for space reasons when shown on Google News. */ public function set_title($title) { $this->_attributes['title'] = $title; return $this; } /** * @param string $keywords A comma-separated list of keywords describing the * topic of the article. Keywords may be drawn from, but are not limited to, * the list of existing Google News keywords. * * @see http://www.google.com/support/webmasters/bin/answer.py?answer=116037 */ public function set_keywords( array $keywords) { $this->_attributes['keywords'] = implode(',', $keywords); return $this; } /** * @param string $tickers A comma-separated list of up to 5 stock tickers of * the companies, mutual funds, or other financial entities that are the main * subject of the article. * * @see http://finance.google.com/ */ public function set_stock_tickers( array $tickers) { if (count($tickers) > 5) { throw new OutOfRangeException('You can\'t provide more than 5 tickers'); } // Check ticker values. foreach($tickers as $ticker) { if (strpos($ticker, ':') === FALSE) { throw new InvalidArgumentException('The ticker '.$ticker.' is in the wrong format'); } } $this->_attributes['stock_tickers'] = implode(', ', $tickers); return $this; } public function create() { // Here we need to create a new DOMDocument. This is so we can re-import the // DOMElement at the other end. $document = new DOMDocument; $news = $document->createElement('news:news'); // Publication $publication = $document->createElement('news:publication'); $news->appendChild($publication); // Publication attributes $publication->appendChild($document->createElement('news:name', $this->_publication['publication'])); $publication->appendChild($document->createElement('news:language', $this->_publication['lang'])); // Append attributes foreach($this->_attributes as $name => $value) { if (NULL !== $value) { $news->appendChild($document->createElement('news:'.$name, $value)); } } return $news; } public function root( DOMElement & $root ) { $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:news', 'http://www.google.com/schemas/sitemap-news/0.9'); } }
{ "content_hash": "b6a6dfcf827125cc070092b0e6336012", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 121, "avg_line_length": 26.255, "alnum_prop": 0.6659683869739097, "repo_name": "killer-djon/dev-v2.web2book.ru", "id": "7bab633113f37b56b3fce6af842b2e8b4ad62b25", "size": "5251", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "sites/develop.eorder.ru/modules/sitemap/classes/kohana/sitemap/news.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "13" }, { "name": "CSS", "bytes": "13253679" }, { "name": "HTML", "bytes": "2708644" }, { "name": "Java", "bytes": "1488388" }, { "name": "JavaScript", "bytes": "30071773" }, { "name": "PHP", "bytes": "24516943" }, { "name": "Python", "bytes": "3330" }, { "name": "Ruby", "bytes": "10354" }, { "name": "Shell", "bytes": "6018" }, { "name": "Smarty", "bytes": "15040" } ], "symlink_target": "" }
package handlers import ( "fmt" "html/template" "log" "net/http" "github.com/go-martini/martini" "github.com/martini-contrib/render" "gopkg.in/mgo.v2/bson" "github.com/warren-community/warren/contenttype/user" "github.com/warren-community/warren/models" ) // Display a login form (or redirect if the user is already logged in). func (h *Handlers) DisplayLogin(w http.ResponseWriter, r *http.Request, render render.Render) { if h.user.IsAuthenticated { h.session.AddFlash(NewFlash("Already logged in!")) h.session.Save(r, w) http.Redirect(w, r, "/", http.StatusSeeOther) return } render.HTML(http.StatusOK, "user/displayLogin", map[string]interface{}{ "Title": "Log in", "User": h.user, "Flashes": h.flashes(r, w), "CSRF": h.session.Values["_csrf_token"], }) } // Log the user in. func (h *Handlers) Login(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { if h.user.IsAuthenticated { http.Redirect(w, r, "/", http.StatusSeeOther) return } username, password := r.FormValue("username"), r.FormValue("password") user, err := models.GetUser(username, h.db) if err != nil { l.Printf("Could not get user: %+v\n", err) h.InternalServerError(w, r, render) return } if !user.Authenticate(password) { h.session.AddFlash(NewFlash("Wrong username or password")) h.session.Save(r, w) http.Redirect(w, r, "/login", http.StatusSeeOther) return } h.session.Values["authenticated"] = true h.session.Values["username"] = username h.session.Save(r, w) http.Redirect(w, r, "/", http.StatusSeeOther) } // Log the user out. func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request) { h.session.Values["authenticated"] = false h.session.Values["username"] = nil h.session.Save(r, w) http.Redirect(w, r, "/", http.StatusSeeOther) } // Display a registration form (or redirect if the user is already logged in). func (h *Handlers) DisplayRegister(w http.ResponseWriter, r *http.Request, render render.Render) { if h.user.IsAuthenticated { h.session.AddFlash(NewFlash("Already logged in!")) h.session.Save(r, w) http.Redirect(w, r, "/", http.StatusSeeOther) return } render.HTML(http.StatusOK, "user/displayRegister", map[string]interface{}{ "Title": "Sign up", "User": h.user, "Flashes": h.flashes(r, w), "CSRF": h.session.Values["_csrf_token"], }) } // Register a new user. func (h *Handlers) Register(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { if h.user.IsAuthenticated { http.Redirect(w, r, "/", http.StatusSeeOther) return } username, email, password, passwordConfirm := r.FormValue("username"), r.FormValue("email"), r.FormValue("password"), r.FormValue("passwordconfirm") if username == "" || email == "" || password == "" { h.session.AddFlash(NewFlash("All fields required!", "warning")) h.session.Save(r, w) http.Redirect(w, r, "/register", http.StatusSeeOther) return } if password != passwordConfirm { h.session.AddFlash(NewFlash("Passwords did not match!", "warning")) h.session.Save(r, w) http.Redirect(w, r, "/register", http.StatusSeeOther) return } c := h.db.C("users") existing, err := c.Find(bson.M{"username": username}).Count() if err != nil { l.Printf("Could not execute find: %+v\n", err) h.InternalServerError(w, r, render) return } if existing > 0 { h.session.AddFlash(NewFlash("Username taken!", "warning")) h.session.Save(r, w) http.Redirect(w, r, "/register", http.StatusSeeOther) return } user, err := models.NewUser(username, email, password) if err != nil { l.Printf("Could not generate user: %+v\n", err) h.InternalServerError(w, r, render) return } user.Save(h.db) http.Redirect(w, r, "/login", http.StatusSeeOther) } // TODO Confirm a user's email address. func (h *Handlers) Confirm(w http.ResponseWriter, r *http.Request) { http.Error(w, "Not implemented", http.StatusNotImplemented) } // Display a user's profile page. func (h *Handlers) DisplayUser(w http.ResponseWriter, r *http.Request, l *log.Logger, params martini.Params, render render.Render) { username := params["username"] var user models.User if h.user.IsAuthenticated && username == h.user.Model.Username { user = h.user.Model } else { var err error user, err = models.GetUser(username, h.db) if err != nil { l.Printf("Could not fetch user from database: %+v\n", err) h.InternalServerError(w, r, render) return } if user.Username == "" { h.NotFound(w, r, render) return } } entities, err := user.Entities(h.db) if err != nil { l.Printf("Could not fetch entities from database: %+v\n", err) h.InternalServerError(w, r, render) return } profile, err := user.Profile(h.db) if err != nil { if err.Error() == "not found" { profile = models.Entity{ RenderedContent: fmt.Sprintf("%s hasn't created a profile yet.", username), } } else { l.Printf("Could not fetch profile from database: %+v\n", err) h.InternalServerError(w, r, render) return } } render.HTML(http.StatusOK, "user/displayUser", map[string]interface{}{ "Title": fmt.Sprintf("User %s", user.Username), "User": h.user, "Flashes": h.flashes(r, w), "CSRF": h.session.Values["_csrf_token"], "DisplayUser": user, "IsFollowing": h.user.Model.IsFollowing(user.Username), "IsFriend": h.user.Model.IsFriend(user.Username), "FriendRequestPending": h.user.Model.HasRequestedFriendship(user.Username), "HasRequestedFriendship": user.HasRequestedFriendship(h.user.Model.Username), "Entities": entities, "ProfileStr": template.HTML(profile.RenderedContent), }) } // Display the page for editing profile and settings. func (h *Handlers) DisplayEditProfile(w http.ResponseWriter, r *http.Request, l *log.Logger, render render.Render) { if !h.user.IsAuthenticated { h.session.AddFlash(NewFlash("Please log in to continue", "warning")) h.session.Save(r, w) http.Redirect(w, r, "/login", http.StatusSeeOther) return } profile, err := h.user.Model.Profile(h.db) if err != nil && err.Error() != "not found" { l.Printf("Could not load profile: %+v\n", err) h.InternalServerError(w, r, render) return } content := user.Profile{} if profile.Content != nil { content = user.NewProfile(profile.Content.(bson.M)) } render.HTML(http.StatusOK, "user/displayEditProfile", map[string]interface{}{ "Title": "Edit profile and settings", "User": h.user, "Flashes": h.flashes(r, w), "CSRF": h.session.Values["_csrf_token"], "ProfileStr": content.ProfileText, "Pronouns": content.Pronouns, "Website": content.Website, }) } // Edit the profile information for a user. func (h *Handlers) EditProfile(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { if !h.user.IsAuthenticated { h.session.AddFlash(NewFlash("Please log in to continue", "warning")) h.session.Save(r, w) http.Redirect(w, r, "/login", http.StatusSeeOther) return } profileStr, website, pronouns := r.FormValue("profile"), r.FormValue("website"), r.FormValue("pronouns") profile, err := h.user.Model.Profile(h.db) if err != nil && err.Error() != "not found" { l.Printf("Error retrieving existing profile: %+v\n", err) h.InternalServerError(w, r, render) return } profile.Delete(h.db) profile = models.NewEntity( "user/profile", h.user.Model.Username, h.user.Model.Username, false, "", []string{}, user.Profile{ ProfileText: profileStr, Pronouns: pronouns, Website: website, }, ) profile.Save(h.db, h.esConn) h.session.AddFlash(NewFlash("Profile updated!", "success")) h.session.Save(r, w) http.Redirect(w, r, fmt.Sprintf("/~%s", h.user.Model.Username), http.StatusSeeOther) } // Edit the raw settings of a user (password, email). func (h *Handlers) EditSettings(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { if !h.user.IsAuthenticated { h.session.AddFlash(NewFlash("Please log in to continue", "warning")) h.session.Save(r, w) http.Redirect(w, r, "/login", http.StatusSeeOther) return } username, password, newpassword, newpasswordconfirm, email := r.FormValue("username"), r.FormValue("password"), r.FormValue("newpassword"), r.FormValue("newpasswordconfirm"), r.FormValue("email") if username != h.user.Model.Username { l.Print("SECURITY: User %s attempted to save to another profile: %s", username, h.user.Model.Username) h.Forbidden(w, r, render) return } if !h.user.Model.Authenticate(password) { h.session.AddFlash(NewFlash("Current password did not match!", "danger")) h.session.Save(r, w) http.Redirect(w, r, "/user/profile", http.StatusSeeOther) return } if newpassword != "" { if newpassword != newpasswordconfirm { h.session.AddFlash(NewFlash("New passwords did not match!", "danger")) h.session.Save(r, w) http.Redirect(w, r, "/user/profile", http.StatusSeeOther) return } h.user.Model.SetPassword(newpassword) } h.user.Model.Email = email h.user.Model.Save(h.db) h.session.AddFlash(NewFlash("Settings updated!", "success")) h.session.Save(r, w) http.Redirect(w, r, "/user/profile", http.StatusSeeOther) } // Attempt to follow a user from the logged-in account. func (h *Handlers) FollowUser(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { username := r.FormValue("username") user, err := models.GetUser(username, h.db) if err != nil { l.Printf("Could not fetch user from database: %+v\n", err) h.InternalServerError(w, r, render) return } if user.Username == "" { h.NotFound(w, r, render) return } h.user.Model.AddFollowing(&user) h.user.Model.Save(h.db) user.Save(h.db) h.session.AddFlash(NewFlash("User followed!", "success")) h.session.Save(r, w) http.Redirect(w, r, fmt.Sprintf("/~%s", username), http.StatusSeeOther) } // Attempt to unfollow a user from from the logged-in account. func (h *Handlers) UnfollowUser(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { username := r.FormValue("username") user, err := models.GetUser(username, h.db) if err != nil { l.Printf("Could not fetch user from database: %+v\n", err) h.InternalServerError(w, r, render) return } if user.Username == "" { h.NotFound(w, r, render) return } h.user.Model.RemoveFollowing(&user) h.user.Model.Save(h.db) user.Save(h.db) h.session.AddFlash(NewFlash("User unfollowed!", "success")) h.session.Save(r, w) http.Redirect(w, r, fmt.Sprintf("/~%s", username), http.StatusSeeOther) } // Attempt to request a friendship with a user from the logged-in account. func (h *Handlers) RequestFriendship(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { username := r.FormValue("username") user, err := models.GetUser(username, h.db) if err != nil { l.Printf("Could not fetch user from database: %+v\n", err) h.InternalServerError(w, r, render) return } if user.Username == "" { h.NotFound(w, r, render) return } h.user.Model.RequestFriendship(&user) h.user.Model.Save(h.db) user.Save(h.db) h.session.AddFlash(NewFlash("Friendship requested!", "success")) h.session.Save(r, w) http.Redirect(w, r, fmt.Sprintf("/~%s", username), http.StatusSeeOther) } // Display currently pending friendship requests for the logged-in account. func (h *Handlers) DisplayFriendshipRequests(w http.ResponseWriter, r *http.Request, l *log.Logger, render render.Render) { if !h.user.IsAuthenticated { h.session.AddFlash(NewFlash("Please log in to continue", "warning")) h.session.Save(r, w) http.Redirect(w, r, "/login", http.StatusSeeOther) return } render.HTML(http.StatusOK, "user/displayFriendshipRequests", map[string]interface{}{ "Title": "Friendship Requests", "User": h.user, "Flashes": h.flashes(r, w), "CSRF": h.session.Values["_csrf_token"], }) } // Confirm a friendship request. func (h *Handlers) ConfirmFriendship(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { username := r.FormValue("username") user, err := models.GetUser(username, h.db) if err != nil { l.Printf("Could not fetch user from database: %+v\n", err) h.InternalServerError(w, r, render) return } if user.Username == "" { h.NotFound(w, r, render) return } h.user.Model.AddFriendship(&user) h.user.Model.Save(h.db) user.Save(h.db) h.session.AddFlash(NewFlash("Friendship confirmed!", "success")) h.session.Save(r, w) http.Redirect(w, r, fmt.Sprintf("/~%s", username), http.StatusSeeOther) } // Reject a friendship request. func (h *Handlers) RejectFriendship(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { username := r.FormValue("username") user, err := models.GetUser(username, h.db) if err != nil { l.Printf("Could not fetch user from database: %+v\n", err) h.InternalServerError(w, r, render) return } if user.Username == "" { h.NotFound(w, r, render) return } user.RemoveFriendshipRequest(&h.user.Model) h.user.Model.Save(h.db) user.Save(h.db) h.session.AddFlash(NewFlash("Friendship request rejected!", "success")) h.session.Save(r, w) http.Redirect(w, r, "/user/friend/requests", http.StatusSeeOther) } // Remove a friendship between two accounts. func (h *Handlers) CancelFriendship(w http.ResponseWriter, r *http.Request, render render.Render, l *log.Logger) { username := r.FormValue("username") user, err := models.GetUser(username, h.db) if err != nil { l.Printf("Could not fetch user from database: %+v\n", err) h.InternalServerError(w, r, render) return } if user.Username == "" { h.NotFound(w, r, render) return } h.user.Model.RemoveFriendship(&user) h.user.Model.Save(h.db) user.Save(h.db) h.session.AddFlash(NewFlash("Friendship canceled!", "success")) h.session.Save(r, w) http.Redirect(w, r, fmt.Sprintf("/~%s", username), http.StatusSeeOther) }
{ "content_hash": "fdb86442ba94c02f30cb1e8c791db29f", "timestamp": "", "source": "github", "line_count": 421, "max_line_length": 196, "avg_line_length": 33.21852731591449, "alnum_prop": 0.6835895602431177, "repo_name": "warren-community/warren", "id": "0557636264f13224692b432bc2f3e831fd421fa0", "size": "14122", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "handlers/user.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "249" }, { "name": "CoffeeScript", "bytes": "149" }, { "name": "Go", "bytes": "60159" }, { "name": "Makefile", "bytes": "2383" } ], "symlink_target": "" }
<div id="__html_id__" class="__style_prefix__ __class__ bx-def-margin-right-auto bx-def-margin-thd-topbottom bx-clearfix" bx_report_data_count="__count__"> <div class="__style_prefix__-element-holder">__do_report__</div> <bx_if:show_counter> <div class="__style_prefix__-counter-holder bx-def-margin-sec-left"<bx_if:show_hidden> style="display:none"</bx_if:show_hidden>>__counter__</div> </bx_if:show_counter> </div> __script__
{ "content_hash": "282b7f35c87f2fc401b4df7fb8dc4b76", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 155, "avg_line_length": 61.714285714285715, "alnum_prop": 0.6782407407407407, "repo_name": "camperjz/trident", "id": "63c87f262a81e1d4a7ce6e9257d5255bc873983b", "size": "432", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "upgrade/files/8.0.1-9.0.0.B1/files/template/report_element_block.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1763" }, { "name": "CSS", "bytes": "1481231" }, { "name": "HTML", "bytes": "690596" }, { "name": "JavaScript", "bytes": "4916309" }, { "name": "PHP", "bytes": "28451148" }, { "name": "Shell", "bytes": "1265" } ], "symlink_target": "" }
package xyz.cofe.odtexport.xtest /** * Шаблон обработки XML узла */ trait NodePattern extends XTest { import org.w3c.dom.{Node => XMLNode}; /** * Вызывается при входе в узел XML * @param node Узел XML * @return True - Входить в дочение элементы */ def enter(node:XMLNode):Boolean = true; /** * Вызывается при выходе из узла * @param node Узел XML */ def exit(node:XMLNode):Unit = {}; /** * Вызывается перед началом обработки первого узла */ def begin():Unit = {}; /** * Вызывается после обработки последнего узла */ def end():Unit = {}; } /** * Базовая реализация шаблона обработки XML узла * @param xtest - Условие совпадения текущего узла древа. * @param delegate - Шаблон которому делегируются вызовы (возможно null). */ class NodePatternBasic( val xtest:XTest, val delegate:NodePatternBasic = null ) extends XTest with NodePattern { import org.w3c.dom.{Node => XMLNode}; /** * Проверяет совпадение узла с указанным условием * @param node XML узел */ override def test(node:XMLNode):Boolean = xtest.test(node); /** * Вызывается при предобработке узла и делегурет вызов (если указан делегат) */ override def enter(node:XMLNode):Boolean = { if( delegate!=null ) return delegate.enter(node); true; } /** * Вызывается при постобработке узла и делегурет вызов (если указан делегат) */ override def exit(node:XMLNode):Unit = if( delegate!=null )delegate.exit(node); /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * @param f Функц предобработки узла * @return Шаблон с функцией. */ def enter( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest,this){ override def enter(node:XMLNode):Boolean = { super.enter(node); f; true } } /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * При этом вхождение в дочерние не будет происходить. * @param f Функц предобработки узла * @return Шаблон с функцией. */ def skip( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest,this){ override def enter(node:XMLNode):Boolean = { super.enter(node); f; false } } /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * @param f Функц обработки узла * @return Шаблон с функцией. */ def enterNode( f: (XMLNode)=>Unit ):NodePatternBasic = new NodePatternBasic(xtest) { override def enter(node:XMLNode):Boolean = { f(node); true } }; /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * При этом вхождение в дочерние не будет происходить. * @param f Функц обработки узла * @return Шаблон с функцией. */ def skipNode( f: (XMLNode)=>Unit ):NodePatternBasic = new NodePatternBasic(xtest) { override def enter(node:XMLNode):Boolean = { f(node); false } }; /** * Создает шаблон с функц. пост срабатывающий XML узела. * @param f Функц постобработки узла * @return Шаблон с функцией. */ def exit( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest,this){ override def exit(node:XMLNode):Unit = { f; super.exit(node); } } /** * Создает шаблон с функц. пост срабатывающий XML узела. * @param f Функц постобработки узла * @return Шаблон с функцией. */ def exitNode( f: (XMLNode)=>Unit ):NodePatternBasic = new NodePatternBasic(xtest,this){ override def exit(node:XMLNode):Unit = { f(node); super.exit(node); } } override def begin():Unit = if( delegate!=null ) delegate.begin(); override def end():Unit = if( delegate!=null ) delegate.end(); def begin( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest,this){ override def begin():Unit = { super.begin(); f; } } def end( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest,this){ override def end():Unit = { f; super.end(); } } } /** * Объект с неявным преобразователем Условие в Шаблон */ object NodePattern { /** * Преобразователь Условие в Шаблон * @param xtest Условие * @return Пустой шаблон */ implicit def extendXTest( xtest:XTest ):XTestExtension = new XTestExtension(xtest); } /** * Расширение условие до возможности создания шаблонов */ class XTestExtension( val xtest:XTest ) { import org.w3c.dom.{Node => XMLNode}; /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * @param f Функц обработки узла * @return Шаблон с функцией. */ def enter( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest) { override def enter(node:XMLNode):Boolean = { f; true } }; /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * При этом вхождение в дочерние не будет происходить. * @param f Функц обработки узла * @return Шаблон с функцией. */ def skip( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest) { override def enter(node:XMLNode):Boolean = { f; false } }; /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * @param f Функц обработки узла * @return Шаблон с функцией. */ def enterNode( f: (XMLNode)=>Unit ):NodePatternBasic = new NodePatternBasic(xtest) { override def enter(node:XMLNode):Boolean = { f(node); true } }; /** * Создает шаблон с функц. срабатывающий при входе в XML узел. * При этом вхождение в дочерние не будет происходить. * @param f Функц обработки узла * @return Шаблон с функцией. */ def skipNode( f: (XMLNode)=>Unit ):NodePatternBasic = new NodePatternBasic(xtest) { override def enter(node:XMLNode):Boolean = { f(node); false } }; /** * Создает шаблон с функц. пост срабатывающий XML узела. * @param f Функц постобработки узла * @return Шаблон с функцией. */ def exit( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest) { override def exit(node:XMLNode):Unit = { f; } } /** * Создает шаблон с функц. преобработки древа * @param f Функция обработки * @return Шаблон с функцией. */ def begin( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest){ override def begin():Unit = { super.begin(); f; } } /** * Создает шаблон с функц. постобработки древа * @param f Функция обработки * @return Шаблон с функцией. */ def end( f: =>Unit ):NodePatternBasic = new NodePatternBasic(xtest){ override def end():Unit = { f; super.end(); } } }
{ "content_hash": "bd810b8985f8edf34a31c3c0624d677e", "timestamp": "", "source": "github", "line_count": 263, "max_line_length": 110, "avg_line_length": 23.840304182509506, "alnum_prop": 0.6708133971291866, "repo_name": "gochaorg/odt-export", "id": "d930340b4b0bc05df6897abebc23de84504c6e0d", "size": "10489", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/xyz/cofe/odtexport/xtest/NodePattern.scala", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2343" }, { "name": "Java", "bytes": "1064" }, { "name": "Scala", "bytes": "147917" } ], "symlink_target": "" }
package com.xeiam.xchange.kraken.dto.marketdata; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonProperty; import com.xeiam.xchange.kraken.dto.trade.KrakenOrderType; import com.xeiam.xchange.kraken.dto.trade.KrakenType; public class KrakenPublicTrade { private final BigDecimal price; private final BigDecimal volume; private final double time; private final KrakenType type; private final KrakenOrderType orderType; private final String miscellaneous; public KrakenPublicTrade(@JsonProperty("price") BigDecimal price, @JsonProperty("volume") BigDecimal volume, @JsonProperty("time") double time, @JsonProperty("type") KrakenType type, @JsonProperty("orderType") KrakenOrderType orderType, @JsonProperty("miscellaneous") String miscellaneous) { this.price = price; this.volume = volume; this.time = time; this.type = type; this.orderType = orderType; this.miscellaneous = miscellaneous; } public BigDecimal getPrice() { return price; } public BigDecimal getVolume() { return volume; } public double getTime() { return time; } public KrakenType getType() { return type; } public KrakenOrderType getOrderType() { return orderType; } public String getMiscellaneous() { return miscellaneous; } @Override public String toString() { return "KrakenPublicTrade [price=" + price + ", volume=" + volume + ", time=" + time + ", type=" + type + ", orderType=" + orderType + ", miscellaneous=" + miscellaneous + "]"; } }
{ "content_hash": "9919703e8acb5cc398870046daa1de4c", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 184, "avg_line_length": 23.96923076923077, "alnum_prop": 0.7105263157894737, "repo_name": "coingecko/XChange", "id": "04f64f45fc1eff3753a9064c46a1cb117e4f6988", "size": "1558", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "xchange-kraken/src/main/java/com/xeiam/xchange/kraken/dto/marketdata/KrakenPublicTrade.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "3649264" } ], "symlink_target": "" }
/** * This file is part of Husky, a scalable, event-driven JavaScript web applications framework. * * (c) Thomas Schedler <thomas@chirimoya.at> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. * * @module husky/extensions */ define('husky/extensions/mediator', function() { 'use strict'; return function(app) { // mediator default config var defaults = { wildcard: true, delimiter: '.', newListener: true, maxListeners: 20 }, attachListener = function(listenerType) { return function(name, listener, context) { if (typeof listener !== 'function' || typeof name !== 'string') { throw new Error('Invalid arguments passed to sandbox.' + listenerType); } context = context || this; var callback = function() { var args = Array.prototype.slice.call(arguments); try { listener.apply(context, args); } catch (e) { app.logger.error('Error caught in listener "' + name + '", called with arguments: ', args, '\nError:', e.message, e, args); } }; this.events = this.events || []; this.events.push({ name: name, listener: listener, callback: callback }); app.core.mediator[listenerType](name, callback); }; }; // extension definition return { name: 'mediator', require: { paths: { eventemitter: 'bower_components/eventemitter2/lib/eventemitter2' } }, initialize: function(app) { var EventEmitter = require('eventemitter'), mediator; app.config.mediator = app.core.util.defaults(app.config.mediator || {}, defaults); mediator = new EventEmitter(app.config.mediator); app.core.mediator = mediator; /** * @class Sandbox */ // extending the default sandbox /** * @method on * @param {String} name * @param {Function} listener */ app.sandbox.on = attachListener('on'); /** * @method once * @param {String} name * @param {Function} listener */ app.sandbox.once = attachListener('once'); /** * @method off * @param {String} name * @param {Function} listener */ app.sandbox.off = function(name, listener) { if (!this.events) { return; } this.events = app.core.util.reject(this.events, function(event) { var match = (event.name === name && event.listener === listener); if (match) { mediator.off(name, event.callback); } return match; }); }; /** * @method emit * @param {String} name * @param {Object} payload */ app.sandbox.emit = function() { var debug = app.config.debug, eventLogData; if (debug === true || (!!debug.enable && (debug.components.length === 0 || debug.components.indexOf('husky:mediator') !== -1))) { eventLogData = Array.prototype.slice.call(arguments); eventLogData.unshift('Event emitted'); app.logger.log.apply(app.logger, eventLogData); } mediator.emit.apply(mediator, arguments); }; /** * @method stopListening */ app.sandbox.stopListening = function() { if (!this.events) { return; } app.core.util.each(this.events, function(event) { mediator.off(event.name, event.callback); }); }; // default event listener mediator.on(['husky', 'sandbox', 'stop'], function(sandbox) { sandbox.stopListening(); }); mediator.on(['husky', 'sandbox', 'pause'], function(sandbox) { // TODO Implement pause event listening app.logger.warn('ATTENTION: Sandbox pause not implemented!', sandbox); }); mediator.on(['husky', 'sandbox', 'continue'], function(sandbox) { // TODO Implement continue event listening app.logger.warn('ATTENTION: Sandbox continue not implemented!', sandbox); }); } }; }; });
{ "content_hash": "05b0aad9d1adddc6d0e78907a60dead2", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 112, "avg_line_length": 32.660714285714285, "alnum_prop": 0.4284672863131037, "repo_name": "massiveart/husky-base", "id": "3c343b62386bfb2c9abec7a38eb1472e0daa4427", "size": "5487", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/extensions/mediator.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "366394" }, { "name": "JavaScript", "bytes": "85940" } ], "symlink_target": "" }
<?php namespace Markup\Contentful\Tests\Filter; use Markup\Contentful\Filter\ContentTypeFilter; class ContentTypeFilterTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $this->value = 'page'; $this->filter = new ContentTypeFilter($this->value); } public function testIsFilter() { $this->assertInstanceOf('Markup\Contentful\FilterInterface', $this->filter); } public function testGetKey() { $this->assertEquals('content_type', $this->filter->getKey()); } public function testGetValue() { $this->assertEquals($this->value, $this->filter->getValue()); } }
{ "content_hash": "1723e36f550b58567db8c05b7fba7b8b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 84, "avg_line_length": 23.06896551724138, "alnum_prop": 0.6502242152466368, "repo_name": "gsdevme/contentful", "id": "6b309752beb9d66ddcd889fededa4fad4be6c3b2", "size": "669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Filter/ContentTypeFilterTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "202468" } ], "symlink_target": "" }
""" Demo: `page_a` and `page_b` are rendered into `page_all`. Note: both `page_a` and `page_b` extend same `master`, inheritance chains intersect at `content` placeholder. """ import unittest from wheezy.template.engine import Engine from wheezy.template.ext.core import CoreExtension from wheezy.template.loader import DictLoader master = """ @def content(): @end @content() """ page_a = """ @extends('master') @def content(): a @end """ page_b = """ @extends('master') @def content(): b @end """ page_all = """ @_r('page_a', ctx, {}, {}) @_r('page_b', ctx, {}, {}) """ pages = { 'master': master, 'page_a': page_a, 'page_b': page_b, 'page_all': page_all } engine = Engine( loader=DictLoader(pages), extensions=[CoreExtension()] ) class TestCase(unittest.TestCase): def test_render(self): template = engine.get_template('page_all') r = template.render({}) self.assertEqual(['a', 'b'], r.split()) if __name__ == '__main__': unittest.main()
{ "content_hash": "7b8484970bb9a2b1d997ea6d806507a7", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 70, "avg_line_length": 16.03125, "alnum_prop": 0.6003898635477583, "repo_name": "ezotrank/wheezy.template", "id": "43886634f1a2454e5e619390bb2232f885090c27", "size": "1026", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demos/include/render.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "636" }, { "name": "Makefile", "bytes": "2504" }, { "name": "Python", "bytes": "114858" }, { "name": "Shell", "bytes": "212" }, { "name": "VimL", "bytes": "758" } ], "symlink_target": "" }
from neo4jrestclient.client import GraphDatabase import getpass def flatten_dict(dictToFlatten): #Pass through for now. Will flatten later (because neo4j doesn't like embedded dictionaries) return dictToFlatten class Neo4jLoader(object): def __init__(self, url, username='neo4j', password=None): if(not password): password=getpass.getpass() self.gdb = GraphDatabase(url, username=username, password=password) def add_vertex(self, vertex): properties = flatten_dict(vertex.properties) jprops = str(properties).replace("{'","{").replace("':",":").replace(", '",", ") queryString = "MERGE (a:%s {hashcode:'%s'}) ON CREATE SET a=%s ON MATCH SET a+=%s"%(vertex.label, vertex.properties['hashcode'], jprops, jprops) return self.gdb.query(queryString) def add_edge(self, edge): properties = flatten_dict(edge.properties) jprops = str(properties).replace("{'","{").replace("':",":").replace(", '",", ") queryString = "MATCH (src:%s {hashcode:'%s'}), (dst:%s {hashcode:'%s'}) MERGE (src)-[:%s %s]->(dst)"%(edge.srcVertex.label, edge.srcVertex.id, edge.dstVertex.label, edge.dstVertex.id, edge.relationship, jprops) return self.gdb.query(queryString) def load_from_model(self, model): for vid in model.vertices: self.add_vertex(model.vertices[vid]) for eid in model.edges: self.add_edge(model.edges[eid])
{ "content_hash": "136c9bc05f8c7c2790565cf3b56319ab", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 218, "avg_line_length": 47.03225806451613, "alnum_prop": 0.6433470507544582, "repo_name": "chroniccrash/c4rtographer", "id": "439e3d5d6ccb8306d933439cf1e671f84e659aeb", "size": "1458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "neo4jloader.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "21720" } ], "symlink_target": "" }
* dependencies updates ## **2022-09-18** - new version 3.8.0 * dependencies updates * drop node 12.x test support ## **2022-08-22** - new version 3.7.13 * dependencies updates * add param expiry_seconds to getDockerCredentials ## **2022-08-13** - new version 3.7.12 * dependencies updates ## **2022-07-25** - new version 3.7.11 * dependencies updates ## **2022-07-09** - new version 3.7.10 * dependencies updates * fix IApp type ## **2022-06-18** - new version 3.7.9 * dependencies updates ## **2022-05-29** - new version 3.7.8 * npm audit + dependencies updates ## **2022-05-21** - new version 3.7.7 * npm audit + dependencies updates ## 2022-05-07 - new version 3.7.6 * add node 18.x test support * drop node 10.x test support * fix app spec types, thanks ([@carlosbaraza](https://github.com/carlosbaraza)) * npm audit + dependencies updates ## **2022-04-30** - new version 3.7.5 * add downloads badge to readme.md * npm audit + dependencies updates * remove console.log from spec file ## **2022-04-09** - new version 3.7.4 * npm audit + dependencies updates ## **2022-03-26** - new version 3.7.3 * npm audit + dependencies updates ## **2022-03-13** - new version 3.7.2 * npm audit + dependencies updates ## **2022-02-26** - new version 3.7.1 * npm audit + dependencies updates ## **2022-02-16** - new version 3.7.0 * npm audit + dependencies updates * add module dots.monitoring * breaking change: removed dots.util, now it's called dots.modules.common ## **2022-02-10** - new version 3.6.3 * npm audit + dependencies updates * fix dots.action.getAction(input) (https://github.com/pjpimentel/dots/issues/186) ## **2021-10-30** - new version 3.6.2 * npm audit + dependencies updates ## **2021-10-05** - new version 3.6.1 * readme update + docs update thanks ([@codyogden](https://github.com/codyogden)) ## **2021-10-04** - new version 3.6.0 * add "force_build" input to dots.app.createAppDeployment ## **2021-09-25** - new version 3.5.9 * npm audit + dependencies updates ## **2021-09-04** - new version 3.5.8 * npm audit + dependencies updates ## **2021-06-14** - new version 3.5.7 * npm audit + dependencies updates ## **2021-05-29** - new version 3.5.6 * npm audit + dependencies updates * security update, https://github.com/advisories/GHSA-6fc8-4gx4-v693 ## **2021-05-17** * fixed domain module docs ## **2021-05-06** - new version: 3.5.5 * npm audit + dependencies updates * security update, https://github.com/advisories/GHSA-35jh-r3h4-6jhm ## **2021-05-01** - new version: 3.5.4 * npm audit + dependencies updates * add method volume.deleteVolumeByName ## **2021-03-29** - new version: 3.5.3 * npm audit + dependencies updates ## **2020-12-22** - new version: 3.5.2 * npm audit + dependencies updates ## **2020-12-03** - new version: 3.5.1 * app platform type fixes (thanks ([@rijkvanzanten](https://github.com/rijkvanzanten))) ## **2020-11-21** - new version: 3.5.0 * npm audit + dependencies updates * add app module * removed node 8 test support * add k8s container registry methods ## **2020-11-01** - new version: 3.4.0 * add missing attributes to firewall type * npm audit + dependencies updates * add list domain record filters * add k8s node pool taints * add droplet.destroyDropletAndAllAssociatedResources * add droplet.destroyDropletAndAssociatedResources * add droplet.getDropletDestroyStatus * add droplet.listDropletAssociatedResources * add droplet.retryDropletDestroy * "add is_default" parameter to vpc.updateVpc and vpc.createVpc * removed "id" field compatibility, see 3.1.0 ## **2020-08-10** - new version: 3.3.3 * load balancer types * npm audit + dependencies updates ## **2020-07-22** - new version: 3.3.2 * pkg.json homepage ## **2020-07-15** - new version: 3.3.1 * npm audit + dependencies updates ## **2020-06-20** - new version: 3.3.0 * add listInvoices, downloadInvoice, getInvoiceSummary, getInvoice to customer module * npm audit + dependencies updates ## **2020-05-22** - new version: 3.2.1 * ICreateDropletsApiRequest && ICreateDropletApiRequest ssh_keys attr ## **2020-05-03** - new version: 3.2.0 * add vpc module * add kubernetes node pool labels * add mysql_settings to createDatabaseClusterUser * npm audit ## **2020-04-30** - new version: 3.1.10 * add customer.getBalance * add customer.listBillingHistory * fix dev dependencies security issue GHSA-jpcq-cgw6-v4j6 * fix DO changed list-all-droplet-neighbors behavior https://developers.digitalocean.com/documentation/changelog/api-v2/changes-to-the-droplet-neighbors-report/ ## **2020-04-27** - new version: 3.1.9 * IKubernetesClusterStatus type * npm audit ## **2020-04-18** - new version: 3.1.8 * IDroplet type ## **2020-03-17** - new version: 3.1.7 * packages update * npm audit ## **2020-03-15** - new version: 3.1.6 * automatic update package acorn from 5.7.3 to 5.7.4 ## **2019-12-15** - new version: 3.1.5 * fix quality gate issues ## **2019-12-15** - new version: 3.1.4 * add **cdn-endpoints** module * add **container-registry** module * fix list-available-options-of-kubernetes url path ## **2019-12-14** - new version: 3.1.3 * add **kubernetes** module * fix updateLoadBalancer test ## **2019-12-12** - new version: 3.1.2 * add **project** module ## **2019-12-10** - new version: 3.1.1 * add **droplet**.deleteDropletsByTag ([@Cosmic-Goat](https://github.com/Cosmic-Goat)) ## **2019-12-08** - new version: 3.1.0 the `id` input was removed from the following methods to avoid missunderstands. now it is `{entity}_id`. (to allow backward compatibility the `id` field still accepted but will be removed in future versions) the following methods were affected: * add **database** module * **loadBalancer**.addDropletsToLoadBalancer >> id -> load_balancer_id * **loadBalancer**.addRulesToLoadBalancer >> id -> load_balancer_id * **loadBalancer**.deleteLoadBalancer >> id -> load_balancer_id * **loadBalancer**.getLoadBalancer >> id -> load_balancer_id * **loadBalancer**.removeDropletsFromLoadBalancer >> id -> load_balancer_id * **loadBalancer**.removeRulesFromLoadBalancer >> id -> load_balancer_id * **loadBalancer**.updateLoadBalancer >> id -> load_balancer_id * **snapshot**.deleteSnapshot >> id -> snapshot_id * **snapshot**.getSnapshot >> id -> snapshot_id * **sshKey**.destroySshKey >> id -> ssh_key_id * **sshKey**.getSshKey >> id -> ssh_key_id * **sshKey**.updateSshKey >> id -> ssh_key_id * **volume**.attachVolumeToDroplet >> id -> volume_id * **volume**.createVolumeSnapshot >> id -> volume_id * **volume**.deleteVolume >> id -> volume_id * **volume**.detachVolumeFromDroplet >> id -> volume_id * **volume**.getVolume >> id -> volume_id * **volume**.listVolumeActions >> id -> volume_id * **volume**.listVolumeSnapshots >> id -> volume_id * **volume**.resizeVolume >> id -> volume_id ## **2019-11-20** - new version: 3.0.2 * browser build ## **2019-11-17** - new version: 3.0.1 * updated main readme ## **2019-11-09** - new version: 3.0.0 project refactor to make it (simple and better) to (use and mantain). if you are using the 2.6.0 and migrate to 3.0.0 you will need to change the inputs/outputs to fit the new pattern. the main changes are: * not using rxjs anymore, just simple promises. * the return signature contain the full http response. * as DO use snake_case, ALL camelCase properties were removed. * unit tests with 100% code coverage. ## version 2.6.0 * initial stable version
{ "content_hash": "d0ede59bbc18066186e72f5a88820385", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 160, "avg_line_length": 26.387900355871885, "alnum_prop": 0.6948078219824679, "repo_name": "pjpimentel/dots", "id": "95b5a3c54bbb78ac103542cc173678acacd003e0", "size": "7467", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "927" }, { "name": "TypeScript", "bytes": "1044738" } ], "symlink_target": "" }
<!doctype html> <html> <head></head> <body> <div style="float:left; display:inline; margin-right:3px;"> <h3>POSITIONED</h3> <div class="container"><span class="prev bl">BLOCK</span><span class="pos next in">INLINE POS</span></div> <div class="container"> <span class="prev bl">BLOCK</span> <div class="pos next bl">BLOCK POS</div> </div> <div class="container"> <span class="prev bl">BLOCK</span> <div class="pos next ib">INLINE BLOCK POS</div> </div> </div> <div style="float:left; display:inline;"> <h3>STATIC</h3> <div class="container"><span class="prev bl">BLOCK</span><span class="next in">INLINE STATIC</span></div> <div class="container"> <span class="prev bl">BLOCK</span> <div class="next bl">BLOCK STATIC</div> </div> <div class="container"> <span class="prev bl">BLOCK</span> <div class="next ib">INLINE BLOCK STATIC</div> </div> </div> </body> </html>
{ "content_hash": "2f958928d5cac4d2ff5fe2fea34ac278", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 112, "avg_line_length": 34.06666666666667, "alnum_prop": 0.576320939334638, "repo_name": "dota8/dota8.github.io", "id": "b6fe1e31feb9f8c382ab16c3b16d01a862f430e2", "size": "1022", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/RM8012/RM8012-2.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16260" }, { "name": "HTML", "bytes": "6713234" }, { "name": "JavaScript", "bytes": "18717" }, { "name": "PHP", "bytes": "5618" }, { "name": "Pascal", "bytes": "1375" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Azure.Messaging.EventHubs { /// <summary> /// Specifies the type of protocol and transport that will be used for communicating with /// Azure Event Hubs. /// </summary> /// public enum EventHubsTransportType { /// <summary>The connection uses the AMQP protocol over TCP.</summary> AmqpTcp, /// <summary>The connection uses the AMQP protocol over web sockets.</summary> AmqpWebSockets } }
{ "content_hash": "93783aac8f14a174843cf34430772591", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 95, "avg_line_length": 29.736842105263158, "alnum_prop": 0.6566371681415929, "repo_name": "stankovski/azure-sdk-for-net", "id": "fb87dcd150990d30f50d63f5c0ba949a2e3014b8", "size": "567", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "sdk/eventhub/Azure.Messaging.EventHubs/src/EventHubsTransportType.cs", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "33972632" }, { "name": "Cucumber", "bytes": "89597" }, { "name": "Shell", "bytes": "675" } ], "symlink_target": "" }
@NonNullApi package com.google.android.exoplayer2.source.mediaparser; import com.google.android.exoplayer2.util.NonNullApi;
{ "content_hash": "1334b9890b2d8c4346a08c6934825e1a", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 57, "avg_line_length": 25.2, "alnum_prop": 0.8412698412698413, "repo_name": "amzn/exoplayer-amazon-port", "id": "3eedf0c7a4e9db06977374908500bfcf2ded2220", "size": "745", "binary": false, "copies": "3", "ref": "refs/heads/amazon/r2.17.1", "path": "library/core/src/main/java/com/google/android/exoplayer2/source/mediaparser/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "60500" }, { "name": "Java", "bytes": "6311191" }, { "name": "Makefile", "bytes": "13718" }, { "name": "Shell", "bytes": "5784" } ], "symlink_target": "" }
import { Directive, Input, HostListener, Renderer, ElementRef, DoCheck, TemplateRef, ViewContainerRef } from '@angular/core'; const EASE_ACCELERATION = 1.005; @Directive({ selector: '[treeAnimateOpen]' }) export class TreeAnimateOpenDirective { private _isOpen: boolean; @Input('treeAnimateOpenSpeed') animateSpeed: number; @Input('treeAnimateOpenAcceleration') animateAcceleration: number; @Input('treeAnimateOpenEnabled') isEnabled: boolean; @Input('treeAnimateOpen') set isOpen(value: boolean) { if (value) { this._show(); if (this.isEnabled && this._isOpen === false) { this._animateOpen(); } } else { this.isEnabled ? this._animateClose() : this._hide(); } this._isOpen = !!value; }; private innerElement: any; constructor( private renderer: Renderer, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {} private _show() { if (this.innerElement) return; // create child view this.innerElement = this.viewContainerRef.createEmbeddedView(this.templateRef).rootNodes[0]; } private _hide() { this.viewContainerRef.clear(); this.innerElement = null; } private _animateOpen() { let delta = this.animateSpeed; let ease = this.animateAcceleration; let maxHeight = 0; // set height to 0 this.renderer.setElementStyle(this.innerElement, 'max-height', `0`); // increase maxHeight until height doesn't change setTimeout(() => { // Allow inner element to create its content const i = setInterval(() => { if (!this._isOpen || !this.innerElement) return clearInterval(i); maxHeight += delta; const roundedMaxHeight = Math.round(maxHeight); this.renderer.setElementStyle(this.innerElement, 'max-height', `${roundedMaxHeight}px`); const height = this.innerElement.getBoundingClientRect().height; // TBD use renderer delta *= ease; ease *= EASE_ACCELERATION; if (height < roundedMaxHeight) { // Make maxHeight auto because animation finished and container might change height later on this.renderer.setElementStyle(this.innerElement, 'max-height', null); clearInterval(i); } }, 17); }); } private _animateClose() { if (!this.innerElement) return; let delta = this.animateSpeed; let ease = this.animateAcceleration; let height = this.innerElement.getBoundingClientRect().height; // TBD use renderer // slowly decrease maxHeight to 0, starting from current height const i = setInterval(() => { if (this._isOpen || !this.innerElement) return clearInterval(i); height -= delta; this.renderer.setElementStyle(this.innerElement, 'max-height', `${height}px`); delta *= ease; ease *= EASE_ACCELERATION; if (height <= 0) { // after animation complete - remove child element this.viewContainerRef.clear(); this.innerElement = null; clearInterval(i); } }, 17); } }
{ "content_hash": "2eb8df4f07174b64f8b7171a19cc890d", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 102, "avg_line_length": 29.442307692307693, "alnum_prop": 0.6548007838014369, "repo_name": "sm-allen/angular-tree-component", "id": "cfc6f36ad3a438b3ba3c356875717749ae24de52", "size": "3062", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/directives/tree-animate-open.directive.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "454" }, { "name": "HTML", "bytes": "1875" }, { "name": "JavaScript", "bytes": "4831" }, { "name": "TypeScript", "bytes": "137214" } ], "symlink_target": "" }
/* Base Application Styles */ body { color: #fff; /*background: #222;*/ background-image: url("../images/background2.jpg") ; background-attachment: fixed; /*background-repeat: no-repeat;*/ /*background-size: cover;*/ }
{ "content_hash": "a7c555dbbc4621d93f454a11c69d4878", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 54, "avg_line_length": 21.181818181818183, "alnum_prop": 0.6523605150214592, "repo_name": "WishTreeGroup/wishtree_web", "id": "54663e1c4a1dbaa23d702b6bc010b6b1544cff0d", "size": "233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/styles/App.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2284" }, { "name": "HTML", "bytes": "831" }, { "name": "JavaScript", "bytes": "34466" } ], "symlink_target": "" }
namespace Kvasir { //SPI0 namespace Spi0Cfg{ ///<SPI Configuration register using Addr = Register::Address<0x40048000,0x00000000,0x00000000,unsigned>; ///SPI enable. enum class EnableVal { disabled=0x00000000, ///<Disabled. The SPI is disabled and the internal state machine and counters are reset. enabled=0x00000001, ///<Enabled. The SPI is enabled for operation. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,EnableVal> enable{}; namespace EnableValC{ constexpr Register::FieldValue<decltype(enable)::Type,EnableVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(enable)::Type,EnableVal::enabled> enabled{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> reserved{}; ///Master mode select. enum class MasterVal { slaveMode=0x00000000, ///<Slave mode. The SPI will operate in slave mode. SCK, MOSI, and the SSEL signals are inputs, MISO is an output. masterMode=0x00000001, ///<Master mode. The SPI will operate in master mode. SCK, MOSI, and the SSEL signals are outputs, MISO is an input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,MasterVal> master{}; namespace MasterValC{ constexpr Register::FieldValue<decltype(master)::Type,MasterVal::slaveMode> slaveMode{}; constexpr Register::FieldValue<decltype(master)::Type,MasterVal::masterMode> masterMode{}; } ///LSB First mode enable. enum class LsbfVal { standard=0x00000000, ///<Standard. Data is transmitted and received in standard MSB first order. reverse=0x00000001, ///<Reverse. Data is transmitted and received in reverse order (LSB first). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,LsbfVal> lsbf{}; namespace LsbfValC{ constexpr Register::FieldValue<decltype(lsbf)::Type,LsbfVal::standard> standard{}; constexpr Register::FieldValue<decltype(lsbf)::Type,LsbfVal::reverse> reverse{}; } ///Clock Phase select. enum class CphaVal { change=0x00000000, ///<Change. The SPI captures serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is changed on the following edge. capture=0x00000001, ///<Capture. The SPI changes serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is captured on the following edge. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,CphaVal> cpha{}; namespace CphaValC{ constexpr Register::FieldValue<decltype(cpha)::Type,CphaVal::change> change{}; constexpr Register::FieldValue<decltype(cpha)::Type,CphaVal::capture> capture{}; } ///Clock Polarity select. enum class CpolVal { low=0x00000000, ///<Low. The rest state of the clock (between frames) is low. high=0x00000001, ///<High. The rest state of the clock (between frames) is high. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,CpolVal> cpol{}; namespace CpolValC{ constexpr Register::FieldValue<decltype(cpol)::Type,CpolVal::low> low{}; constexpr Register::FieldValue<decltype(cpol)::Type,CpolVal::high> high{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> reserved{}; ///Loopback mode enable. Loopback mode applies only to Master mode, and connects transmit and receive data connected together to allow simple software testing. enum class LoopVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,LoopVal> loop{}; namespace LoopValC{ constexpr Register::FieldValue<decltype(loop)::Type,LoopVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(loop)::Type,LoopVal::enabled> enabled{}; } ///SSEL0 Polarity select. enum class Spol0Val { low=0x00000000, ///<Low. The SSEL0 pin is active low. The value in the SSEL0 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL0 is not inverted relative to the pins. high=0x00000001, ///<High. The SSEL0 pin is active high. The value in the SSEL0 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL0 is inverted relative to the pins. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,Spol0Val> spol0{}; namespace Spol0ValC{ constexpr Register::FieldValue<decltype(spol0)::Type,Spol0Val::low> low{}; constexpr Register::FieldValue<decltype(spol0)::Type,Spol0Val::high> high{}; } ///SSEL1 Polarity select. enum class Spol1Val { low=0x00000000, ///<Low. The SSEL1 pin is active low. The value in the SSEL1 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL1 is not inverted relative to the pins. high=0x00000001, ///<High. The SSEL1 pin is active high. The value in the SSEL1 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL1 is inverted relative to the pins. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Spol1Val> spol1{}; namespace Spol1ValC{ constexpr Register::FieldValue<decltype(spol1)::Type,Spol1Val::low> low{}; constexpr Register::FieldValue<decltype(spol1)::Type,Spol1Val::high> high{}; } ///SSEL2 Polarity select. enum class Spol2Val { low=0x00000000, ///<Low. The SSEL2 pin is active low. The value in the SSEL2 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL2 is not inverted relative to the pins. high=0x00000001, ///<High. The SSEL2 pin is active high. The value in the SSEL2 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL2 is inverted relative to the pins. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,Spol2Val> spol2{}; namespace Spol2ValC{ constexpr Register::FieldValue<decltype(spol2)::Type,Spol2Val::low> low{}; constexpr Register::FieldValue<decltype(spol2)::Type,Spol2Val::high> high{}; } ///SSEL3 Polarity select. enum class Spol3Val { low=0x00000000, ///<Low. The SSEL3 pin is active low. The value in the SSEL3 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL3 is not inverted relative to the pins. high=0x00000001, ///<High. The SSEL3 pin is active high. The value in the SSEL3 fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL3 is inverted relative to the pins. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,Spol3Val> spol3{}; namespace Spol3ValC{ constexpr Register::FieldValue<decltype(spol3)::Type,Spol3Val::low> low{}; constexpr Register::FieldValue<decltype(spol3)::Type,Spol3Val::high> high{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,12),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Dly{ ///<SPI Delay register using Addr = Register::Address<0x40048004,0x00000000,0x00000000,unsigned>; ///Controls the amount of time between SSEL assertion and the beginning of a data frame. There is always one SPI clock time between SSEL assertion and the first clock edge. This is not considered part of the pre-delay. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> preDelay{}; ///Controls the amount of time between the end of a data frame and SSEL deassertion. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> postDelay{}; ///Controls the minimum amount of time between adjacent data frames. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> frameDelay{}; ///Controls the minimum amount of time that the SSEL is deasserted between transfers. 0x0 = The minimum time that SSEL is deasserted is 1 SPI clock time. (Zero added time.) 0x1 = The minimum time that SSEL is deasserted is 2 SPI clock times. 0x2 = The minimum time that SSEL is deasserted is 3 SPI clock times. ... 0xF = The minimum time that SSEL is deasserted is 16 SPI clock times. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,12),Register::ReadWriteAccess,unsigned> transferDelay{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Stat{ ///<SPI Status. Some status flags can be cleared by writing a 1 to that bit position using Addr = Register::Address<0x40048008,0x00000000,0x00000000,unsigned>; ///Receiver Ready flag. When 1, indicates that data is available to be read from the receiver buffer. Cleared after a read of the RXDAT register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> rxrdy{}; ///Transmitter Ready flag. When 1, this bit indicates that data may be written to the transmit buffer. Previous data may still be in the process of being transmitted. Cleared when data is written to TXDAT or TXDATCTL until the data is moved to the transmit shift register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> txrdy{}; ///Receiver Overrun interrupt flag. This flag applies only to slave mode (Master = 0). This flag is set when the beginning of a received character is detected while the receiver buffer is still in use. If this occurs, the receiver buffer contents are preserved, and the incoming data is lost. Data received by the SPI should be considered undefined if RxOv is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> rxov{}; ///Transmitter Underrun interrupt flag. This flag applies only to slave mode (Master = 0). In this case, the transmitter must begin sending new data on the next input clock if the transmitter is idle. If that data is not available in the transmitter holding register at that point, there is no data to transmit and the TXUR flag is set. Data transmitted by the SPI should be considered undefined if TXUR is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> txur{}; ///Slave Select Assert. This flag is set whenever any slave select transitions from deasserted to asserted, in both master and slave modes. This allows determining when the SPI transmit/receive functions become busy, and allows waking up the device from reduced power modes when a slave mode access begins. This flag is cleared by software. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ssa{}; ///Slave Select Deassert. This flag is set whenever any asserted slave selects transition to deasserted, in both master and slave modes. This allows determining when the SPI transmit/receive functions become idle. This flag is cleared by software. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> ssd{}; ///Stalled status flag. This indicates whether the SPI is currently in a stall condition. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> stalled{}; ///End Transfer control bit. Software can set this bit to force an end to the current transfer when the transmitter finishes any activity already in progress, as if the EOT flag had been set prior to the last transmission. This capability is included to support cases where it is not known when transmit data is written that it will be the end of a transfer. The bit is cleared when the transmitter becomes Idle as the transfer comes to an end. Forcing an end of transfer in this manner causes any specified FrameDelay and TransferDelay to be inserted. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> endtransfer{}; ///Idle status flag. This bit is 1 whenever the SPI master function is fully idle. This means that the transmit holding register is empty and the transmitter is not in the process of sending data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> idle{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,9),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Intenset{ ///<SPI Interrupt Enable read and Set. A complete value may be read from this register. Writing a 1 to any implemented bit position causes that bit to be set. using Addr = Register::Address<0x4004800c,0x00000000,0x00000000,unsigned>; ///Determines whether an interrupt occurs when receiver data is available. enum class RxrdyenVal { noInterruptWillBe=0x00000000, ///<No interrupt will be generated when receiver data is available. anInterruptWillBe=0x00000001, ///<An interrupt will be generated when receiver data is available in the RXDAT register. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RxrdyenVal> rxrdyen{}; namespace RxrdyenValC{ constexpr Register::FieldValue<decltype(rxrdyen)::Type,RxrdyenVal::noInterruptWillBe> noInterruptWillBe{}; constexpr Register::FieldValue<decltype(rxrdyen)::Type,RxrdyenVal::anInterruptWillBe> anInterruptWillBe{}; } ///Determines whether an interrupt occurs when the transmitter holding register is available. enum class TxrdyenVal { noInterruptWillBe=0x00000000, ///<No interrupt will be generated when the transmitter holding register is available. anInterruptWillBe=0x00000001, ///<An interrupt will be generated when data may be written to TXDAT. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,TxrdyenVal> txrdyen{}; namespace TxrdyenValC{ constexpr Register::FieldValue<decltype(txrdyen)::Type,TxrdyenVal::noInterruptWillBe> noInterruptWillBe{}; constexpr Register::FieldValue<decltype(txrdyen)::Type,TxrdyenVal::anInterruptWillBe> anInterruptWillBe{}; } ///Determines whether an interrupt occurs when a receiver overrun occurs. This happens in slave mode when there is a need for the receiver to move newly received data to the RXDAT register when it is already in use. The interface prevents receiver overrun in Master mode by not allowing a new transmission to begin when a receiver overrun would otherwise occur. enum class RxovenVal { noInterruptWillBe=0x00000000, ///<No interrupt will be generated when a receiver overrun occurs. anInterruptWillBe=0x00000001, ///<An interrupt will be generated if a receiver overrun occurs. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,RxovenVal> rxoven{}; namespace RxovenValC{ constexpr Register::FieldValue<decltype(rxoven)::Type,RxovenVal::noInterruptWillBe> noInterruptWillBe{}; constexpr Register::FieldValue<decltype(rxoven)::Type,RxovenVal::anInterruptWillBe> anInterruptWillBe{}; } ///Determines whether an interrupt occurs when a transmitter underrun occurs. This happens in slave mode when there is a need to transmit data when none is available. enum class TxurenVal { noInterruptWillBe=0x00000000, ///<No interrupt will be generated when the transmitter underruns. anInterruptWillBe=0x00000001, ///<An interrupt will be generated if the transmitter underruns. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,TxurenVal> txuren{}; namespace TxurenValC{ constexpr Register::FieldValue<decltype(txuren)::Type,TxurenVal::noInterruptWillBe> noInterruptWillBe{}; constexpr Register::FieldValue<decltype(txuren)::Type,TxurenVal::anInterruptWillBe> anInterruptWillBe{}; } ///Determines whether an interrupt occurs when the Slave Select is asserted. enum class SsaenVal { noInterruptWillBe=0x00000000, ///<No interrupt will be generated when any Slave Select transitions from deasserted to asserted. anInterruptWillBe=0x00000001, ///<An interrupt will be generated when any Slave Select transitions from deasserted to asserted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,SsaenVal> ssaen{}; namespace SsaenValC{ constexpr Register::FieldValue<decltype(ssaen)::Type,SsaenVal::noInterruptWillBe> noInterruptWillBe{}; constexpr Register::FieldValue<decltype(ssaen)::Type,SsaenVal::anInterruptWillBe> anInterruptWillBe{}; } ///Determines whether an interrupt occurs when the Slave Select is deasserted. enum class SsdenVal { noInterruptWillBe=0x00000000, ///<No interrupt will be generated when all asserted Slave Selects transition to deasserted. anInterruptWillBe=0x00000001, ///<An interrupt will be generated when all asserted Slave Selects transition to deasserted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,SsdenVal> ssden{}; namespace SsdenValC{ constexpr Register::FieldValue<decltype(ssden)::Type,SsdenVal::noInterruptWillBe> noInterruptWillBe{}; constexpr Register::FieldValue<decltype(ssden)::Type,SsdenVal::anInterruptWillBe> anInterruptWillBe{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Intenclr{ ///<SPI Interrupt Enable Clear. Writing a 1 to any implemented bit position causes the corresponding bit in INTENSET to be cleared. using Addr = Register::Address<0x40048010,0x00000000,0x00000000,unsigned>; ///Writing 1 clears the corresponding bits in the INTENSET register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> rxrdyen{}; ///Writing 1 clears the corresponding bits in the INTENSET register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> txrdyen{}; ///Writing 1 clears the corresponding bits in the INTENSET register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> rxoven{}; ///Writing 1 clears the corresponding bits in the INTENSET register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> txuren{}; ///Writing 1 clears the corresponding bits in the INTENSET register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ssaen{}; ///Writing 1 clears the corresponding bits in the INTENSET register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> ssden{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Rxdat{ ///<SPI Receive Data using Addr = Register::Address<0x40048014,0x00000000,0x00000000,unsigned>; ///Receiver Data. This contains the next piece of received data. The number of bits that are used depends on the FLen setting in TXCTL / TXDATCTL. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> rxdat{}; ///Slave Select for receive. This field allows the state of the SSEL0 pin to be saved along with received data. The value will reflect the SSEL0 pin for both master and slave operation. A zero indicates that a slave select is active. The actual polarity of each slave select pin is configured by the related SPOL bit in CFG. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> rxssel0{}; ///Slave Select for receive. This field allows the state of the SSEL1 pin to be saved along with received data. The value will reflect the SSEL1 pin for both master and slave operation. A zero indicates that a slave select is active. The actual polarity of each slave select pin is configured by the related SPOL bit in CFG. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> rxssel1{}; ///Slave Select for receive. This field allows the state of the SSEL2 pin to be saved along with received data. The value will reflect the SSEL2 pin for both master and slave operation. A zero indicates that a slave select is active. The actual polarity of each slave select pin is configured by the related SPOL bit in CFG. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> rxssel2{}; ///Slave Select for receive. This field allows the state of the SSEL3 pin to be saved along with received data. The value will reflect the SSEL3 pin for both master and slave operation. A zero indicates that a slave select is active. The actual polarity of each slave select pin is configured by the related SPOL bit in CFG. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> rxssel3{}; ///Start of Transfer flag. This flag will be 1 if this is the first frame after the SSELs went from deasserted to asserted (i.e., any previous transfer has ended). This information can be used to identify the first piece of data in cases where the frame length is greater than 16 bit. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> sot{}; ///Reserved, the value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,21),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Txdatctl{ ///<SPI Transmit Data with Control using Addr = Register::Address<0x40048018,0x00000000,0x00000000,unsigned>; ///Transmit Data. This field provides from 1 to 16 bits of data to be transmitted. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> txdat{}; ///Transmit Slave Select . This field controls what is output for SSEL0 in master mode. The active state of the SSEL0 function is configured by bits in the CFG register. enum class Txssel0Val { ssel0Asserted=0x00000000, ///<SSEL0 asserted. ssel0NotAsserted=0x00000001, ///<SSEL0 not asserted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,Txssel0Val> txssel0{}; namespace Txssel0ValC{ constexpr Register::FieldValue<decltype(txssel0)::Type,Txssel0Val::ssel0Asserted> ssel0Asserted{}; constexpr Register::FieldValue<decltype(txssel0)::Type,Txssel0Val::ssel0NotAsserted> ssel0NotAsserted{}; } ///Transmit Slave Select . This field controls what is output for SSEL1 in master mode. The active state of the SSEL1 function is configured by bits in the CFG register. enum class Txssel1Val { ssel1Asserted=0x00000000, ///<SSEL1 asserted. ssel1NotAsserted=0x00000001, ///<SSEL1 not asserted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,Txssel1Val> txssel1{}; namespace Txssel1ValC{ constexpr Register::FieldValue<decltype(txssel1)::Type,Txssel1Val::ssel1Asserted> ssel1Asserted{}; constexpr Register::FieldValue<decltype(txssel1)::Type,Txssel1Val::ssel1NotAsserted> ssel1NotAsserted{}; } ///Transmit Slave Select . This field controls what is output for SSEL2 in master mode. The active state of the SSEL2 function is configured by bits in the CFG register. enum class Txssel2Val { ssel2Asserted=0x00000000, ///<SSEL2 asserted. ssel2NotAsserted=0x00000001, ///<SSEL2 not asserted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,Txssel2Val> txssel2{}; namespace Txssel2ValC{ constexpr Register::FieldValue<decltype(txssel2)::Type,Txssel2Val::ssel2Asserted> ssel2Asserted{}; constexpr Register::FieldValue<decltype(txssel2)::Type,Txssel2Val::ssel2NotAsserted> ssel2NotAsserted{}; } ///Transmit Slave Select . This field controls what is output for SSEL3 in master mode. The active state of the SSEL3 function is configured by bits in the CFG register. enum class Txssel3Val { ssel3Asserted=0x00000000, ///<SSEL3 asserted. ssel3NotAsserted=0x00000001, ///<SSEL3 not asserted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,Txssel3Val> txssel3{}; namespace Txssel3ValC{ constexpr Register::FieldValue<decltype(txssel3)::Type,Txssel3Val::ssel3Asserted> ssel3Asserted{}; constexpr Register::FieldValue<decltype(txssel3)::Type,Txssel3Val::ssel3NotAsserted> ssel3NotAsserted{}; } ///End of Transfer. The asserted SSEL will be deasserted at the end of a transfer, and remain so for at least the time specified by the Transfer_delay value in the DLY register. enum class EotVal { sselNotDeasserted=0x00000000, ///<SSEL not deasserted. This piece of data is not treated as the end of a transfer. SSEL will not be deasserted at the end of this data. sselDeasserted=0x00000001, ///<SSEL deasserted. This piece of data is treated as the end of a transfer. SSEL will be deasserted at the end of this piece of data. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,EotVal> eot{}; namespace EotValC{ constexpr Register::FieldValue<decltype(eot)::Type,EotVal::sselNotDeasserted> sselNotDeasserted{}; constexpr Register::FieldValue<decltype(eot)::Type,EotVal::sselDeasserted> sselDeasserted{}; } ///End of Frame. Between frames, a delay may be inserted, as defined by the Frame_delay value in the DLY register. The end of a frame may not be particularly meaningful if the FRAME_DELAY value = 0. This control can be used as part of the support for frame lengths greater than 16 bits. enum class EofVal { dataNotEof=0x00000000, ///<Data not EOF. This piece of data transmitted is not treated as the end of a frame. dataEof=0x00000001, ///<Data EOF. This piece of data is treated as the end of a frame, causing the FRAME_DELAY time to be inserted before subsequent data is transmitted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,EofVal> eof{}; namespace EofValC{ constexpr Register::FieldValue<decltype(eof)::Type,EofVal::dataNotEof> dataNotEof{}; constexpr Register::FieldValue<decltype(eof)::Type,EofVal::dataEof> dataEof{}; } ///Receive Ignore. This allows data to be transmitted using the SPI without the need to read unneeded data from the receiver to simplify the transmit process and can be used with the DMA. enum class RxignoreVal { readReceivedData=0x00000000, ///<Read received data. Received data must be read in order to allow transmission to progress. In slave mode, an overrun error will occur if received data is not read before new data is received. ignoreReceivedData=0x00000001, ///<Ignore received data. Received data is ignored, allowing transmission without reading unneeded received data. No receiver flags are generated. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,RxignoreVal> rxignore{}; namespace RxignoreValC{ constexpr Register::FieldValue<decltype(rxignore)::Type,RxignoreVal::readReceivedData> readReceivedData{}; constexpr Register::FieldValue<decltype(rxignore)::Type,RxignoreVal::ignoreReceivedData> ignoreReceivedData{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> reserved{}; ///Frame Length. Specifies the frame length from 1 to 16 bits. Note that frame lengths greater than 16 bits are supported by implementing multiple sequential frames. Note that if a 1-bit frame is selected, the master function will always insert a delay with a length of one SCK time following the single clock seen on the SCK pin. 0x0 = Data frame is 1 bit in length. 0x1 = Data frame is 2 bits in length. 0x2 = Data frame is 3 bits in length. ... 0xF = Data frame is 16 bits in length. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> flen{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Txdat{ ///<SPI Transmit Data with Control using Addr = Register::Address<0x4004801c,0x00000000,0x00000000,unsigned>; ///Transmit Data. This field provides from 4 to 16 bits of data to be transmitted. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> data{}; ///Reserved. Only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Txctl{ ///<SPI Transmit Control using Addr = Register::Address<0x40048020,0x00000000,0x00000000,unsigned>; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> reserved{}; ///Transmit Slave Select 0. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> txssel0{}; ///Transmit Slave Select 1. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> txssel1{}; ///Transmit Slave Select 2. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> txssel2{}; ///Transmit Slave Select 3. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> txssel3{}; ///End of Transfer. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eot{}; ///End of Frame. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eof{}; ///Receive Ignore. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> rxignore{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> reserved{}; ///Frame Length. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> flen{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Div{ ///<SPI clock Divider using Addr = Register::Address<0x40048024,0x00000000,0x00000000,unsigned>; ///Rate divider value. Specifies how the PCLK for the SPI is divided to produce the SPI clock rate in master mode. DIVVAL is -1 encoded such that the value 0 results in PCLK/1, the value 1 results in PCLK/2, up to the maximum possible divide value of 0xFFFF, which results in PCLK/65536. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> divval{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Spi0Intstat{ ///<SPI Interrupt Status using Addr = Register::Address<0x40048028,0x00000000,0x00000000,unsigned>; ///Receiver Ready flag. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> rxrdy{}; ///Transmitter Ready flag. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> txrdy{}; ///Receiver Overrun interrupt flag. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> rxov{}; ///Transmitter Underrun interrupt flag. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> txur{}; ///Slave Select Assert. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ssa{}; ///Slave Select Deassert. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> ssd{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::ReadWriteAccess,unsigned> reserved{}; } }
{ "content_hash": "e098e50df015eec319f9254bfb896bc8", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 560, "avg_line_length": 95.10416666666667, "alnum_prop": 0.7191675794085433, "repo_name": "porkybrain/Kvasir", "id": "0da62b9d607e4d246d12e7ca5bc6894b32398209", "size": "36566", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Lib/Chip/CM3/NXP/LPC15xx_v0.7/SPI0.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "16510" }, { "name": "C++", "bytes": "763437041" }, { "name": "CMake", "bytes": "1504" }, { "name": "Python", "bytes": "13637" } ], "symlink_target": "" }
<?php /** * Job queue aggregator code. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file * @author Aaron Schulz */ /** * Class to handle tracking information about all queues * * @ingroup JobQueue * @since 1.21 */ abstract class JobQueueAggregator { /** @var JobQueueAggregator */ protected static $instance = null; /** * @param array $params */ protected function __construct( array $params ) { } /** * @throws MWException * @return JobQueueAggregator */ final public static function singleton() { global $wgJobQueueAggregator; if ( !isset( self::$instance ) ) { $class = $wgJobQueueAggregator['class']; $obj = new $class( $wgJobQueueAggregator ); if ( !( $obj instanceof JobQueueAggregator ) ) { throw new MWException( "Class '$class' is not a JobQueueAggregator class." ); } self::$instance = $obj; } return self::$instance; } /** * Destroy the singleton instance * * @return void */ final public static function destroySingleton() { self::$instance = null; } /** * Mark a queue as being empty * * @param string $wiki * @param string $type * @return bool Success */ final public function notifyQueueEmpty( $wiki, $type ) { wfProfileIn( __METHOD__ ); $ok = $this->doNotifyQueueEmpty( $wiki, $type ); wfProfileOut( __METHOD__ ); return $ok; } /** * @see JobQueueAggregator::notifyQueueEmpty() */ abstract protected function doNotifyQueueEmpty( $wiki, $type ); /** * Mark a queue as being non-empty * * @param string $wiki * @param string $type * @return bool Success */ final public function notifyQueueNonEmpty( $wiki, $type ) { wfProfileIn( __METHOD__ ); $ok = $this->doNotifyQueueNonEmpty( $wiki, $type ); wfProfileOut( __METHOD__ ); return $ok; } /** * @see JobQueueAggregator::notifyQueueNonEmpty() */ abstract protected function doNotifyQueueNonEmpty( $wiki, $type ); /** * Get the list of all of the queues with jobs * * @return array (job type => (list of wiki IDs)) */ final public function getAllReadyWikiQueues() { wfProfileIn( __METHOD__ ); $res = $this->doGetAllReadyWikiQueues(); wfProfileOut( __METHOD__ ); return $res; } /** * @see JobQueueAggregator::getAllReadyWikiQueues() */ abstract protected function doGetAllReadyWikiQueues(); /** * Purge all of the aggregator information * * @return bool Success */ final public function purge() { wfProfileIn( __METHOD__ ); $res = $this->doPurge(); wfProfileOut( __METHOD__ ); return $res; } /** * @see JobQueueAggregator::purge() */ abstract protected function doPurge(); /** * Get all databases that have a pending job. * This poll all the queues and is this expensive. * * @return array (job type => (list of wiki IDs)) */ protected function findPendingWikiQueues() { global $wgLocalDatabases; $pendingDBs = array(); // (job type => (db list)) foreach ( $wgLocalDatabases as $db ) { foreach ( JobQueueGroup::singleton( $db )->getQueuesWithJobs() as $type ) { $pendingDBs[$type][] = $db; } } return $pendingDBs; } }
{ "content_hash": "0b42b7f0f61715a5893e7eaddc734a17", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 81, "avg_line_length": 23.62962962962963, "alnum_prop": 0.6650992685475444, "repo_name": "ArcherCraftStore/ArcherVMPeridot", "id": "8600eed903973b380bf4e26732df9cb58b3c8112", "size": "3828", "binary": false, "copies": "63", "ref": "refs/heads/master", "path": "apps/mediawiki/htdocs/includes/jobqueue/aggregator/JobQueueAggregator.php", "mode": "33261", "license": "apache-2.0", "language": [], "symlink_target": "" }
import gtk import viewer reload(viewer) class Application(gtk.Window): def __init__(self, appname, size): gtk.gdk.threads_init() super(Application, self).__init__() self.appname = appname self.size = size self.extensions = {} def parse_framework(self, parent, frm): self.extensions[frm.name] = viewer.get_view[frm.type](frm) for ext in frm.subExtension: self.extensions[ext.name] = viewer.get_view[ext.type](ext) self.extensions[frm.name].attach(self.extensions[ext.name].widget, ext) for view in frm.subFramework: self.parse_framework(self.extensions[frm.name], view) parent.attach(self.extensions[frm.name], frm) def attach(self, widget, extension): self.add(widget) def start(self, main_framework): self.parse_framework(self, main_framework) self.set_size_request(int(self.size[0]), int(self.size[1])) self.set_position(gtk.WIN_POS_CENTER) self.set_title(self.appname) # self.set_icon_from_file(icon) self.connect("destroy", self.destroy) self.show_all() gtk.threads_enter() gtk.main() gtk.threads_leave() def destroy(self, widget): gtk.main_quit()
{ "content_hash": "cf222c062abbf4026495ba6958d0c63e", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 83, "avg_line_length": 32.87179487179487, "alnum_prop": 0.6185647425897036, "repo_name": "2000jedi/WebViewer", "id": "89442522004139b98f5eff66fe987c70fac99a08", "size": "1282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/application.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "11659" } ], "symlink_target": "" }
package main import ( "flag" "fmt" "log" "net/http" "os" ) func main() { httpListenAddr := flag.String("port", "8080", "HTTP Listen address.") flag.Parse() log.Println("Starting server...") // point / at the handler function http.HandleFunc("/", handler) // serve static content from /static http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))) log.Println("Server started. Listening on port " + *httpListenAddr) log.Fatal(http.ListenAndServe(":"+*httpListenAddr, nil)) } const ( html = ` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Croc Hunter</title> <link rel='stylesheet' href='/static/game.css'/> <link rel="icon" type="image/png" href="/static/favicon-16x16.png" sizes="16x16" /> <link rel="icon" type="image/png" href="/static/favicon-32x32.png" sizes="32x32" /> </head> <body> <canvas id="canvasBg" width="800" height="490" ></canvas> <canvas id="canvasEnemy" width="800" height="500" ></canvas> <canvas id="canvasJet" width="800" height="500" ></canvas> <canvas id="canvasHud" width="800" height="500" ></canvas> <script src='/static/game.js'></script> <div class="details"> <strong>Hostname: </strong>%s<br> <strong>Region: </strong>%s<br> <strong>Commit: </strong>%s<br> </div> </body> </html> ` ) func handler(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/healthz" { w.WriteHeader(http.StatusOK) return } hostname, err := os.Hostname() if err != nil { log.Fatalf("could not get hostname: %s", err) } region := os.Getenv("REGION") commit := os.Getenv("GIT_SHA") if region == "" { region = "unknown" } if commit == "" { commit = "not present" } fmt.Fprintf(w, html, hostname, region, commit) }
{ "content_hash": "a021acde26f3165f0444ee0c8afe5fef", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 92, "avg_line_length": 23.818181818181817, "alnum_prop": 0.628680479825518, "repo_name": "gabrtv/croc-hunter", "id": "223e8f3b9fc9dbae9e00f7907799dcfae0b8d8a6", "size": "1896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "croc-hunter.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1896" }, { "name": "Makefile", "bytes": "1066" }, { "name": "Smarty", "bytes": "313" } ], "symlink_target": "" }
package com.ickstream.common.jsonrpc; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Annotation that is used to specify which error code a specific exception should result in. * This annotation is used by {@link StreamJsonRpcService} or one of its implementations to create the appropriate * JSON-RPC response message after an exception has been thrown */ @Retention(RetentionPolicy.RUNTIME) public @interface JsonRpcError { /** * The caller was not authorized to make the specified JSON-RPC request */ public final static int UNAUTHORIZED = -32000; /** * An internal error has occurred inside the service implementing the processing of the JSON-RPC request */ public final static int SERVICE_ERROR = -32001; /** * The request contained invalid JSON data */ public final static int INVALID_JSON = -32700; /** * The request was not valid JSON-RPC request */ public final static int INVALID_REQUEST = -32600; /** * The request method does not exist */ public final static int METHOD_NOT_FOUND = -32601; /** * The specified list of parameters to the request is invalid */ public final static int INVALID_PARAMS = -32602; /** * @return The exception thrown */ Class<? extends Throwable> exception(); /** * The error code to use in JSON-RPC response message * @return Error code */ int code(); /** * The error description to use in JSON-RPC response message * @return Error message */ String message(); /** * The additional data about the error to use in JSON-RPC response message * @return Additional information about the error */ String data() default ""; }
{ "content_hash": "bb4499a1d00823495f8dcab7448d2227", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 114, "avg_line_length": 29.129032258064516, "alnum_prop": 0.6688815060908084, "repo_name": "bluegaspode/ickstream-java-common", "id": "0bb7b4b7e31e6d8ec171e0a3c87db5239305e969", "size": "3384", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jsonrpc/src/main/java/com/ickstream/common/jsonrpc/JsonRpcError.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "1157718" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <title>MoneyBag | {% block title %} {% endblock %}</title> {% load staticfiles %} <!-- Favicon--> <link rel="icon" type="image/png" href="{% static 'favicon.png' %}"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css"> {% load compress %} {% compress css %} <!-- Bootstrap Core Css --> <link href="{% static 'libs/bootstrap/css/bootstrap.css' %}" rel="stylesheet"> <!-- Waves Effect Css --> <link href="{% static 'libs/node-waves/waves.css' %}" rel="stylesheet" /> <!-- Animation Css --> <link href="{% static 'libs/animate-css/animate.css' %}" rel="stylesheet" /> <!-- Custom Css --> <link href="{% static 'css/style.css' %}" rel="stylesheet"> {% endcompress %} </head> <body class="bg-light-blue"> <!-- child page --> {% block childPage %} {% endblock %} <!-- end child page --> {% compress js %} <!-- Jquery Core Js --> <script src="{% static 'libs/jquery/jquery.min.js' %}"></script> <!-- Bootstrap Core Js --> <script src="{% static 'libs/bootstrap/js/bootstrap.js' %}"></script> <!-- Waves Effect Plugin Js --> <script src="{% static 'libs/node-waves/waves.js' %}"></script> <!-- Validation Plugin Js --> <script src="{% static 'libs/jquery-validation/jquery.validate.js' %}"></script> <!-- Custom Js --> <script src="{% static 'js/generic.js' %}"></script> <script src="{% static 'js/gate.js' %}"></script> <!-- child page js --> {% block child_page_js %} {% endblock %} {% endcompress %} </body> </html>
{ "content_hash": "6b4a909d212829c396eabea86aea21fb", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 131, "avg_line_length": 31.983606557377048, "alnum_prop": 0.5786776012301383, "repo_name": "pyprism/Hiren-Tracker", "id": "3a3ab71f34a57379adbb314364d9cd6d2c7788fb", "size": "1951", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "templates/base/frontend_master.html", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "10059" } ], "symlink_target": "" }
datafolder: docker-app datafile: docker_app_pull title: docker app pull --- <!-- This page is automatically generated from Docker's source code. If you want to suggest a change to the text that appears here, open a ticket or pull request in the source repository on GitHub: https://github.com/docker/app --> {% include cli.md datafolder=page.datafolder datafile=page.datafile %}
{ "content_hash": "71cbee24910d208eb63ca8357dc80745", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 78, "avg_line_length": 31.666666666666668, "alnum_prop": 0.7684210526315789, "repo_name": "thaJeztah/docker.github.io", "id": "7a1baa3b884efb172bf37e16532b2b2a343038ee", "size": "384", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "engine/reference/commandline/app_pull.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4032" }, { "name": "Dockerfile", "bytes": "6346" }, { "name": "Go", "bytes": "13662" }, { "name": "HCL", "bytes": "3185" }, { "name": "HTML", "bytes": "99217" }, { "name": "JavaScript", "bytes": "17521" }, { "name": "Makefile", "bytes": "2459" }, { "name": "Ruby", "bytes": "17262" }, { "name": "SCSS", "bytes": "58511" }, { "name": "Shell", "bytes": "1712" }, { "name": "XSLT", "bytes": "3132" } ], "symlink_target": "" }
/*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <qapplication.h> #include <qfont.h> #include <qstring.h> #include <qtextcodec.h> #include <qtranslator.h> #include <qpushbutton.h> #include "clientview.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); ClientView cv( NULL, "Lan Screen Capture" ); QObject::connect( &cv, SIGNAL( quitSignal() ), &a, SLOT( quit() ) ); cv.start(); cv.resize( 400, 400 ); a.setMainWidget( &cv ); cv.show(); return a.exec(); }
{ "content_hash": "bbb1d30e63a42e13243e18a240070586", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 77, "avg_line_length": 30.194444444444443, "alnum_prop": 0.4452621895124195, "repo_name": "clarkli86/udp_multicast_example", "id": "2cafce4afa24bcb205079ddbcdd7b05414cc38f5", "size": "1472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Client/main.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "25954" }, { "name": "Shell", "bytes": "210" } ], "symlink_target": "" }
from .grammar import SchemaGrammar class PostgresSchemaGrammar(SchemaGrammar): _modifiers = ['increment', 'nullable', 'default'] _serials = ['big_integer', 'integer', 'medium_integer', 'small_integer', 'tiny_integer'] marker = '%s' def compile_rename_column(self, blueprint, command, connection): """ Compile a rename column command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :param connection: The connection :type connection: orator.connections.Connection :rtype: list """ table = self.get_table_prefix() + blueprint.get_table() column = self.wrap(command.from_) return 'ALTER TABLE %s RENAME COLUMN %s TO %s'\ % (table, column, self.wrap(command.to)) def compile_table_exists(self): """ Compile the query to determine if a table exists :rtype: str """ return 'SELECT * ' \ 'FROM information_schema.tables ' \ 'WHERE table_name = %(marker)s' \ % {'marker': self.get_marker()} def compile_column_exists(self, table): """ Compile the query to determine the list of columns. """ return 'SELECT column_name ' \ 'FROM information_schema.columns ' \ 'WHERE table_name = \'%s\'' % table def compile_create(self, blueprint, command, _): """ Compile a create table command. """ columns = ', '.join(self._get_columns(blueprint)) return 'CREATE TABLE %s (%s)' % (self.wrap_table(blueprint), columns) def compile_add(self, blueprint, command, _): table = self.wrap_table(blueprint) columns = self.prefix_list('ADD COLUMN', self._get_columns(blueprint)) return 'ALTER TABLE %s %s' % (table, ', '.join(columns)) def compile_primary(self, blueprint, command, _): columns = self.columnize(command.columns) return 'ALTER TABLE %s ADD PRIMARY KEY (%s)'\ % (self.wrap_table(blueprint), columns) def compile_unique(self, blueprint, command, _): columns = self.columnize(command.columns) table = self.wrap_table(blueprint) return 'ALTER TABLE %s ADD CONSTRAINT %s UNIQUE (%s)'\ % (table, command.index, columns) def compile_index(self, blueprint, command, _): columns = self.columnize(command.columns) table = self.wrap_table(blueprint) return 'CREATE INDEX %s ON %s (%s)' % (command.index, table, columns) def compile_drop(self, blueprint, command, _): return 'DROP TABLE %s' % self.wrap_table(blueprint) def compile_drop_if_exists(self, blueprint, command, _): return 'DROP TABLE IF EXISTS %s' % self.wrap_table(blueprint) def compile_drop_column(self, blueprint, command, connection): columns = self.prefix_list( 'DROP COLUMN', self.wrap_list(command.columns)) table = self.wrap_table(blueprint) return 'ALTER TABLE %s %s' % (table, ', '.join(columns)) def compile_drop_primary(self, blueprint, command, _): table = blueprint.get_table() return 'ALTER TABLE %s DROP CONSTRAINT %s_pkey'\ % (self.wrap_table(blueprint), table) def compile_drop_unique(self, blueprint, command, _): table = self.wrap_table(blueprint) return 'ALTER TABLE %s DROP CONSTRAINT %s' % (table, command.index) def compile_drop_index(self, blueprint, command, _): return 'DROP INDEX %s' % command.index def compile_drop_foreign(self, blueprint, command, _): table = self.wrap_table(blueprint) return 'ALTER TABLE %s DROP CONSTRAINT %s' % (table, command.index) def compile_rename(self, blueprint, command, _): from_ = self.wrap_table(blueprint) return 'ALTER TABLE %s RENAME TO %s' % ( from_, self.wrap_table(command.to)) def _type_char(self, column): return "CHAR(%s)" % column.length def _type_string(self, column): return "VARCHAR(%s)" % column.length def _type_text(self, column): return 'TEXT' def _type_medium_text(self, column): return 'TEXT' def _type_long_text(self, column): return 'TEXT' def _type_integer(self, column): return 'SERIAL' if column.auto_increment else 'INTEGER' def _type_big_integer(self, column): return 'BIGSERIAL' if column.auto_increment else 'BIGINT' def _type_medium_integer(self, column): return 'SERIAL' if column.auto_increment else 'INTEGER' def _type_tiny_integer(self, column): return 'SMALLSERIAL' if column.auto_increment else 'SMALLINT' def _type_small_integer(self, column): return 'SMALLSERIAL' if column.auto_increment else 'SMALLINT' def _type_float(self, column): return self._type_double(column) def _type_double(self, column): return 'DOUBLE PRECISION' def _type_decimal(self, column): return 'DECIMAL(%s, %s)' % (column.total, column.places) def _type_boolean(self, column): return 'BOOLEAN' def _type_enum(self, column): allowed = list(map(lambda a: "'%s'" % a, column.allowed)) return 'VARCHAR(255) CHECK ("%s" IN (%s))' % ( column.name, ', '.join(allowed)) def _type_json(self, column): return 'JSON' def _type_date(self, column): return 'DATE' def _type_datetime(self, column): return 'TIMESTAMP(6) WITHOUT TIME ZONE' def _type_time(self, column): return 'TIME(6) WITHOUT TIME ZONE' def _type_timestamp(self, column): if column.use_current: return ('TIMESTAMP(6) WITHOUT TIME ZONE ' 'DEFAULT CURRENT_TIMESTAMP(6)') return 'TIMESTAMP(6) WITHOUT TIME ZONE' def _type_binary(self, column): return 'BYTEA' def _modify_nullable(self, blueprint, column): if column.get('nullable'): return ' NULL' return ' NOT NULL' def _modify_default(self, blueprint, column): if column.get('default') is not None: return ' DEFAULT %s' % self._get_default_value(column.default) return '' def _modify_increment(self, blueprint, column): if column.type in self._serials and column.auto_increment: return ' PRIMARY KEY' return '' def _get_dbal_column_type(self, type_): """ Get the dbal column type. :param type_: The fluent type :type type_: str :rtype: str """ type_ = type_.lower() if type_ == 'enum': return 'string' return super()._get_dbal_column_type(type_) def _list_tables(self): sql = """\ SELECT c.relname AS "table_name" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r','') AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND n.nspname !~ '^pg_toast' AND pg_catalog.pg_table_is_visible(c.oid) """ return sql def _list_columns(self, table_name): sql = """\ SELECT column_name AS "name", data_type AS "ttype", COALESCE(numeric_precision, character_maximum_length) \ AS "precision", is_nullable AS "nullable", column_default AS "default" FROM information_schema.columns WHERE table_name = '{}' """.format(table_name) return sql def _list_indexes(self, table_name): sql = """\ SELECT indexname AS "name", indexdef FROM pg_indexes WHERE tablename = '{}' """.format(table_name) return sql def _show_index(self, index): sql = """\ select a.attname as column_name from pg_class t, pg_class i, pg_index ix, pg_attribute a where t.oid = ix.indrelid and i.oid = ix.indexrelid and a.attrelid = t.oid and a.attnum = ANY(ix.indkey) and t.relkind = 'r' and i.relname = '{}' order by t.relname, i.relname; """.format(index) return sql def _list_foreign_keys(self, table_name): sql = """\ SELECT t2.oid::regclass::text AS "to_table", a1.attname AS "column", a2.attname AS "primary_key", c.conname AS "name", c.confupdtype AS "on_update", c.confdeltype AS "on_delete" FROM pg_constraint c JOIN pg_class t1 ON c.conrelid = t1.oid JOIN pg_class t2 ON c.confrelid = t2.oid JOIN pg_attribute a1 ON a1.attnum = c.conkey[1] AND a1.attrelid = t1.oid JOIN pg_attribute a2 ON a2.attnum = c.confkey[1] AND a2.attrelid = t2.oid JOIN pg_namespace t3 ON c.connamespace = t3.oid WHERE c.contype = 'f' AND t1.relname = '{}' ORDER BY c.conname """.format(table_name) return sql
{ "content_hash": "3c04b56082c05ec09216a30236291fc0", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 78, "avg_line_length": 30.838709677419356, "alnum_prop": 0.5573221757322175, "repo_name": "Hanaasagi/sorator", "id": "da873fd969d26b48062d6330d499fa5b2c685ad6", "size": "9585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "orator/schema/grammars/postgres_grammar.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "2023" }, { "name": "Python", "bytes": "1070898" } ], "symlink_target": "" }
package org.visualeagle.gui.remotewindow.fileprovider; import com.asyncsockets.ListenableFutureTask; import java.util.List; /** * @author sad */ public abstract class AbstractFileProvider { private RFile currentFolder; public RFile getCurrentFolder() { return currentFolder; } public void setCurrentFolder(RFile currentFolder) { this.currentFolder = currentFolder; } public abstract String separator(); public abstract ListenableFutureTask<List<RFile>> listFiles(RFile folder); public abstract ListenableFutureTask<List<RFile>> listRoots(); public abstract ListenableFutureTask<Boolean> removeFile(RFile folder); public abstract ListenableFutureTask<Boolean> renameFile(RFile file, String newName); public abstract ListenableFutureTask<Boolean> createFolder(RFile currentFolder, String newFolderName); public abstract ListenableFutureTask<Boolean> exists(RFile file); /** Return handle to file */ public abstract ListenableFutureTask<Long> openFileForReading(RFile file); /** Return handle to file */ public abstract ListenableFutureTask<Long> openFileForWriting(RFile file, boolean append); public abstract ListenableFutureTask<Boolean> writeToFile(long handle, byte[]buffer,int count); /** Tries to fully fill buffer from file opened with @handle<br> returns number of actually read bytes */ public abstract ListenableFutureTask<Integer> readFromFile(long handle, byte[]buffer); public abstract ListenableFutureTask<Boolean> close(long handle); }
{ "content_hash": "dd006a58aec09a679cb5f6a4ad3d8d11", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 106, "avg_line_length": 30.39622641509434, "alnum_prop": 0.7405338299193048, "repo_name": "Otaka/KOSBuild", "id": "c4a9eb6e248aeb5ed47d80a085c8cd94acd0d2da", "size": "1611", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VisualEagle/src/main/java/org/visualeagle/gui/remotewindow/fileprovider/AbstractFileProvider.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "434348" } ], "symlink_target": "" }
package info.joriki.pdf; public interface PairHandler { boolean handle (PDFObject objectA,PDFObject objectB); }
{ "content_hash": "a688c8d29827006002c6d67af341be37", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 55, "avg_line_length": 16.714285714285715, "alnum_prop": 0.7777777777777778, "repo_name": "emistoolbox/emistoolbox", "id": "673f3b807828ef5303b64ffbded6d47fdb4611e9", "size": "210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libs/joriki/src/info/joriki/pdf/PairHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "852" }, { "name": "C#", "bytes": "111691" }, { "name": "CSS", "bytes": "74403" }, { "name": "HTML", "bytes": "34400" }, { "name": "Java", "bytes": "3825395" }, { "name": "JavaScript", "bytes": "40730" }, { "name": "Perl", "bytes": "3782" } ], "symlink_target": "" }
@class AMAvatar; @class AMContentTypeEnum; @class AMDialog; @class AMMessageStateEnum; @class AMPeer; @interface AMDialogBuilder : NSObject #pragma mark Public - (instancetype)init; - (instancetype)initWithAMDialog:(AMDialog *)dialog; - (AMDialog *)createDialog; - (AMDialogBuilder *)setDialogAvatarWithAMAvatar:(AMAvatar *)avatar; - (AMDialogBuilder *)setDialogTitleWithNSString:(NSString *)dialogTitle; - (AMDialogBuilder *)setMessageTypeWithAMContentTypeEnum:(AMContentTypeEnum *)messageType; - (AMDialogBuilder *)setPeerWithAMPeer:(AMPeer *)peer; - (AMDialogBuilder *)setRelatedUidWithInt:(jint)relatedUid; - (AMDialogBuilder *)setRidWithLong:(jlong)rid; - (AMDialogBuilder *)setSenderIdWithInt:(jint)senderId; - (AMDialogBuilder *)setSortKeyWithLong:(jlong)sortKey; - (AMDialogBuilder *)setStatusWithAMMessageStateEnum:(AMMessageStateEnum *)status; - (AMDialogBuilder *)setTextWithNSString:(NSString *)text; - (AMDialogBuilder *)setTimeWithLong:(jlong)time; - (AMDialogBuilder *)setUnreadCountWithInt:(jint)unreadCount; @end J2OBJC_EMPTY_STATIC_INIT(AMDialogBuilder) FOUNDATION_EXPORT void AMDialogBuilder_init(AMDialogBuilder *self); FOUNDATION_EXPORT AMDialogBuilder *new_AMDialogBuilder_init() NS_RETURNS_RETAINED; FOUNDATION_EXPORT void AMDialogBuilder_initWithAMDialog_(AMDialogBuilder *self, AMDialog *dialog); FOUNDATION_EXPORT AMDialogBuilder *new_AMDialogBuilder_initWithAMDialog_(AMDialog *dialog) NS_RETURNS_RETAINED; J2OBJC_TYPE_LITERAL_HEADER(AMDialogBuilder) typedef AMDialogBuilder ImActorModelEntityDialogBuilder; #endif // _AMDialogBuilder_H_
{ "content_hash": "f75c29b430769edd8b7c9c47192e07fb", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 111, "avg_line_length": 27.912280701754387, "alnum_prop": 0.8076681332495286, "repo_name": "shaunstanislaus/actor-platform", "id": "e39a0accdc5954aa6fc9e97a8fa5f40ff95d1ffe", "size": "1857", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "actor-apps/core-async-cocoa/src/im/actor/model/entity/DialogBuilder.h", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46672" }, { "name": "HTML", "bytes": "2608" }, { "name": "Java", "bytes": "4085955" }, { "name": "JavaScript", "bytes": "134940" }, { "name": "Objective-C", "bytes": "6115908" }, { "name": "Ruby", "bytes": "2670" }, { "name": "Scala", "bytes": "898518" }, { "name": "Shell", "bytes": "9522" }, { "name": "Swift", "bytes": "503432" } ], "symlink_target": "" }
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt package openblocks.yacodeblocks; import com.google.appinventor.components.common.YaVersion; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URL; import java.net.URLConnection; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.Random; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JDialog; import org.json.*; import org.apache.commons.io.*; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; /** * Class for communication with a Phone/Emulator containing an embedded Yail REPL. * Handles the lower levels of communication with a device. * * @author markf@google.com (Mark Friedman) */ public class DeviceReplCommController implements AndroidController.DeviceConnectionListener { public interface PostProcessor { void postProcess(String message); void onFailure(Throwable e); void onDisconnect(String serialNumber); void onConnect(String serialNumber); } private static final boolean DEBUG = true; private String host; private int port; private Socket socket; private OutputStream out; private InputStream in; private ReadWriteThread inputThread; private AndroidController androidController; private PostProcessor postProcessor; private PhoneCommManager phoneManager; private volatile boolean connectionHappy = false; // is there a device connected and working private volatile int devicesPluggedIn = 0; private volatile boolean stopWireless = false; // set to true to break out of the rendezvous server read loop prematurely private final String rendezvousUrl = "http://rendezvous.appinventor.mit.edu/rendezvous/"; // This should be parameterized (will be!) public DeviceReplCommController(String host, int port, AndroidController androidController, PostProcessor postProcessor) { this.host = host; this.port = port; this.androidController = androidController; this.postProcessor = postProcessor; } private void doWrite(String message) throws IOException { out.write(message.getBytes("UTF-8")); out.write('\n'); if (DEBUG) { System.out.println(String.format("Sent '%s\n", message)); } } /** * Send initial string to the REPL controller. If the REPL controller * isn't actually connected, will take a series of escalating steps to * reconnect it. * @param message the string to send to the REPL controller * @param mustRestartApp if true, will restart the app before doing the send * @throws IOException, ExternalStorageException */ public void sendInitial(String message, boolean mustRestartApp) throws IOException, ExternalStorageException { String selectedDevice = androidController.getSelectedDevice(); if (DEBUG) { System.out.println("ReplController sending " + message); System.out.println("**** devicesPluggedIn: " + devicesPluggedIn + " selectedDevice: " + selectedDevice + " connectionHappy: " + connectionHappy); } // TODO(kerr): deal with threading with respect to devices plugged in? // if think is connected, try a write. // if that fails, start debugging. String failedMessage = "Failed to restart communication for unknown reason."; if (connectionHappy && !mustRestartApp) { // we _think_ that it is connected... try { doWrite(message); connectionHappy = true; return; } catch (IOException e) { if (DEBUG) { System.out.println("**** Exception while writing: " + e.getMessage()); System.out.println(" ... ignoring and trying to reconnect."); } } } connectionHappy = false; if (selectedDevice != null) { // Only check if there is a selected device /* * Always reinstall app when there is a problem. The new "tight security" * app will only ever accept one socket connection and disables itself * as soon as it starts, so it cannot be restarted. */ boolean restarted = false; // If true, failure was probably at the socket level try { if (DEBUG) { System.out.println("**** Trying to do restart from reinstalling the application...."); } if (!selectedDevice.equals("WiFi")) { // Cannot restart WiFi app, but it is likely just fine. doReinstallApplication(); doRestartApplication(); } restarted = true; establishSocketLevelCommunication(); doWrite(message); connectionHappy = true; return; } catch (IOException e) { if (DEBUG) { System.out.println("**** Reinstall was not enough: " + e.getMessage()); } if (restarted) { androidController.androidRestartBridge(); // try exponential back-off for opening the socket int sleepTime = 3000; // start with 3 seconds for (int i = 1; i <=4 ; i++) { // 4 tries at most = 45 sec. total try { if (DEBUG) { System.out.println(" ... waiting " + sleepTime/1000 + " seconds and then trying again to establish connection"); } Thread.sleep(sleepTime); establishSocketLevelCommunication(); doWrite(message); connectionHappy = true; return; } catch (Exception e2) { if (i == 4) { if (DEBUG) { System.out.println("**** giving up on connecting to phone: " + e2.getMessage()); } } else { if (DEBUG) { System.out.println("Failed to connect: " + e2.getMessage()); } sleepTime = sleepTime * 2; // double and try again } } } } failedMessage = e.getMessage(); } } else { if (DEBUG) { System.out.println("***** No device selected"); } throw new IOException("It appears that no device has been selected"); } connectionHappy = false; // there was nothing plugged in, or somehow we got unplugged by now if (devicesPluggedIn == 0) { String errorMessage = "App Inventor cannot find any connected devices.\n"; throw new IOException(errorMessage); } if (DEBUG) { System.out.println("**** devicesPluggedIn: " + devicesPluggedIn + " selectedDevice: " + selectedDevice + " connectionHappy: " + connectionHappy); } throw new IOException(failedMessage); } /** * Send a string to the REPL controller. Expects that the controller is * already happily running. * @param message the string to send to the REPL controller * @throws IOException */ public void send(String message) throws IOException { if (DEBUG) { System.out.println("ReplController sending " + message); } // TODO(kerr): how deal with threading with respect to devices plugged in? if (connectionHappy) { // we _think_ that it is connected... doWrite(message); } else { throw new IOException("Connection is not happy and needs restart."); } } private void establishSocketLevelCommunication() throws IOException { // Unfortunately, need to reforward the port for every new socket connection. reset(); if (! forwardAndroidPort()) { throw new IOException("Could not forward TCP port."); } if (DEBUG) { System.out.println("trying to establish communication"); } try { setupSocket(); } catch (IOException e) { if (DEBUG) { System.out.println("Failed in setupSocket: " + e.getMessage()); } throw e; } } private void setupSocket() throws IOException { if (inputThread != null) { inputThread.stopRunning(); } socket = new Socket(host, port); // Note that this call does not fail even if there's nothing running on // the other end. Also, there's no problem getting the streams. Sigh. out = socket.getOutputStream(); in = socket.getInputStream(); int ch = in.read(); // We'll put it back before the thread tries to read it. if (ch < 0) { throw new IOException("Input stream closed before found anything on it."); } inputThread = new ReadWriteThread(ch); inputThread.start(); } private boolean forwardAndroidPort() { boolean result = androidController.androidForwardTcpPort( PhoneCommManager.REPL_COMMUNICATION_PORT, PhoneCommManager.REPL_COMMUNICATION_PORT); if (DEBUG) { if (result) { System.out.println("ADB forward command was successfully run"); } else { System.out.println("ADB forward command failed to run"); } } return result; } /** * This function can take as long as 10 seconds since it sleeps (in .1 * second increments) while waiting for the application to restart. * Usually does not take more than two or three seconds, sometimes much * less. */ private void doRestartApplication() throws IOException { try { androidController.androidKillStarterApplication(); androidController.androidStartStarterApplication(); int attempts = 0; while (attempts < 10) { // Unfortunately, the test if the application is running is not as // good as a test if it is actually responding. Thread.sleep(1000); if (androidController.androidIsStarterApplicationRunning()) { return; } attempts++; } // Sometimes we can't tell if it's running but it seems to be doing // so. We'll catch the error later if it really didn't start. if (DEBUG) { System.out.println("Allegedly failed to start application - waited too long."); } } catch (AndroidControllerException e) { throw new IOException("Failed to start application: " + e.getMessage()); } catch (java.lang.InterruptedException e) { throw new IOException("Failed to start application: " + e.getMessage()); } } private void doReinstallApplication() throws IOException, ExternalStorageException { if (DEBUG) { System.out.println("Trying to sync and install on the device..."); } try { androidController.androidSyncAndInstallStarterApplication(); } catch (AndroidControllerException e) { throw new IOException(e.getMessage()); } } public void reset() { try { if (inputThread != null) { inputThread.stopRunning(); } if (socket != null) { socket.close(); socket = null; } } catch (IOException e) { if (DEBUG) { System.out.println("Problem closing REPL socket"); } } } public void deviceConnected(String serialNumber) { devicesPluggedIn++; if (DEBUG) { System.out.println("Device connected: " + devicesPluggedIn + " devices plugged in."); } postProcessor.onConnect(serialNumber); } public void deviceDisconnected(String serialNumber) { devicesPluggedIn--; if (DEBUG) { System.out.println("Device disconnected: " + devicesPluggedIn + " devices plugged in."); } if (devicesPluggedIn < 0) { if (DEBUG) { System.out.println("XXXXXX We're confused about number of connected devices. Yikes!"); } devicesPluggedIn = 0; } else if (serialNumber.equals(androidController.getSelectedDevice())) { // If the user unplugged the device we were connected to, we care. Otherwise not. connectionHappy = false; } postProcessor.onDisconnect(serialNumber); } public String getSelectedDevice() { return androidController.getSelectedDevice(); } public boolean selectDevice(String device, String ipAddress) { try { if (device.equals("WiFi")) { this.host = ipAddress; androidController.selectDevice(device, ipAddress); phoneManager.replWifiStart(); } else { this.host = "127.0.0.1"; // The IP address used for USB connected phones androidController.selectDevice(device); } return true; } catch (AndroidControllerException e) { return false; } } public boolean selectDevice(String device) { try { if (device.equals("WiFi")) { rendevzousIpAddress(); // This runs in another thread which calls selectDevice(device, ipaddress) when ready return false; } else { androidController.selectDevice(device); } return true; } catch (AndroidControllerException e) { return false; } } class ReadWriteThread extends Thread { private volatile boolean shouldRun = true; private volatile int initialCh = -1; ReadWriteThread(int ch) { super(); initialCh = ch; } public void stopRunning() { this.shouldRun = false; } @Override public void run () { try { byte[] buffer = new byte[1024]; while (shouldRun) { int ch; if (initialCh != -1) { ch = initialCh; initialCh = -1; } else { ch = in.read(); } if (ch < 0) break; // ??? FIXME buffer[0] = (byte) ch; int avail = in.available(); if (avail > 0) { if (avail > buffer.length - 1) avail = buffer.length - 1; avail = in.read(buffer, 1, avail); } String received = new String(buffer, 0, avail + 1, "UTF-8"); if (postProcessor != null) { postProcessor.postProcess(received); } } } catch (java.io.IOException ex) { if (shouldRun) { // exception wasn't due to us being reset if (DEBUG) { System.out.println("ReadWriteThread got exception " + ex); ex.printStackTrace(); } postProcessor.onFailure(ex); } } } } private void rendevzousIpAddress() { // Generate the random 6 digit code and the QRCode that contains it. String AB = "abcdefghijklmnopqrstuvwxyz"; Random rnd = new Random(); StringBuilder sb = new StringBuilder(6); for(int i=0; i<6; i++) sb.append(AB.charAt(rnd.nextInt(AB.length()))); final String code = sb.toString(); final ImageIcon qrcode = generateQRCode(code); stopWireless = false; // Re-initialize in case it was set in a previous attempt final JDialog displayedCode = FeedbackReporter.showWirelessCodeDialog(code, qrcode, new Runnable() { public void run() { setStopWireless(); }}); Thread t = new Thread(new Runnable() { public void run() { try { // Put up the wireless dialog box Thread.sleep(4000); // Sleep 4 seconds, time to give the user a chance to start the Companion App String jsonString = fetchJsonString(code); int count = 0; while (jsonString == null) { if (count++ > 56) { // This limits this loop to about a minute (4 seconds wait above and 56 seconds round the loop) javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { displayedCode.setVisible(false); // Take down pending message FeedbackReporter.showErrorMessage("We failed to find your phone, please try again.", "Try Again"); }}); return; } if (stopWireless) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { displayedCode.setVisible(false); // Take down pending message }}); return; } Thread.sleep(1000); // Pause a second (so the total wait time for the first loop is really 5 seconds subsequent loops are 1 second if (DEBUG) System.out.println("DeviceReplCommController (WiFi Connect) looping count = " + count); jsonString = fetchJsonString(code); } JSONObject jsonObject = new JSONObject(jsonString); final String ipAddress = (String) jsonObject.get("ipaddr"); if (DEBUG) System.out.println("Got ipaddr = " + ipAddress); // We have the IP address, we now send our version to the phone which // starts the phone TelnetRepl listening. If this version doesn't match // The phone will display an error and not listen. We don't need to know // the result because if the phone fails to listen it will reject the // connection that is attempted when we call selectDevice() String curl = "http://" + ipAddress + ":8000/_version?version=" + YaVersion.YOUNG_ANDROID_VERSION; if (DEBUG) System.out.println("Connecting to: " + curl); URL url = new URL(curl); URLConnection con = null; try { con = url.openConnection(); con.getInputStream().close(); // We don't care about the return value } catch (FileNotFoundException fnf) { System.out.println("Exception setting version, ignoring for now."); fnf.printStackTrace(System.out); // Let's not hide it though! } javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { displayedCode.setVisible(false); selectDevice("WiFi", ipAddress); // This is run on the UI thread }}); } catch(Exception e) { System.out.println("It did not work." + e.toString());//return e.printStackTrace(System.out); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { if (displayedCode != null) displayedCode.setVisible(false); }}); }}}); t.start(); } private ImageIcon generateQRCode(String code) { Charset charset = Charset.forName("ISO-8859-1"); CharsetEncoder encoder = charset.newEncoder(); byte[] b = null; try { // Convert a string to ISO-8859-1 bytes in a ByteBuffer ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(code)); b = bbuf.array(); } catch (CharacterCodingException e) { System.out.println(e.getMessage()); } String data = null; try { data = new String(b, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } // get a byte matrix for the data BitMatrix matrix = null; int h = 200; int w = 200; com.google.zxing.Writer writer = new QRCodeWriter(); try { matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, w, h); ImageIcon qrcode = new ImageIcon(); qrcode.setImage(MatrixToImageWriter.toBufferedImage(matrix)); return qrcode; } catch (Exception e) { System.out.println(e.getMessage()); } return null; } private String fetchJsonString(String code) throws IOException { URL url = new URL(rendezvousUrl + code); // URLConnection con = url.openConnection(); InputStream in = con.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); return (reader.readLine()); } private void setStopWireless() { stopWireless = true; } public void setPhoneManager(PhoneCommManager phoneManager) { this.phoneManager = phoneManager; } }
{ "content_hash": "d742af365332e3d491ca2a2a4fa9570b", "timestamp": "", "source": "github", "line_count": 593, "max_line_length": 144, "avg_line_length": 34.827993254637434, "alnum_prop": 0.6207814845300925, "repo_name": "cjessica/aifoo", "id": "6425eb73ae49e855a7be27863d46652c272bb034", "size": "20653", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "appinventor/blockslib/src/openblocks/yacodeblocks/DeviceReplCommController.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26318" }, { "name": "Java", "bytes": "5282597" }, { "name": "JavaScript", "bytes": "8199" }, { "name": "Python", "bytes": "8421" }, { "name": "Scheme", "bytes": "137314" }, { "name": "Shell", "bytes": "2340" }, { "name": "Standard ML", "bytes": "1373833" } ], "symlink_target": "" }
""" Copyright 2017 Alexander Minyushkin 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. """ from gutenberg.acquire import load_etext from gutenberg.cleanup import strip_headers from functools import reduce if __name__ == '__main__': author = "Sheckley_Robert" book_id = [33854, 9055, 29446, 29458, 29876, 32040, 29487, 29445, 32346, 29525, 51833, 32041, 50844, 51768, 20919, 51545, 29509, 29548, 29579 ] author = "Best_books" book_id = [1342,219,844,84,2542,5200,76,98,11,345,2701,2591,74,6130,1080,43,1400,174,158,1232,1661] all_texts = reduce((lambda x, y: x + y), [ strip_headers(load_etext(id)).strip() for id in book_id]) f = open("../data/pg/" + author + ".txt", 'w') f.write(all_texts) f.close()
{ "content_hash": "b555fe93fa882acdd225420680611cab", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 147, "avg_line_length": 33.916666666666664, "alnum_prop": 0.7125307125307125, "repo_name": "Alexander-Minyushkin/aistreamer", "id": "600272475a2d0bd50d3af91238f9e613bb19dd68", "size": "1221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "worker/text_from_gutenberg.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "728" }, { "name": "HTML", "bytes": "5501" }, { "name": "Python", "bytes": "60578" }, { "name": "Shell", "bytes": "2289" } ], "symlink_target": "" }
<!-- HTML header for doxygen 1.8.10--> <!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.10"/> <title>Wanzyee Studio: QuaternionConverter</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="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </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" /> <link href="stylesheet.css" rel="stylesheet" type="text/css"/> <link href="https://wanzyee.github.io/UnityLab/Resource/Asset/logo_pink_16.png" rel="shortcut icon"> </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 id="projectlogo"> <a href="annotated.html"><img alt="Logo" src="logo_pink_48.png"/></a> </td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Wanzyee Studio </div> </td> <td> <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> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('class_wanzyee_studio_1_1_json_1_1_quaternion_converter.html','');}); </script> <div id="doc-content"> <!-- 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 class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pro-methods">Protected Member Functions</a> &#124; <a href="class_wanzyee_studio_1_1_json_1_1_quaternion_converter-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">QuaternionConverter<div class="ingroups"><a class="el" href="group___released.html">Released Packages</a> &raquo; <a class="el" href="group___json_net_converters.html">Json.NET Converters</a></div></div> </div> </div><!--header--> <div class="contents"> <p>Custom <code>Newtonsoft.Json.JsonConverter</code> for <code>UnityEngine.Quaternion</code>. <a href="class_wanzyee_studio_1_1_json_1_1_quaternion_converter.html#details">More...</a></p> <p>Inherits <a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html">PartialConverter&lt; Quaternion &gt;</a>.</p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a8cf86720a5481c744a0a551d1541f5d8"><td class="memItemLeft" align="right" valign="top">override bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html#a8cf86720a5481c744a0a551d1541f5d8">CanConvert</a> (Type objectType)</td></tr> <tr class="memdesc:a8cf86720a5481c744a0a551d1541f5d8"><td class="mdescLeft">&#160;</td><td class="mdescRight">Determine if the object type is <code>T</code>. <a href="#a8cf86720a5481c744a0a551d1541f5d8">More...</a><br /></td></tr> <tr class="separator:a8cf86720a5481c744a0a551d1541f5d8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a63d4f63128781acfa8229a12763b5440"><td class="memItemLeft" align="right" valign="top">override object&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html#a63d4f63128781acfa8229a12763b5440">ReadJson</a> (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)</td></tr> <tr class="memdesc:a63d4f63128781acfa8229a12763b5440"><td class="mdescLeft">&#160;</td><td class="mdescRight">Read the specified properties to the object. <a href="#a63d4f63128781acfa8229a12763b5440">More...</a><br /></td></tr> <tr class="separator:a63d4f63128781acfa8229a12763b5440"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a05ac0c517b46f5f9bf33cb826ca8e465"><td class="memItemLeft" align="right" valign="top">override void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html#a05ac0c517b46f5f9bf33cb826ca8e465">WriteJson</a> (JsonWriter writer, object value, JsonSerializer serializer)</td></tr> <tr class="memdesc:a05ac0c517b46f5f9bf33cb826ca8e465"><td class="mdescLeft">&#160;</td><td class="mdescRight">Write the specified properties of the object. <a href="#a05ac0c517b46f5f9bf33cb826ca8e465">More...</a><br /></td></tr> <tr class="separator:a05ac0c517b46f5f9bf33cb826ca8e465"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a> Protected Member Functions</h2></td></tr> <tr class="memitem:a61eca50fcecd37b6ced0c9f9a8b0672c"><td class="memItemLeft" align="right" valign="top">override string[]&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_wanzyee_studio_1_1_json_1_1_quaternion_converter.html#a61eca50fcecd37b6ced0c9f9a8b0672c">GetPropertyNames</a> ()</td></tr> <tr class="memdesc:a61eca50fcecd37b6ced0c9f9a8b0672c"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the property names include <code>x</code>, <code>y</code>, <code>z</code>, <code>w</code>. <a href="#a61eca50fcecd37b6ced0c9f9a8b0672c">More...</a><br /></td></tr> <tr class="separator:a61eca50fcecd37b6ced0c9f9a8b0672c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a07606f5a91b11a5fe26eb9fbcbfbbd7d"><td class="memItemLeft" align="right" valign="top">virtual T&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html#a07606f5a91b11a5fe26eb9fbcbfbbd7d">CreateInstance</a> ()</td></tr> <tr class="memdesc:a07606f5a91b11a5fe26eb9fbcbfbbd7d"><td class="mdescLeft">&#160;</td><td class="mdescRight">Create the instance for <code><a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html#a63d4f63128781acfa8229a12763b5440" title="Read the specified properties to the object. ">ReadJson()</a></code> to populate. <a href="#a07606f5a91b11a5fe26eb9fbcbfbbd7d">More...</a><br /></td></tr> <tr class="separator:a07606f5a91b11a5fe26eb9fbcbfbbd7d"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Custom <code>Newtonsoft.Json.JsonConverter</code> for <code>UnityEngine.Quaternion</code>. </p> </div><h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="a61eca50fcecd37b6ced0c9f9a8b0672c"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">override string [] GetPropertyNames </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Get the property names include <code>x</code>, <code>y</code>, <code>z</code>, <code>w</code>. </p> <dl class="section return"><dt>Returns</dt><dd>The property names.</dd></dl> <p>Implements <a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html#a6ecff156facbd3639f7277e9e3d5fc74">PartialConverter&lt; Quaternion &gt;</a>.</p> </div> </div> <a class="anchor" id="a07606f5a91b11a5fe26eb9fbcbfbbd7d"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual T CreateInstance </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span><span class="mlabel">virtual</span><span class="mlabel">inherited</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Create the instance for <code><a class="el" href="class_wanzyee_studio_1_1_json_1_1_partial_converter.html#a63d4f63128781acfa8229a12763b5440" title="Read the specified properties to the object. ">ReadJson()</a></code> to populate. </p> <dl class="section return"><dt>Returns</dt><dd>The instance.</dd></dl> </div> </div> <a class="anchor" id="a8cf86720a5481c744a0a551d1541f5d8"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">override bool CanConvert </td> <td>(</td> <td class="paramtype">Type&#160;</td> <td class="paramname"><em>objectType</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inherited</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Determine if the object type is <code>T</code>. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">objectType</td><td>Type of the object.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd><code>true</code> if this can convert the specified type; otherwise, <code>false</code>.</dd></dl> </div> </div> <a class="anchor" id="a63d4f63128781acfa8229a12763b5440"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">override object ReadJson </td> <td>(</td> <td class="paramtype">JsonReader&#160;</td> <td class="paramname"><em>reader</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">Type&#160;</td> <td class="paramname"><em>objectType</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">object&#160;</td> <td class="paramname"><em>existingValue</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">JsonSerializer&#160;</td> <td class="paramname"><em>serializer</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inherited</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Read the specified properties to the object. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">reader</td><td>The <code>Newtonsoft.Json.JsonReader</code> to read from.</td></tr> <tr><td class="paramname">objectType</td><td>Type of the object.</td></tr> <tr><td class="paramname">existingValue</td><td>The existing value of object being read.</td></tr> <tr><td class="paramname">serializer</td><td>The calling serializer.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>The object value.</dd></dl> </div> </div> <a class="anchor" id="a05ac0c517b46f5f9bf33cb826ca8e465"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">override void WriteJson </td> <td>(</td> <td class="paramtype">JsonWriter&#160;</td> <td class="paramname"><em>writer</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">object&#160;</td> <td class="paramname"><em>value</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">JsonSerializer&#160;</td> <td class="paramname"><em>serializer</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inherited</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Write the specified properties of the object. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">writer</td><td>The <code>Newtonsoft.Json.JsonWriter</code> to write to.</td></tr> <tr><td class="paramname">value</td><td>The value.</td></tr> <tr><td class="paramname">serializer</td><td>The calling serializer.</td></tr> </table> </dd> </dl> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- HTML footer for doxygen 1.8.10--> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespace_wanzyee_studio.html">WanzyeeStudio</a></li><li class="navelem"><a class="el" href="namespace_wanzyee_studio_1_1_json.html">Json</a></li><li class="navelem"><a class="el" href="class_wanzyee_studio_1_1_json_1_1_quaternion_converter.html">QuaternionConverter</a></li> <li class="footer"> Generated for&nbsp; <a href="http://wanzyeestudio.blogspot.com/" target="_blank">Wanzyee Studio</a> &nbsp;by&nbsp; <a href="http://www.doxygen.org/index.html" target="_blank"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li> </ul> </div> </body> </html>
{ "content_hash": "2164c0dc81ee7a653986c9ff17561ef8", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 414, "avg_line_length": 46.589595375722546, "alnum_prop": 0.6545285359801489, "repo_name": "Wanzyee/UnityLab", "id": "f2dd3c37c869faf24d66e99396b45748d8603bfc", "size": "16120", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "html/class_wanzyee_studio_1_1_json_1_1_quaternion_converter.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "60249" }, { "name": "HTML", "bytes": "4032411" }, { "name": "JavaScript", "bytes": "528506" } ], "symlink_target": "" }
package Locale::Maketext::Guts; use Locale::Maketext; our $VERSION = '1.17'; =head1 NAME Locale::Maketext::Guts - Deprecated module to load Locale::Maketext utf8 code =head1 SYNOPSIS # Do this instead please use Locale::Maketext =head1 DESCRIPTION Previously Local::Maketext::GutsLoader performed some magic to load Locale::Maketext when utf8 was unavailable. The subs this module provided were merged back into Locale::Maketext =cut 1;
{ "content_hash": "dedc0134cf01d9bc2317364ad05eb67d", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 77, "avg_line_length": 18.791666666666668, "alnum_prop": 0.7649667405764967, "repo_name": "melvin-mancini/Multitasking-RealTime-Arduino-System", "id": "75c993caee59784da11d25ffec8df90e489525f1", "size": "451", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "ARTe/work/tools/cygwin/lib/perl5/5.14/Locale/Maketext/Guts.pm", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "790705" }, { "name": "Awk", "bytes": "30024" }, { "name": "Batchfile", "bytes": "8999" }, { "name": "C", "bytes": "75986100" }, { "name": "C#", "bytes": "291" }, { "name": "C++", "bytes": "43391168" }, { "name": "CSS", "bytes": "11935" }, { "name": "GAP", "bytes": "29013" }, { "name": "GDB", "bytes": "43889" }, { "name": "HTML", "bytes": "16756531" }, { "name": "Java", "bytes": "2947" }, { "name": "Logos", "bytes": "39516" }, { "name": "Makefile", "bytes": "847094" }, { "name": "Mathematica", "bytes": "6430" }, { "name": "Objective-C", "bytes": "147889" }, { "name": "Perl", "bytes": "22959040" }, { "name": "Perl 6", "bytes": "1645534" }, { "name": "PostScript", "bytes": "19471" }, { "name": "Processing", "bytes": "16131" }, { "name": "Prolog", "bytes": "67331" }, { "name": "Python", "bytes": "156764" }, { "name": "Roff", "bytes": "1614973" }, { "name": "Shell", "bytes": "667133" }, { "name": "Slash", "bytes": "3000" }, { "name": "Smalltalk", "bytes": "21223" }, { "name": "SystemVerilog", "bytes": "34576" }, { "name": "Tcl", "bytes": "1430349" }, { "name": "TeX", "bytes": "392340" }, { "name": "Vim script", "bytes": "4718" }, { "name": "XC", "bytes": "7809" }, { "name": "XS", "bytes": "7714" }, { "name": "XSLT", "bytes": "52138" }, { "name": "sed", "bytes": "1016" } ], "symlink_target": "" }
Log backwards! Yet another logging library for Android
{ "content_hash": "d23b0f796be6111085f2ddf096e3d1e4", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 54, "avg_line_length": 55, "alnum_prop": 0.8363636363636363, "repo_name": "porquenao/gol", "id": "1341a5716db4aa17d183ac79bf62f91fada7417e", "size": "61", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "21344" } ], "symlink_target": "" }