text
stringlengths
2
1.04M
meta
dict
require "aws-sdk-ec2" # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param key_pair_name [String] The name for the key pair and private # key file. # @return [Boolean] true if the key pair and private key file were # created; otherwise, false. # @example # exit 1 unless key_pair_created?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'my-key-pair' # ) def key_pair_created?(ec2_client, key_pair_name) key_pair = ec2_client.create_key_pair(key_name: key_pair_name) puts "Created key pair '#{key_pair.key_name}' with fingerprint " \ "'#{key_pair.key_fingerprint}' and ID '#{key_pair.key_pair_id}'." filename = File.join(Dir.home, key_pair_name + ".pem") File.open(filename, "w") { |file| file.write(key_pair.key_material) } puts "Private key file saved locally as '#{filename}'." return true rescue Aws::EC2::Errors::InvalidKeyPairDuplicate puts "Error creating key pair: a key pair named '#{key_pair_name}' " \ "already exists." return false rescue StandardError => e puts "Error creating key pair or saving private key file: #{e.message}" return false end # Displays information about available key pairs in # Amazon Elastic Compute Cloud (Amazon EC2). # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @example # describe_key_pairs(Aws::EC2::Client.new(region: 'us-west-2')) def describe_key_pairs(ec2_client) result = ec2_client.describe_key_pairs if result.key_pairs.count.zero? puts "No key pairs found." else puts "Key pair names:" result.key_pairs.each do |key_pair| puts key_pair.key_name end end rescue StandardError => e puts "Error getting information about key pairs: #{e.message}" end # Deletes a key pair in Amazon Elastic Compute Cloud (Amazon EC2). # # Prerequisites: # # - The key pair to delete. # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param key_pair_name [String] The name of the key pair to delete. # @return [Boolean] true if the key pair was deleted; otherwise, false. # @example # exit 1 unless key_pair_deleted?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'my-key-pair' # ) def key_pair_deleted?(ec2_client, key_pair_name) ec2_client.delete_key_pair(key_name: key_pair_name) return true rescue StandardError => e puts "Error deleting key pair: #{e.message}" return false end # Full example call: def run_me key_pair_name = "" region = "" # Print usage information and then stop. if ARGV[0] == "--help" || ARGV[0] == "-h" puts "Usage: ruby ec2-ruby-example-key-pairs.rb KEY_PAIR_NAME REGION" puts "Example: ruby ec2-ruby-example-key-pairs.rb my-key-pair us-west-2" exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? key_pair_name = "my-key-pair" region = "us-west-2" # Otherwise, use the values as specified at the command prompt. else key_pair_name = ARGV[0] region = ARGV[1] end ec2_client = Aws::EC2::Client.new(region: region) puts "Displaying existing key pair names before creating this key pair..." describe_key_pairs(ec2_client) puts "-" * 10 puts "Creating key pair..." unless key_pair_created?(ec2_client, key_pair_name) puts "Stopping program." exit 1 end puts "-" * 10 puts "Displaying existing key pair names after creating this key pair..." describe_key_pairs(ec2_client) puts "-" * 10 puts "Deleting key pair..." unless key_pair_deleted?(ec2_client, key_pair_name) puts "Stopping program. You must delete the key pair yourself." exit 1 end puts "Key pair deleted." puts "-" * 10 puts "Now that the key pair is deleted, " \ "also deleting the related private key pair file..." filename = File.join(Dir.home, key_pair_name + ".pem") File.delete(filename) if File.exist?(filename) puts "Could not delete file at '#{filename}'. You must delete it yourself." else puts "File deleted." end puts "-" * 10 puts "Displaying existing key pair names after deleting this key pair..." describe_key_pairs(ec2_client) end run_me if $PROGRAM_NAME == __FILE__ # snippet-end:[ec2.Ruby.exampleKeyPairs]
{ "content_hash": "7a282ee3b62ce187a2c66350447dab4c", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 79, "avg_line_length": 32.067669172932334, "alnum_prop": 0.6830011723329426, "repo_name": "awsdocs/aws-doc-sdk-examples", "id": "62aa1de5beeabbda6c59d0906b34a349d8a2da62", "size": "4832", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "ruby/example_code/ec2/ec2-ruby-example-key-pairs.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "476653" }, { "name": "Batchfile", "bytes": "900" }, { "name": "C", "bytes": "3852" }, { "name": "C#", "bytes": "2051923" }, { "name": "C++", "bytes": "943634" }, { "name": "CMake", "bytes": "82068" }, { "name": "CSS", "bytes": "33378" }, { "name": "Dockerfile", "bytes": "2243" }, { "name": "Go", "bytes": "1764292" }, { "name": "HTML", "bytes": "319090" }, { "name": "Java", "bytes": "4966853" }, { "name": "JavaScript", "bytes": "1655476" }, { "name": "Jupyter Notebook", "bytes": "9749" }, { "name": "Kotlin", "bytes": "1099902" }, { "name": "Makefile", "bytes": "4922" }, { "name": "PHP", "bytes": "1220594" }, { "name": "Python", "bytes": "2507509" }, { "name": "Ruby", "bytes": "500331" }, { "name": "Rust", "bytes": "558811" }, { "name": "Shell", "bytes": "63776" }, { "name": "Swift", "bytes": "267325" }, { "name": "TypeScript", "bytes": "119632" } ], "symlink_target": "" }
<!-- saved from url=(0014)about:internet --><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <html> <!-- Standard Head Part --> <head> <title>NUnit - Platform</title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-US"> <link rel="stylesheet" type="text/css" href="nunit.css"> <link rel="shortcut icon" href="favicon.ico"> </head> <!-- End Standard Head Part --> <body> <!-- Standard Header for NUnit.org --> <div id="header"> <a id="logo" href="http://www.nunit.org"><img src="img/logo.gif" alt="NUnit.org" title="NUnit.org"></a> <div id="nav"> <a href="http://www.nunit.org">NUnit</a> <a class="active" href="index.html">Documentation</a> </div> </div> <!-- End of Header --> <div id="content"> <script language="JavaScript" src="codeFuncs.js" ></script> <!-- Do it this way for IE --> <style><!-- div.code { width: 34em } --></style> <h3>PlatformAttribute (NUnit 2.2.2)</h3> <p>The Platform attribute is used to specify platforms for which a test or fixture should be run. Platforms are specified using case-insensitive string values and may be either included or excluded from the run by use of the Include or Exclude properties respectively. Platforms to be included may alternatively be specified as an argument to the PlatformAttribute constructor. In either case, multiple comma-separated values may be specified. <p>If a test or fixture with the Platform attribute does not satisfy the specified platform requirements it is skipped. The test does not affect the outcome of the run at all: it is not considered as ignored and is not even counted in the total number of tests. In the gui, the tree node for the test remains gray and the status bar color is not affected.</p> <blockquote><i><b>Note:</b> In versions of NUnit prior to 2.4, these tests were shown as ignored.</i></blockquote> <h4>Test Fixture Syntax</h4> <div class="code"> <div class="langFilter"> <a href="javascript:Show('DD1')" onmouseover="Show('DD1')"><img src="img/langFilter.gif" width="14" height="14" alt="Language Filter"></a> <div id="DD1" class="dropdown" style="display: none;" onclick="Hide('DD1')"> <a href="javascript:ShowCS()">C#</a><br> <a href="javascript:ShowVB()">VB</a><br> <a href="javascript:ShowMC()">C++</a><br> <a href="javascript:ShowJS()">J#</a><br> </div> </div> <pre class="cs">namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] [Platform(&quot;NET-2.0&quot;)] public class DotNetTwoTests { // ... } } </pre> <pre class="vb">Imports System Imports Nunit.Framework Namespace Nunit.Tests &lt;TestFixture(), Platform(&quot;NET-2.0&quot;)&gt; Public Class DotNetTwoTests &#39; ... End Class End Namespace </pre> <pre class="mc">#using &lt;Nunit.Framework.dll&gt; using namespace System; using namespace NUnit::Framework; namespace NUnitTests { [TestFixture] [Platform(&quot;NET-2.0&quot;)] public __gc class DotNetTwoTests { // ... }; } #include &quot;cppsample.h&quot; namespace NUnitTests { // ... } </pre> <pre class="js">package NUnit.Tests; import System.*; import NUnit.Framework.TestFixture; /** @attribute NUnit.Framework.TestFixture() */ /** @attribute NUnit.Framework.Platform(&quot;NET-2.0&quot;) */ public class DotNetTwoTests { // ... } </pre> </div> <h4>Test Syntax</h4> <div class="code"> <div class="langFilter"> <a href="javascript:Show('DD2')" onmouseover="Show('DD2')"><img src="img/langFilter.gif" width="14" height="14" alt="Language Filter"></a> <div id="DD2" class="dropdown" style="display: none;" onclick="Hide('DD2')"> <a href="javascript:ShowCS()">C#</a><br> <a href="javascript:ShowVB()">VB</a><br> <a href="javascript:ShowMC()">C++</a><br> <a href="javascript:ShowJS()">J#</a><br> </div> </div> <pre class="cs">namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Platform(Exclude=&quot;Win98,WinME&quot;)] public void SomeTest() { /* ... */ } } </pre> <pre class="vb">Imports System Imports Nunit.Framework Namespace Nunit.Tests &lt;TestFixture()&gt; Public Class SuccessTests &lt;Test(), Platform(Exclude=&quot;Win98,WinME&quot;)&gt; Public Sub SomeTest() &#39; ... End Sub End Class End Namespace </pre> <pre class="mc">#using &lt;Nunit.Framework.dll&gt; using namespace System; using namespace NUnit::Framework; namespace NUnitTests { [TestFixture] public __gc class SuccessTests { [Test][Platform(Exclude=&quot;Win98,WinME&quot;)] void SomeTest(); }; } #include &quot;cppsample.h&quot; namespace NUnitTests { // ... } </pre> <pre class="js">package NUnit.Tests; import System.*; import NUnit.Framework.TestFixture; /** @attribute NUnit.Framework.TestFixture() */ public class SuccessTests { /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Platform(Exclude=&quot;Win98,WinME&quot;) */ public void SomeTest() { /* ... */ } } </pre> </div> <h3>Platform Specifiers</h3> <p>The following values are recognized as platform specifiers. They may be expressed in upper, lower or mixed case.</p> <ul class="across"> <li>Win</li> <li>Win32</li> <li>Win32S</li> <li>Win32Windows</li> <li>Win32NT</li> <li>WinCE</li> <li>Win95</li> <li>Win98</li> <li>WinMe</li> <li>NT3</li> <li>NT4</li> <li>NT5</li> <li>NT6</li> <li>Win2K</li> <li>WinXP</li> <li>Win2003Server</li> <li>Vista</li> <li>Win2008Server</li> <li>Unix</li> <li>Linux</li> <li>Net</li> <li>Net-1.0</li> <li>Net-1.1</li> <li>Net-2.0</li> <li>Net-4.0</li> <li>NetCF</li> <li>SSCLI</li> <li>Rotor</li> <li>Mono</li> <li>Mono-1.0</li> <li>Mono-2.0</li> </ul> </div> <!-- Submenu --> <div id="subnav"> <ul> <li><a href="index.html">NUnit 2.5.7</a></li> <ul> <li><a href="getStarted.html">Getting&nbsp;Started</a></li> <li><a href="assertions.html">Assertions</a></li> <li><a href="constraintModel.html">Constraints</a></li> <li><a href="attributes.html">Attributes</a></li> <ul> <li><a href="category.html">Category</a></li> <li><a href="combinatorial.html">Combinatorial</a></li> <li><a href="culture.html">Culture</a></li> <li><a href="datapoint.html">Datapoint(s)</a></li> <li><a href="description.html">Description</a></li> <li><a href="exception.html">Exception</a></li> <li><a href="explicit.html">Explicit</a></li> <li><a href="ignore.html">Ignore</a></li> <li><a href="maxtime.html">Maxtime</a></li> <li><a href="pairwise.html">Pairwise</a></li> <li id="current"><a href="platform.html">Platform</a></li> <li><a href="property.html">Property</a></li> <li><a href="random.html">Random</a></li> <li><a href="range.html">Range</a></li> <li><a href="repeat.html">Repeat</a></li> <li><a href="requiredAddin.html">RequiredAddin</a></li> <li><a href="requiresMTA.html">Requires&nbsp;MTA</a></li> <li><a href="requiresSTA.html">Requires&nbsp;STA</a></li> <li><a href="requiresThread.html">Requires&nbsp;Thread</a></li> <li><a href="sequential.html">Sequential</a></li> <li><a href="setCulture.html">SetCulture</a></li> <li><a href="setup.html">Setup</a></li> <li><a href="setupFixture.html">SetupFixture</a></li> <li><a href="suite.html">Suite</a></li> <li><a href="teardown.html">Teardown</a></li> <li><a href="test.html">Test</a></li> <li><a href="testCase.html">TestCase</a></li> <li><a href="testCaseSource.html">TestCaseSource</a></li> <li><a href="testFixture.html">TestFixture</a></li> <li><a href="fixtureSetup.html">TestFixtureSetUp</a></li> <li><a href="fixtureTeardown.html">TestFixtureTearDown</a></li> <li><a href="theory.html">Theory</a></li> <li><a href="timeout.html">Timeout</a></li> <li><a href="values.html">Values</a></li> <li><a href="valueSource.html">ValueSource</a></li> </ul> <li><a href="runningTests.html">Running&nbsp;Tests</a></li> <li><a href="extensibility.html">Extensibility</a></li> <li><a href="releaseNotes.html">Release&nbsp;Notes</a></li> <li><a href="samples.html">Samples</a></li> <li><a href="license.html">License</a></li> </ul> </ul> </div> <!-- End of Submenu --> <!-- Standard Footer for NUnit.org --> <div id="footer"> Copyright &copy; 2009 Charlie Poole. All Rights Reserved. </div> <!-- End of Footer --> </body> </html>
{ "content_hash": "2225987216093093c944d182b9b2ee90", "timestamp": "", "source": "github", "line_count": 309, "max_line_length": 139, "avg_line_length": 27.550161812297734, "alnum_prop": 0.646070715376483, "repo_name": "continuoustests/AutoTest.Net", "id": "eb0170733b5f3cac7a52952f3fdf48dc41774012", "size": "8513", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/celer/src/lib/NUnit-2.5.7.10213/doc/platform.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "150" }, { "name": "C#", "bytes": "10019506" }, { "name": "C++", "bytes": "87166" }, { "name": "CSS", "bytes": "30132" }, { "name": "JavaScript", "bytes": "102119" }, { "name": "Pascal", "bytes": "215" }, { "name": "PowerShell", "bytes": "156" }, { "name": "Ruby", "bytes": "3593661" }, { "name": "Shell", "bytes": "22163" }, { "name": "Visual Basic", "bytes": "147102" }, { "name": "XSLT", "bytes": "166141" } ], "symlink_target": "" }
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; $environment = (getenv('APP_ENVIRONMENT') !== false) ? getenv('APP_ENVIRONMENT') : 'dev'; $debug = (getenv('APP_DEBUG') !== false) ? (bool) getenv('APP_DEBUG') : true; /** * @var Composer\Autoload\ClassLoader */ $loader = require __DIR__.'/../app/autoload.php'; if (true === $debug) { Debug::enable(); } else { include_once __DIR__.'/../var/bootstrap.php.cache'; } $kernel = new AppKernel($environment, $debug); $kernel->loadClassCache(); // Feel free to activate AppCache if you like if (false === $debug && 'prod' === $environment) { // $kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter // Request::enableHttpMethodParameterOverride(); } $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
{ "content_hash": "c5e4ed37c5e2509036b606459354a86d", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 135, "avg_line_length": 30.818181818181817, "alnum_prop": 0.671583087512291, "repo_name": "Orbitale/EasyImpress", "id": "8000b3ba805acae56732492fb199b7692f6cfe9f", "size": "1017", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "web/app.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "963" }, { "name": "CSS", "bytes": "12438" }, { "name": "HTML", "bytes": "6136" }, { "name": "JavaScript", "bytes": "33940" }, { "name": "PHP", "bytes": "84740" } ], "symlink_target": "" }
using System.Collections.Generic; using Robotlegs.Bender.Extensions.ViewManagement; using Robotlegs.Bender.Extensions.ViewManagement.Impl; using UnityEngine; namespace Robotlegs.Bender.Framework.Unity.Extensions.ViewManagement.Impl { public class UnityParentFinder : IParentFinder { // Container contains container public bool Contains(object parentContainer, object childContainer) { //#if UNITY_EDITOR // Check only in the editor the user is using transforms // if ((parentContainer != null && !(parentContainer is Transform)) || (childContainer != null && !(childContainer is Transform))) // throw new Exception("Container must always be a transform"); //#endif Transform parentTransform = parentContainer as Transform; Transform childTransform = childContainer as Transform; // No child to be contained if (childTransform == null) return false; // Container is the stage/root if (parentTransform == null) return true; while (childTransform != null) { if (childTransform.parent == parentTransform) return true; childTransform = childTransform.parent; } return false; } // View Find Parent Container public object FindParent(object childView, Dictionary<object, ContainerBinding> containers) { return FindParent (childView, new List<ContainerBinding>(containers.Values)); } public object FindParent(object childView, IEnumerable<ContainerBinding> containers) { if (childView is Component) { childView = (childView as Component).transform; } else if (childView is GameObject) { childView = (childView as GameObject).transform; } else return null; Transform transform = childView as Transform; while (transform != null) { foreach (ContainerBinding containerBinding in containers) { if (containerBinding.Container is Transform && (Transform)containerBinding.Container == transform.parent) return containerBinding.Container; } transform = transform.parent; } return null; } } }
{ "content_hash": "f04068add0211d7cc83be72a61b7f548", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 132, "avg_line_length": 28.054794520547944, "alnum_prop": 0.7255859375, "repo_name": "robotlegs-sharp/robotlegs-sharp-framework", "id": "b9124231ef04837aa34d295e47dcd9621e88f906", "size": "2445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Robotlegs/Bender/Platforms/Unity/Extensions/ViewManagement/Impl/UnityParentFinder.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "970300" } ], "symlink_target": "" }
.pure-paginator { letter-spacing: -.31em; *letter-spacing: normal; *word-spacing: -.43em; text-rendering: optimizespeed; list-style: none; margin: 0; padding: 0 } .opera-only :-o-prefocus, .pure-paginator { word-spacing: -.43em } .pure-paginator li { display: inline-block; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; vertical-align: top; text-rendering: auto } .pure-paginator .pure-button { border-radius: 0; padding: .8em 1.4em; vertical-align: top; height: 1.1em } .pure-paginator .pure-button:focus, .pure-paginator .pure-button:active { outline-style: none } .pure-paginator .prev, .pure-paginator .next { color: #C0C1C3; text-shadow: 0 -1px 0 rgba(0, 0, 0, .45) } .pure-paginator .prev { border-radius: 2px 0 0 2px } .pure-paginator .next { border-radius: 0 2px 2px 0 }
{ "content_hash": "37c98c41018d02ad43f576a97e38713d", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 73, "avg_line_length": 18.9375, "alnum_prop": 0.6336633663366337, "repo_name": "AlexanderNZ/pure-website-refactor", "id": "e1decf3be0981524192eb5e53e39c58ddd38c274", "size": "1058", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "css/menus-paginator-min.css", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "616" }, { "name": "CSS", "bytes": "2028200" }, { "name": "HTML", "bytes": "122967" }, { "name": "JavaScript", "bytes": "2079729" }, { "name": "PHP", "bytes": "9161423" }, { "name": "XSLT", "bytes": "6357" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <!-- Generated by javadoc (1.8.0_60) on Wed Mar 30 11:39:21 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>PlayHandler.NettyInvocation (Play! API)</title> <meta name="date" content="2016-03-30"> <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="PlayHandler.NettyInvocation (Play! API)"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </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 class="navBarCell1Rev">Class</li> <li><a href="class-use/PlayHandler.NettyInvocation.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../play/server/PlayHandler.html" title="class in play.server"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../play/server/PlayHandler.WebSocketInvocation.html" title="class in play.server"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?play/server/PlayHandler.NettyInvocation.html" target="_top">Frames</a></li> <li><a href="PlayHandler.NettyInvocation.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">play.server</div> <h2 title="Class PlayHandler.NettyInvocation" class="title">Class PlayHandler.NettyInvocation</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../play/Invoker.Invocation.html" title="class in play">play.Invoker.Invocation</a></li> <li> <ul class="inheritance"> <li>play.server.PlayHandler.NettyInvocation</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.lang.Runnable</dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../play/server/PlayHandler.html" title="class in play.server">PlayHandler</a></dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">PlayHandler.NettyInvocation</span> extends <a href="../../play/Invoker.Invocation.html" title="class in play">Invoker.Invocation</a></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../play/server/PlayHandler.NettyInvocation.html#NettyInvocation-play.mvc.Http.Request-play.mvc.Http.Response-org.jboss.netty.channel.ChannelHandlerContext-org.jboss.netty.handler.codec.http.HttpRequest-org.jboss.netty.channel.MessageEvent-">NettyInvocation</a></span>(<a href="../../play/mvc/Http.Request.html" title="class in play.mvc">Http.Request</a>&nbsp;request, <a href="../../play/mvc/Http.Response.html" title="class in play.mvc">Http.Response</a>&nbsp;response, org.jboss.netty.channel.ChannelHandlerContext&nbsp;ctx, org.jboss.netty.handler.codec.http.HttpRequest&nbsp;nettyRequest, org.jboss.netty.channel.MessageEvent&nbsp;e)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../play/server/PlayHandler.NettyInvocation.html#execute--">execute</a></span>()</code> <div class="block">Override this method</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code><a href="../../play/Invoker.InvocationContext.html" title="class in play">Invoker.InvocationContext</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../play/server/PlayHandler.NettyInvocation.html#getInvocationContext--">getInvocationContext</a></span>()</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../play/server/PlayHandler.NettyInvocation.html#init--">init</a></span>()</code> <div class="block">Init the call (especially usefull in DEV mode to detect changes)</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../play/server/PlayHandler.NettyInvocation.html#onSuccess--">onSuccess</a></span>()</code> <div class="block">Things to do when the whole invocation has succeeded (before + execute + after)</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../play/server/PlayHandler.NettyInvocation.html#run--">run</a></span>()</code> <div class="block">It's time to execute.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.play.Invoker.Invocation"> <!-- --> </a> <h3>Methods inherited from class&nbsp;play.<a href="../../play/Invoker.Invocation.html" title="class in play">Invoker.Invocation</a></h3> <code><a href="../../play/Invoker.Invocation.html#Z:Z_finally--">_finally</a>, <a href="../../play/Invoker.Invocation.html#after--">after</a>, <a href="../../play/Invoker.Invocation.html#before--">before</a>, <a href="../../play/Invoker.Invocation.html#onException-java.lang.Throwable-">onException</a>, <a href="../../play/Invoker.Invocation.html#preInit--">preInit</a>, <a href="../../play/Invoker.Invocation.html#suspend-play.Invoker.Suspend-">suspend</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="NettyInvocation-play.mvc.Http.Request-play.mvc.Http.Response-org.jboss.netty.channel.ChannelHandlerContext-org.jboss.netty.handler.codec.http.HttpRequest-org.jboss.netty.channel.MessageEvent-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>NettyInvocation</h4> <pre>public&nbsp;NettyInvocation(<a href="../../play/mvc/Http.Request.html" title="class in play.mvc">Http.Request</a>&nbsp;request, <a href="../../play/mvc/Http.Response.html" title="class in play.mvc">Http.Response</a>&nbsp;response, org.jboss.netty.channel.ChannelHandlerContext&nbsp;ctx, org.jboss.netty.handler.codec.http.HttpRequest&nbsp;nettyRequest, org.jboss.netty.channel.MessageEvent&nbsp;e)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="init--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>init</h4> <pre>public&nbsp;boolean&nbsp;init()</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from class:&nbsp;<code><a href="../../play/Invoker.Invocation.html#init--">Invoker.Invocation</a></code></span></div> <div class="block">Init the call (especially usefull in DEV mode to detect changes)</div> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code><a href="../../play/Invoker.Invocation.html#init--">init</a></code>&nbsp;in class&nbsp;<code><a href="../../play/Invoker.Invocation.html" title="class in play">Invoker.Invocation</a></code></dd> </dl> </li> </ul> <a name="getInvocationContext--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getInvocationContext</h4> <pre>public&nbsp;<a href="../../play/Invoker.InvocationContext.html" title="class in play">Invoker.InvocationContext</a>&nbsp;getInvocationContext()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../play/Invoker.Invocation.html#getInvocationContext--">getInvocationContext</a></code>&nbsp;in class&nbsp;<code><a href="../../play/Invoker.Invocation.html" title="class in play">Invoker.Invocation</a></code></dd> </dl> </li> </ul> <a name="run--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>run</h4> <pre>public&nbsp;void&nbsp;run()</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from class:&nbsp;<code><a href="../../play/Invoker.Invocation.html#run--">Invoker.Invocation</a></code></span></div> <div class="block">It's time to execute.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>run</code>&nbsp;in interface&nbsp;<code>java.lang.Runnable</code></dd> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code><a href="../../play/Invoker.Invocation.html#run--">run</a></code>&nbsp;in class&nbsp;<code><a href="../../play/Invoker.Invocation.html" title="class in play">Invoker.Invocation</a></code></dd> </dl> </li> </ul> <a name="execute--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>execute</h4> <pre>public&nbsp;void&nbsp;execute() throws java.lang.Exception</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from class:&nbsp;<code><a href="../../play/Invoker.Invocation.html#execute--">Invoker.Invocation</a></code></span></div> <div class="block">Override this method</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../play/Invoker.Invocation.html#execute--">execute</a></code>&nbsp;in class&nbsp;<code><a href="../../play/Invoker.Invocation.html" title="class in play">Invoker.Invocation</a></code></dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>java.lang.Exception</code></dd> </dl> </li> </ul> <a name="onSuccess--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>onSuccess</h4> <pre>public&nbsp;void&nbsp;onSuccess() throws java.lang.Exception</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from class:&nbsp;<code><a href="../../play/Invoker.Invocation.html#onSuccess--">Invoker.Invocation</a></code></span></div> <div class="block">Things to do when the whole invocation has succeeded (before + execute + after)</div> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code><a href="../../play/Invoker.Invocation.html#onSuccess--">onSuccess</a></code>&nbsp;in class&nbsp;<code><a href="../../play/Invoker.Invocation.html" title="class in play">Invoker.Invocation</a></code></dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>java.lang.Exception</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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 class="navBarCell1Rev">Class</li> <li><a href="class-use/PlayHandler.NettyInvocation.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../play/server/PlayHandler.html" title="class in play.server"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../play/server/PlayHandler.WebSocketInvocation.html" title="class in play.server"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?play/server/PlayHandler.NettyInvocation.html" target="_top">Frames</a></li> <li><a href="PlayHandler.NettyInvocation.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><a href="http://guillaume.bort.fr">Guillaume Bort</a> &amp; <a href="http://www.zenexity.fr">zenexity</a> - Distributed under <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2 licence</a>, without any warrantly</small></p> </body> </html>
{ "content_hash": "7e01aa9474b8fb0e821d1a57969d6a1d", "timestamp": "", "source": "github", "line_count": 397, "max_line_length": 470, "avg_line_length": 42.4382871536524, "alnum_prop": 0.6631054131054132, "repo_name": "play1-maven-plugin/play1-maven-plugin.github.io", "id": "1b083b444478ff23a2807975076dd82f72adfccf", "size": "16848", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "external-apidocs/com/google/code/maven-play-plugin/org/playframework/play/1.4.2/play/server/PlayHandler.NettyInvocation.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "245466" }, { "name": "HTML", "bytes": "161333450" }, { "name": "JavaScript", "bytes": "11578" } ], "symlink_target": "" }
context('Secure routes', () => { // '/about' - should provide access to admins it('.about_access_admins()', () => { cy.login('administrator') cy.visit('/about') cy.contains('Environment') }) // '/about' - should not provide access to regular users it('.about_access_regular_users()', () => { cy.login('user') cy.visit('/about') cy.contains('Environment').should('not.exist') }) // '/about' - should not provide access to anonymous users it('.about_access_anonymous_users()', () => { cy.visit('/about') cy.contains('Environment').should('not.exist') }) // '/about/health' - should provide access to admins it('.health_access_admins()', () => { cy.login('administrator') cy.visit('/about/health') cy.contains('Service Health') }) // '/about/health' - should not provide access to regular users it('.health_access_regular_users()', () => { cy.login('user') cy.visit('/about/health') cy.contains('Service Health').should('not.exist') }) // '/about/health' - should not provide access to anonymous users it('.health_access_anonymous_users()', () => { cy.visit('/about/health') cy.contains('Service Health').should('not.exist') }) })
{ "content_hash": "22a401e12ebafab1a369e9f3574cba7a", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 67, "avg_line_length": 30.048780487804876, "alnum_prop": 0.612012987012987, "repo_name": "nulib/avalon", "id": "051189524a4aae9c8dd3e1bee1f0f5ab1c65ac66", "size": "1232", "binary": false, "copies": "2", "ref": "refs/heads/nu/deploy/staging", "path": "spec/cypress/integration/secure_routes_spec.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2934" }, { "name": "CoffeeScript", "bytes": "45476" }, { "name": "Dockerfile", "bytes": "2704" }, { "name": "HCL", "bytes": "43433" }, { "name": "HTML", "bytes": "382033" }, { "name": "JavaScript", "bytes": "257650" }, { "name": "Ruby", "bytes": "1610264" }, { "name": "SCSS", "bytes": "294228" }, { "name": "Shell", "bytes": "1011" }, { "name": "XSLT", "bytes": "260523" } ], "symlink_target": "" }
"""distutils.dir_util Utility functions for manipulating directories and directory trees.""" __revision__ = "$Id: dir_util.py 76956 2009-12-21 01:22:46Z tarek.ziade $" import os from distutils.errors import DistutilsFileError, DistutilsInternalError from distutils import log # cache for by mkpath() -- in addition to cheapening redundant calls, # eliminates redundant "creating /foo/bar/baz" messages in dry-run mode _path_created = {} # I don't use os.makedirs because a) it's new to Python 1.5.2, and # b) it blows up if the directory already exists (I want to silently # succeed in that case). def mkpath(name, mode=0777, verbose=1, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists (or if 'name' is the empty string, which means the current directory, which of course exists), then do nothing. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout. Return the list of directories actually created. """ global _path_created # Detect a common bug -- name is None if not isinstance(name, basestring): raise DistutilsInternalError, \ "mkpath: 'name' must be a string (got %r)" % (name,) # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath(name) created_dirs = [] if os.path.isdir(name) or name == '': return created_dirs if _path_created.get(os.path.abspath(name)): return created_dirs (head, tail) = os.path.split(name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir(head): (head, tail) = os.path.split(head) tails.insert(0, tail) # push next higher dir onto stack # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join(head, d) abs_head = os.path.abspath(head) if _path_created.get(abs_head): continue if verbose >= 1: log.info("creating %s", head) if not dry_run: try: os.mkdir(head) created_dirs.append(head) except OSError, exc: raise DistutilsFileError, \ "could not create '%s': %s" % (head, exc[-1]) _path_created[abs_head] = 1 return created_dirs def create_tree(base_dir, files, mode=0777, verbose=1, dry_run=0): """Create all the empty directories under 'base_dir' needed to put 'files' there. 'base_dir' is just the a name of a directory which doesn't necessarily exist yet; 'files' is a list of filenames to be interpreted relative to 'base_dir'. 'base_dir' + the directory portion of every file in 'files' will be created if it doesn't already exist. 'mode', 'verbose' and 'dry_run' flags are as for 'mkpath()'. """ # First get the list of directories to create need_dir = {} for file in files: need_dir[os.path.join(base_dir, os.path.dirname(file))] = 1 need_dirs = need_dir.keys() need_dirs.sort() # Now create them for dir in need_dirs: mkpath(dir, mode, verbose=verbose, dry_run=dry_run) def copy_tree(src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=1, dry_run=0): """Copy an entire directory tree 'src' to a new location 'dst'. Both 'src' and 'dst' must be directory names. If 'src' is not a directory, raise DistutilsFileError. If 'dst' does not exist, it is created with 'mkpath()'. The end result of the copy is that every file in 'src' is copied to 'dst', and directories under 'src' are recursively copied to 'dst'. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by 'update' or 'dry_run': it is simply the list of all files under 'src', with the names changed to be under 'dst'. 'preserve_mode' and 'preserve_times' are the same as for 'copy_file'; note that they only apply to regular files, not to directories. If 'preserve_symlinks' is true, symlinks will be copied as symlinks (on platforms that support them!); otherwise (the default), the destination of the symlink will be copied. 'update' and 'verbose' are the same as for 'copy_file'. """ from distutils.file_util import copy_file if not dry_run and not os.path.isdir(src): raise DistutilsFileError, \ "cannot copy tree '%s': not a directory" % src try: names = os.listdir(src) except os.error, (errno, errstr): if dry_run: names = [] else: raise DistutilsFileError, \ "error listing files in '%s': %s" % (src, errstr) if not dry_run: mkpath(dst, verbose=verbose) outputs = [] for n in names: src_name = os.path.join(src, n) dst_name = os.path.join(dst, n) if preserve_symlinks and os.path.islink(src_name): link_dest = os.readlink(src_name) if verbose >= 1: log.info("linking %s -> %s", dst_name, link_dest) if not dry_run: os.symlink(link_dest, dst_name) outputs.append(dst_name) elif os.path.isdir(src_name): outputs.extend( copy_tree(src_name, dst_name, preserve_mode, preserve_times, preserve_symlinks, update, verbose=verbose, dry_run=dry_run)) else: copy_file(src_name, dst_name, preserve_mode, preserve_times, update, verbose=verbose, dry_run=dry_run) outputs.append(dst_name) return outputs def _build_cmdtuple(path, cmdtuples): """Helper for remove_tree().""" for f in os.listdir(path): real_f = os.path.join(path,f) if os.path.isdir(real_f) and not os.path.islink(real_f): _build_cmdtuple(real_f, cmdtuples) else: cmdtuples.append((os.remove, real_f)) cmdtuples.append((os.rmdir, path)) def remove_tree(directory, verbose=1, dry_run=0): """Recursively remove an entire directory tree. Any errors are ignored (apart from being reported to stdout if 'verbose' is true). """ from distutils.util import grok_environment_error global _path_created if verbose >= 1: log.info("removing '%s' (and everything under it)", directory) if dry_run: return cmdtuples = [] _build_cmdtuple(directory, cmdtuples) for cmd in cmdtuples: try: cmd[0](cmd[1]) # remove dir from cache if it's already there abspath = os.path.abspath(cmd[1]) if abspath in _path_created: del _path_created[abspath] except (IOError, OSError), exc: log.warn(grok_environment_error( exc, "error removing %s: " % directory)) def ensure_relative(path): """Take the full path 'path', and make it a relative path. This is useful to make 'path' the second argument to os.path.join(). """ drive, path = os.path.splitdrive(path) if path[0:1] == os.sep: path = drive + path[1:] return path
{ "content_hash": "1573b5dfab8f09ab3b06bb7b9094a0dd", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 78, "avg_line_length": 37.27142857142857, "alnum_prop": 0.6177334866487799, "repo_name": "MalloyPower/parsing-python", "id": "eddf3d294f7231e1ed834f191879315e889a163f", "size": "7827", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "front-end/testsuite-python-lib/Python-2.7/Lib/distutils/dir_util.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1963" }, { "name": "Lex", "bytes": "238458" }, { "name": "Makefile", "bytes": "4513" }, { "name": "OCaml", "bytes": "412695" }, { "name": "Python", "bytes": "17319" }, { "name": "Rascal", "bytes": "523063" }, { "name": "Yacc", "bytes": "429659" } ], "symlink_target": "" }
namespace ui { class SlideAnimation; } // namespace ui namespace views { class BubbleFrameView; // BubbleDelegateView creates frame and client views for bubble Widgets. // BubbleDelegateView itself is the client's contents view. // /////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT BubbleDelegateView : public WidgetDelegateView, public ui::AnimationDelegate, public Widget::Observer { public: // The default bubble background color. static const SkColor kBackgroundColor; BubbleDelegateView(); BubbleDelegateView(View* anchor_view, BubbleBorder::ArrowLocation arrow_location); virtual ~BubbleDelegateView(); // Create and initialize the bubble Widget(s) with proper bounds. static Widget* CreateBubble(BubbleDelegateView* bubble_delegate); // WidgetDelegate overrides: virtual View* GetInitiallyFocusedView() OVERRIDE; virtual BubbleDelegateView* AsBubbleDelegate() OVERRIDE; virtual View* GetContentsView() OVERRIDE; virtual NonClientFrameView* CreateNonClientFrameView( views::Widget* widget) OVERRIDE; // Widget::Observer overrides: virtual void OnWidgetVisibilityChanged(Widget* widget, bool visible) OVERRIDE; virtual void OnWidgetActivationChanged(Widget* widget, bool active) OVERRIDE; bool close_on_esc() const { return close_on_esc_; } void set_close_on_esc(bool close_on_esc) { close_on_esc_ = close_on_esc; } bool close_on_deactivate() const { return close_on_deactivate_; } void set_close_on_deactivate(bool close_on_deactivate) { close_on_deactivate_ = close_on_deactivate; } View* anchor_view() const { return anchor_view_; } void set_anchor_view(View* anchor_view) { anchor_view_ = anchor_view; } BubbleBorder::ArrowLocation arrow_location() const { return arrow_location_; } void set_arrow_location(BubbleBorder::ArrowLocation arrow_location) { arrow_location_ = arrow_location; } SkColor color() const { return color_; } void set_color(SkColor color) { color_ = color; } int margin() const { return margin_; } void set_margin(int margin) { margin_ = margin; } gfx::NativeView parent_window() const { return parent_window_; } void set_parent_window(gfx::NativeView window) { parent_window_ = window; } bool use_focusless() const { return use_focusless_; } void set_use_focusless(bool use_focusless) { use_focusless_ = use_focusless; } // Get the arrow's anchor rect in screen space. virtual gfx::Rect GetAnchorRect(); // Show the bubble's widget (and |border_widget_| on Windows). void Show(); // Fade the bubble in or out via Widget transparency. // Fade in calls Widget::Show; fade out calls Widget::Close upon completion. void StartFade(bool fade_in); // Reset fade and opacity of bubble. Restore the opacity of the // bubble to the setting before StartFade() was called. void ResetFade(); // Sets the bubble alignment relative to the anchor. void SetAlignment(BubbleBorder::BubbleAlignment alignment); protected: // View overrides: virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE; // ui::AnimationDelegate overrides: virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE; virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE; // Perform view initialization on the contents for bubble sizing. virtual void Init(); // Resizes and potentially moves the Bubble to best accommodate the // contents preferred size. void SizeToContents(); BubbleFrameView* GetBubbleFrameView() const; private: FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, NonClientHitTest); FRIEND_TEST_ALL_PREFIXES(BubbleDelegateTest, CreateDelegate); // Get bubble bounds from the anchor point and client view's preferred size. gfx::Rect GetBubbleBounds(); #if defined(OS_WIN) && !defined(USE_AURA) // Get bounds for the Windows-only widget that hosts the bubble's contents. gfx::Rect GetBubbleClientBounds() const; #endif // Fade animation for bubble. scoped_ptr<ui::SlideAnimation> fade_animation_; // Flags controlling bubble closure on the escape key and deactivation. bool close_on_esc_; bool close_on_deactivate_; // The view hosting this bubble; the arrow is anchored to this view. View* anchor_view_; // The arrow's location on the bubble. BubbleBorder::ArrowLocation arrow_location_; // The background color of the bubble. SkColor color_; // The margin between the content and the inside of the border, in pixels. int margin_; // Original opacity of the bubble. int original_opacity_; // The widget hosting the border for this bubble (non-Aura Windows only). Widget* border_widget_; // Create a popup window for focusless bubbles on Linux/ChromeOS. // These bubbles are not interactive and should not gain focus. bool use_focusless_; // Parent native window of the bubble. gfx::NativeView parent_window_; DISALLOW_COPY_AND_ASSIGN(BubbleDelegateView); }; } // namespace views #endif // UI_VIEWS_BUBBLE_BUBBLE_DELEGATE_H_
{ "content_hash": "27fa2cf03c26860f5c3678fa058d38c5", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 80, "avg_line_length": 34, "alnum_prop": 0.7132352941176471, "repo_name": "rogerwang/chromium", "id": "75f6c16823f924d8c5af83e58ad05952aed6c8af", "size": "5647", "binary": false, "copies": "2", "ref": "refs/heads/node", "path": "ui/views/bubble/bubble_delegate.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1178292" }, { "name": "C", "bytes": "73237787" }, { "name": "C++", "bytes": "116793287" }, { "name": "F#", "bytes": "381" }, { "name": "Go", "bytes": "10440" }, { "name": "Java", "bytes": "23296" }, { "name": "JavaScript", "bytes": "8698365" }, { "name": "Objective-C", "bytes": "5351255" }, { "name": "PHP", "bytes": "97796" }, { "name": "Perl", "bytes": "918286" }, { "name": "Python", "bytes": "5933085" }, { "name": "R", "bytes": "524" }, { "name": "Shell", "bytes": "4149150" }, { "name": "Tcl", "bytes": "277077" } ], "symlink_target": "" }
namespace iTin.Export.Model { using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Xml.Serialization; [GeneratedCode("System.Xml", "4.0.30319.18033")] [Serializable] //[DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(Namespace = "http://schemas.itin.com/export/engine/2014/configuration/v1.0")] public partial class MiniChartLineTypeModel : BaseModel<MiniChartLineTypeModel> { } }
{ "content_hash": "d525dd7f96a41f712e04eda664c9d072", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 90, "avg_line_length": 29.6875, "alnum_prop": 0.7052631578947368, "repo_name": "iAJTin/iExportEngine", "id": "18c0a09f3112539bf25a0ca6873c8a116538ec81", "size": "476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/library/iTin.Export.Core/Model/Export/Table/Charts/MiniChart/Type/Line/MiniChartLineTypeModel.designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2298" }, { "name": "C#", "bytes": "2815693" }, { "name": "Smalltalk", "bytes": "7632" }, { "name": "XSLT", "bytes": "14099" } ], "symlink_target": "" }
package com.pi4j.io.gpio.trigger; import java.util.List; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; public class GpioSetStateTrigger extends GpioTriggerBase { private final GpioPinDigitalOutput targetPin; private final PinState targetPinState; public GpioSetStateTrigger(GpioPinDigitalOutput targetPin, PinState targetPinState) { super(); this.targetPin = targetPin; this.targetPinState = targetPinState; } public GpioSetStateTrigger(PinState state, GpioPinDigitalOutput targetPin, PinState targetPinState) { super(state); this.targetPin = targetPin; this.targetPinState = targetPinState; } public GpioSetStateTrigger(PinState[] states, GpioPinDigitalOutput targetPin, PinState targetPinState) { super(states); this.targetPin = targetPin; this.targetPinState = targetPinState; } public GpioSetStateTrigger(List<PinState> states, GpioPinDigitalOutput targetPin, PinState targetPinState) { super(states); this.targetPin = targetPin; this.targetPinState = targetPinState; } public GpioPinDigitalOutput getTargetPin() { return targetPin; } public PinState getTargetPinState() { return targetPinState; } @Override public void invoke(GpioPin pin, PinState state) { if (targetPin != null) { targetPin.setState(targetPinState); } } }
{ "content_hash": "b43fb2cc5a961e861d289e0642d5a93e", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 112, "avg_line_length": 27.818181818181817, "alnum_prop": 0.6947712418300653, "repo_name": "starksm64/pi4j", "id": "798ad134ef796f7566fc828303fdbfb365776aed", "size": "2549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pi4j-core/src/main/java/com/pi4j/io/gpio/trigger/GpioSetStateTrigger.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "97682" }, { "name": "Java", "bytes": "964121" }, { "name": "Makefile", "bytes": "10460" }, { "name": "Shell", "bytes": "6839" } ], "symlink_target": "" }
#ifndef itkBlueColormapFunction_h #define itkBlueColormapFunction_h #include "itkColormapFunction.h" namespace itk { namespace Function { /** * \class BlueColormapFunction * \brief Function object which maps a scalar value into an RGB colormap value. * * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich * and James C. Gee * * \image html BlueColormapFunction.png "Blue colormap." * This code was contributed in the Insight Journal paper: * * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" * http://www.insight-journal.org/browse/publication/285 * https://hdl.handle.net/1926/1452 * * \ingroup ITKColormap */ template< typename TScalar, typename TRGBPixel > class ITK_TEMPLATE_EXPORT BlueColormapFunction: public ColormapFunction< TScalar, TRGBPixel > { public: typedef BlueColormapFunction Self; typedef ColormapFunction< TScalar, TRGBPixel > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); typedef typename Superclass::RGBPixelType RGBPixelType; typedef typename Superclass::ScalarType ScalarType; typedef typename Superclass::RealType RealType; virtual RGBPixelType operator()(const TScalar &) const ITK_OVERRIDE; protected: BlueColormapFunction() {} ~BlueColormapFunction() {} private: ITK_DISALLOW_COPY_AND_ASSIGN(BlueColormapFunction); }; } // end namespace functor } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkBlueColormapFunction.hxx" #endif #endif
{ "content_hash": "9d74759c0e442e2c0b8ffe920e7e4308", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 79, "avg_line_length": 28.262295081967213, "alnum_prop": 0.7169373549883991, "repo_name": "RayRuizhiLiao/ITK_4D", "id": "2ac55c4b8d6787eb10e4c8c99584423f3019b6c9", "size": "2515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Modules/Filtering/Colormap/include/itkBlueColormapFunction.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "572693" }, { "name": "C++", "bytes": "36720665" }, { "name": "CMake", "bytes": "1448020" }, { "name": "CSS", "bytes": "18346" }, { "name": "Java", "bytes": "29480" }, { "name": "Objective-C++", "bytes": "6753" }, { "name": "Perl", "bytes": "6113" }, { "name": "Python", "bytes": "385395" }, { "name": "Ruby", "bytes": "309" }, { "name": "Shell", "bytes": "92050" }, { "name": "Tcl", "bytes": "75202" }, { "name": "XSLT", "bytes": "8874" } ], "symlink_target": "" }
var hyperspace = require('hyperspace'); var fs = require('fs'); var html = fs.readFileSync(__dirname + '/cat.html', 'utf8'); module.exports = function () { return hyperspace(html, { key: 'data-key' }, function (row) { return { '.name': row.value.name, '.lives': row.value.lives }; }); };
{ "content_hash": "66cecc1d4338ef3af47d24c218158875", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 65, "avg_line_length": 28.083333333333332, "alnum_prop": 0.5489614243323442, "repo_name": "substack/liver", "id": "08574967e63544359eb09e6a211acd192bb6e200", "size": "337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/pets/parts/cats/render.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "536" }, { "name": "JavaScript", "bytes": "11098" } ], "symlink_target": "" }
(function() { window.SimplePanorama = (function() { SimplePanorama.modules = {}; SimplePanorama.use3DTransform = Modernizr.csstransforms3d && (navigator.userAgent.indexOf('Safari') < 0 || navigator.userAgent.indexOf('Chrome') > -1); function SimplePanorama(options) { var imgFile, pano, wrapperElem; this.maxPos = { x: 0, y: 0 }; this.size = { x: 0, y: 0 }; this.elem = null; this.img = null; this.subElem = null; this.pos = { x: 0.0, y: 0.0 }; this.targetSpeed = { x: 0, y: 0 }; this.speed = { x: 0, y: 0 }; this.hsCounter = 0; this.isRepeative = null; this.moduleData = {}; this.hotspots = {}; this.offset = 0; this.speedOverride = { x: false, y: false }; wrapperElem = options.elem; if ((!wrapperElem) && options.selector) { wrapperElem = $(options.selector); } if (!wrapperElem.length) { throw 'No DOM element supplied for panorama, use "elem" or "selector."'; return null; } this.elem = $('<div class="sp-container"></div>'); imgFile = options.imagePath; if (!imgFile) { throw 'No image path supplied for panorama, use "imagePath".'; return null; } if (options.initialPos) { this.pos.x = wrapperElem.innerWidth() / 2 - options.initialPos; } this.isRepeative = options.repeative === void 0 ? true : options.repeative; this.img = new Image; pano = this; this.img.onload = function() { var i, imgHtml, max, _i, _ref; pano.elem.css("height", this.height + "px"); imgHtml = "<div>"; max = pano.isRepeative ? 2 : 0; for (i = _i = 0; 0 <= max ? _i <= max : _i >= max; i = 0 <= max ? ++_i : --_i) { imgHtml += "<img class=\"sp-image sp-number_" + i + "\" src=\"" + imgFile + "\" alt\"Panorama\" />"; } pano.elem.html(imgHtml + "</div>"); pano.subElem = $(pano.elem.children()[0]); pano.offset = pano.isRepeative ? this.width : 0; pano.subElem.css({ width: this.width * (max + 1) + "px", left: "-" + pano.offset + "px" }); pano.lastTick = (new Date).getTime(); pano.updateSpeedTicks = 0; window.setInterval((function() { return pano._updatePano(); }), 1); pano.elem.mousedown(function(event) { return event.preventDefault(); }); pano.elem.attr("oncontextmenu", "return false;"); if (options.modules) { $.each(options.modules, function(i, moduleId) { pano.moduleData[moduleId] = {}; return SimplePanorama.modules[moduleId](pano, pano.moduleData[moduleId]); }); } wrapperElem.html(pano.elem); $(window).trigger("resize"); if ((_ref = options.callback) != null) { _ref.call(pano); } return $(pano).trigger('loaded'); }; $(window).resize(function() { pano.size.x = pano.img.width < pano.elem.width() ? pano.img.width : pano.elem.parent().innerWidth(); pano.size.y = pano.img.height < pano.elem.height() ? pano.img.height : pano.elem.parent().innerHeight(); pano.elem.css("width", pano.width + "px"); pano.maxPos.x = pano.isRepeative ? pano.img.width : pano.img.width - pano.size.x; return pano.maxPos.y = pano.img.height - pano.size.y; }); this.img.src = imgFile; } SimplePanorama.prototype._updateSpeed = function() { if (this.speedOverride.x) { this.speed.x = this.speedOverride.x; this.speedOverride.x = false; } else { this.speed.x = (1.8 * this.speed.x + 0.2 * this.targetSpeed.x) / 2; } if (this.speedOverride.y) { this.speed.y = this.speedOverride.y; return this.speedOverride.y = false; } else { return this.speed.y = (1.8 * this.speed.y + 0.2 * this.targetSpeed.y) / 2; } }; SimplePanorama.prototype.setCurrentSpeed = function(x, y) { if (y == null) { y = false; } if (x) { this.speedOverride.x = x; } if (y) { return this.speedOverride.y = y; } }; SimplePanorama.prototype.setTargetSpeed = function(x, y) { if (y == null) { y = 0; } this.targetSpeed.x = x; return this.targetSpeed.y = y; }; SimplePanorama.prototype._boundCoordinate = function(value, max) { if (value > 0) { return 0; } else if (value < -max) { return -max; } else { return value; } }; SimplePanorama.prototype._updatePano = function() { var newPosX, newPosY, passedTicks, ticks, transform; ticks = new Date().getTime(); passedTicks = ticks - this.lastTick; this.lastTick = ticks; this.updateSpeedTicks += passedTicks; if (this.updateSpeedTicks > 50) { this._updateSpeed(); this.updateSpeedTicks = 0; } if (this.subElem !== null) { newPosX = this.pos.x + this.speed.x * passedTicks; newPosY = this.pos.y + this.speed.y * passedTicks; this.pos.x = this.isRepeative ? newPosX % this.maxPos.x : this._boundCoordinate(newPosX, this.maxPos.x); this.pos.y = this._boundCoordinate(newPosY, this.maxPos.y); if (SimplePanorama.use3DTransform) { transform = "translate3D(" + this.pos.x + "px, " + this.pos.y + "px, 0)"; return this.subElem.css({ "-o-transform": transform, "-webkit-transform": transform, "-moz-transform": transform, "-ms-transform": transform, "transform": transform }); } else { this.subElem.css("left", this.pos.x - this.offset + "px"); return this.subElem.css("top", this.pos.y + "px"); } } }; SimplePanorama.prototype.createCircleHotspot = function(content, x, y, r, category) { var hs; hs = this._prepareHotspot(content, "sp-circ", x - r, y - r, r * 2, r * 2); hs.css("border-radius", r + "px"); this._populateTripleBuffer(hs, category); return this.hsCounter; }; SimplePanorama.prototype.createRectHotspot = function(content, x, y, w, h, category) { var hs; hs = this._prepareHotspot(content, "sp-rect", x, y, w, h); this._populateTripleBuffer(hs, category); return this.hsCounter; }; SimplePanorama.prototype._prepareHotspot = function(content, cssClass, x, y, w, h) { var result; result = $('<div class="sp-number-' + ++this.hsCounter + ' sp-hotspot ' + cssClass + '"><div class="sp-hotspot-content">' + content + '</div></div>'); result.css({ left: x + 'px', top: y + 'px', width: w + 'px', height: h + 'px' }); return result; }; SimplePanorama.prototype.getRelativePos = function(pageX, pageY) { var left, result, top; left = this.elem.offset().left; top = this.elem.offset().top; result = new Object(); result.x = Math.floor(pageX - left + this.img.width - this.pos.x); result.x %= this.img.width; result.y = Math.floor(pageY - top); if (result.y < 0) { result.y = 0; } return result; }; SimplePanorama.prototype.getRotation = function() { return this.getRelativePos(this.elem.offset().left, 0).x; }; SimplePanorama.prototype._populateTripleBuffer = function(elem, category) { var c1, c2, left; if (!this.hotspots[category]) { this.hotspots[category] = []; } if (this.isRepeative) { c1 = elem.clone(); c2 = elem.clone(); left = parseInt(elem.css('left').slice(0, -2)); c1.css("left", left + this.img.width + "px"); c2.css("left", left + this.img.width * 2 + "px"); this.subElem.append(c1, c2); this.hotspots[category].push(c1, c2); } this.subElem.append(elem); return this.hotspots[category].push(elem); }; SimplePanorama.prototype.showHotspots = function(category, visible) { var elem, _i, _len, _ref, _results; if (visible == null) { visible = true; } if (this.hotspots[category]) { _ref = this.hotspots[category]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elem = _ref[_i]; if (visible) { _results.push($(elem).show()); } else { _results.push($(elem).hide()); } } return _results; } }; SimplePanorama.prototype.removeHotspots = function(category) { var elem, _i, _len, _ref; if (this.hotspots[category]) { _ref = this.hotspots[category]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elem = _ref[_i]; $(elem).remove(); } return this.hotspots[category] = []; } }; return SimplePanorama; })(); }).call(this); (function() { SimplePanorama.modules.move_mousedown = function(pano, data) { pano.elem.on('mousedown', function(event) { if (event.which === 1) { data.mouseStart = { x: event.pageX, y: event.pageY }; pano.elem.css("cursor", "move"); return event.preventDefault(); } }); $("*").on('mousemove', function(event) { if (data.mouseStart !== void 0) { return pano.setTargetSpeed((data.mouseStart.x - event.pageX) / $(window).width() * 3, (data.mouseStart.y - event.pageY) / $(window).height() * 3); } }); return $("*").on('mouseup', function(event) { if (data.mouseStart !== void 0 && event.which === 1) { pano.setTargetSpeed(0); pano.elem.css("cursor", "auto"); return data.mouseStart = void 0; } }); }; }).call(this); (function() { SimplePanorama.modules.move_mousehover = function() { return function(pano) { return pano.elem.on('mousemove', function(event) { var setZero; pano.setTargetSpeed(2 - (event.pageX - pano.elem.position().left) / pano.elem.width() * 4); setZero = pano.targetSpeed.x > 0 ? pano.targetSpeed.x < 1 : pano.targetSpeed.x > -1; if (setZero) { return pano.setTargetSpeed(0); } }); }; }; }).call(this); (function() { SimplePanorama.modules.move_swipe = function(pano, data) { pano.elem.on("touchstart", function(event) { data.touchStart = { x: event.originalEvent.touches[0].pageX, y: event.originalEvent.touches[0].pageY }; return pano.setTargetSpeed(0); }); $("*").on("touchmove", function(event) { var speed, tmp; if (data.touchStart !== void 0) { tmp = { x: event.originalEvent.changedTouches[0].pageX, y: event.originalEvent.changedTouches[0].pageY }; speed = { x: (tmp.x - data.touchStart.x) / 100, y: (tmp.y - data.touchStart.y) / 100 }; if (Math.abs(speed.x) < Math.abs(pano.speed.x)) { speed.x = false; } if (Math.abs(speed.y) < Math.abs(pano.speed.y)) { speed.y = false; } pano.setCurrentSpeed(speed.x, speed.y); return data.touchStart = tmp; } }); return $("*").on("touchend", function() { if (data.touchStart !== void 0) { return data.touchStart = void 0; } }); }; }).call(this); (function() { SimplePanorama.modules.move_touch = function(pano, data) { pano.elem.on("touchstart", function(event) { return data.touchStart = { x: event.originalEvent.touches[0].pageX, y: event.originalEvent.touches[0].pageY }; }); $("*").on("touchmove", function(event) { if (data.touchStart !== void 0) { return pano.setTargetSpeed((data.touchStart.x - event.originalEvent.touches[0].pageX) / 200, (data.touchStart.y - event.originalEvent.touches[0].pageY) / 200); } }); return $("*").on("touchend", function() { if (data.touchStart !== void 0) { pano.setTargetSpeed(0); return data.touchStart = void 0; } }); }; }).call(this); (function() { SimplePanorama.modules.show_coordinates = function(pano) { var box, circ, cursor, postFix, rect, updateCoords; box = $('<div class="scInfoBox"><p></p><p></p><p></p></div>'); cursor = {}; circ = {}; rect = {}; postFix = "SCTemp_9012457832451"; updateCoords = function() { $(box.children('p')[0]).html('Cursor: ' + cursor.x + " " + cursor.y + "<br />Rotation: " + pano.getRotation()); if (rect.path) { $(box.children('p')[1]).html("Rechteck: " + rect.path); rect = {}; } if (circ.path) { $(box.children('p')[2]).html("Kreis: " + circ.path); return circ = {}; } }; $(pano).on('loaded', function() { box.insertBefore(pano.elem); return setInterval(updateCoords, 1000 / 30); }); pano.elem.on('mousedown', function(event) { switch (event.which) { case 3: return rect.start = cursor; case 2: return circ.pos = cursor; } }); $("*").on('mouseup', function(event) { switch (event.which) { case 3: return rect.path = rect.x + "," + rect.y + "," + (rect.x + rect.w) + "," + (rect.y + rect.h); case 2: return circ.path = circ.pos.x + "," + circ.pos.y + "," + circ.r; } }); $("*").on('contextmenu', function() { return !(rect.start || circ.pos); }); return $("*").on('mousemove', function(event) { cursor = pano.getRelativePos(event.pageX, event.pageY); if (rect.start) { rect.w = Math.abs(cursor.x - rect.start.x); rect.h = Math.abs(cursor.y - rect.start.y); rect.x = Math.min(cursor.x, rect.start.x); rect.y = Math.min(cursor.y, rect.start.y); pano.removeHotspots("rect" + postFix); pano.createRectHotspot("", rect.x, rect.y, rect.w, rect.h, "rect" + postFix); } if (circ.pos) { circ.r = Math.max(Math.abs(circ.pos.x - cursor.x), Math.abs(circ.pos.y - cursor.y)); pano.removeHotspots("circ" + postFix); return pano.createCircleHotspot("", circ.pos.x, circ.pos.y, circ.r, "circ" + postFix); } }); }; }).call(this);
{ "content_hash": "a2de0cba9556c1b166b4db5ded2f6d3b", "timestamp": "", "source": "github", "line_count": 451, "max_line_length": 167, "avg_line_length": 32.27272727272727, "alnum_prop": 0.5365166609412573, "repo_name": "TiloW/SimplePanorama", "id": "80586c8b4d5e48e9ce5674fc8c181d94e659b5db", "size": "14555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/simple-panorama.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "645" }, { "name": "CoffeeScript", "bytes": "10624" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Voxalia.ClientGame.EntitySystem; using Voxalia.Shared; namespace Voxalia.ClientGame.NetworkSystem.PacketsIn { public class LoseControlOfVehiclePacketIn : AbstractPacketIn { public override bool ParseBytesAndExecute(byte[] data) { if (data.Length != 8 + 8) { return false; } CharacterEntity driver = TheClient.TheRegion.GetEntity(Utilities.BytesToLong(Utilities.BytesPartial(data, 0, 8))) as CharacterEntity; ModelEntity vehicle = TheClient.TheRegion.GetEntity(Utilities.BytesToLong(Utilities.BytesPartial(data, 8, 8))) as ModelEntity; if (driver == null || vehicle == null) { return true; // Might've been despawned. } PlayerEntity player = driver as PlayerEntity; if (player == null) { return true; // TODO: non-player support! } player.InVehicle = false; player.DrivingMotors.Clear(); player.SteeringMotors.Clear(); player.Vehicle = null; vehicle.HeloPilot = null; vehicle.PlanePilot = null; return true; } } }
{ "content_hash": "2db7090e0630d5fa0dd45c9e7e609281", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 145, "avg_line_length": 34.56410256410256, "alnum_prop": 0.599406528189911, "repo_name": "Morphan1/Voxalia", "id": "9269bf35ce7a064d7dfc33f111aece430b8c9c9c", "size": "1640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Voxalia/ClientGame/NetworkSystem/PacketsIn/LoseControlOfVehiclePacketIn.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "107" }, { "name": "C#", "bytes": "2818801" }, { "name": "C++", "bytes": "2693" }, { "name": "GLSL", "bytes": "54718" }, { "name": "Shell", "bytes": "106" }, { "name": "SourcePawn", "bytes": "1882" } ], "symlink_target": "" }
package fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.pesv; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.CorpusModule; import fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.ResolvedObjects; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Annotation; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Corpus; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Document; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Layer; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.NameType; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Section; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.creators.AnnotationCreator; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.creators.DocumentCreator; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.creators.SectionCreator; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.ResolverException; import fr.inra.maiage.bibliome.alvisnlp.core.module.ModuleException; import fr.inra.maiage.bibliome.alvisnlp.core.module.ProcessingContext; import fr.inra.maiage.bibliome.alvisnlp.core.module.ProcessingException; import fr.inra.maiage.bibliome.alvisnlp.core.module.lib.AlvisNLPModule; import fr.inra.maiage.bibliome.alvisnlp.core.module.lib.Param; import fr.inra.maiage.bibliome.util.Iterators; import fr.inra.maiage.bibliome.util.fragments.Fragment; import fr.inra.maiage.bibliome.util.fragments.SimpleFragment; import fr.inra.maiage.bibliome.util.streams.SourceStream; @AlvisNLPModule(beta=true) public abstract class PESVReader extends CorpusModule<ResolvedObjects> implements DocumentCreator, SectionCreator, AnnotationCreator { private SourceStream docStream; private SourceStream entitiesStream; private String tokenLayerName = "tokens"; private String ordFeatureKey = "ord"; private String sectionName = "text"; private String entityLayerName = "entities"; private String propertiesFeatureKey = "properties"; @Override public void process(ProcessingContext<Corpus> ctx, Corpus corpus) throws ModuleException { try { Logger logger = getLogger(ctx); loadDocuments(logger, corpus); loadEntities(logger, corpus); } catch (IOException e) { throw new ProcessingException(e); } } private void loadEntities(Logger logger, Corpus corpus) throws IOException { Iterator<Reader> readers = entitiesStream.getReaders(); for (Reader r : Iterators.loop(readers)) { String name = entitiesStream.getStreamName(r); logger.info("reading " + name); for (CSVRecord record : CSVFormat.MYSQL.withQuote('"').withFirstRecordAsHeader().parse(r)) { loadEntities(logger, corpus, record); } } } private void loadEntities(Logger logger, Corpus corpus, CSVRecord record) { if (!record.isConsistent()) { logger.warning("line " + record.getRecordNumber() + " has wrong number of columns"); } String docId = record.get("id_articleweb"); if (!corpus.hasDocument(docId)) { logger.warning("line " + record.getRecordNumber() + ": no document " + docId + ", ignoring record"); return; } Document doc = corpus.getDocument(docId); Section sec = doc.sectionIterator(sectionName).next(); Annotation a = createAnnotation(sec, record); for (String col : record.getParser().getHeaderNames()) { String value = record.get(col); a.addFeature(col, value); a.addFeature(propertiesFeatureKey, value); } } private Annotation createAnnotation(Section sec, CSVRecord record) { Layer tokens = sec.ensureLayer(tokenLayerName); String firstTokenIndexStr = record.get("token_index"); String lastTokenIndexStr = getLastTokenIndexStr(firstTokenIndexStr, record); Annotation firstToken = lookupToken(tokens, firstTokenIndexStr); Annotation lastToken = lookupToken(tokens, lastTokenIndexStr); int start = firstToken.getStart(); int end = lastToken.getEnd(); Layer entities = sec.ensureLayer(entityLayerName); return new Annotation(this, entities, start, end); } private static String getLastTokenIndexStr(String firstTokenIndexStr, CSVRecord record) { int firstTokenIndex = Integer.parseInt(firstTokenIndexStr); int entityLength = Integer.parseInt(record.get("length")); int lastTokenIndex = firstTokenIndex + entityLength - 1; return Integer.toString(lastTokenIndex); } private Annotation lookupToken(Layer tokens, String tokenIndexStr) { for (Annotation t : tokens) { if (tokenIndexStr.equals(t.getLastFeature(ordFeatureKey))) { return t; } } return null; } private void loadDocuments(Logger logger, Corpus corpus) throws IOException { Iterator<Reader> readers = docStream.getReaders(); for (Reader r : Iterators.loop(readers)) { String name = docStream.getStreamName(r); logger.info("reading " + name); for (CSVRecord record : CSVFormat.MYSQL.withQuote('"').withFirstRecordAsHeader().parse(r)) { loadDocument(logger, corpus, record); } } } private void loadDocument(Logger logger, Corpus corpus, CSVRecord record) { if (!record.isConsistent()) { logger.warning("line " + record.getRecordNumber() + " has wrong number of columns"); } String docId = record.get("id"); Document doc = Document.getDocument(this, corpus, docId); Map<String,String> features = record.toMap(); for (Map.Entry<String,String> e : features.entrySet()) { String key = e.getKey(); if (!key.equals("id")) { doc.addFeature(key, e.getValue()); } } List<String> tokens = getTokens(record); List<Fragment> frags = new ArrayList<Fragment>(tokens.size()); StringBuilder content = new StringBuilder(); for (String t : tokens) { if (content.length() > 0) { content.append(' '); } int start = content.length(); content.append(t); int end = content.length(); Fragment f = new SimpleFragment(start, end); frags.add(f); } Section sec = new Section(this, doc, sectionName , content.toString()); Layer layer = sec.ensureLayer(tokenLayerName); for (int i = 0; i < frags.size(); ++i) { Fragment f = frags.get(i); Annotation a = new Annotation(this, layer, f.getStart(), f.getEnd()); a.addFeature(ordFeatureKey, Integer.toString(i)); } } private static final Pattern TOKEN_PATTERN = Pattern.compile("<t>(.+?)</t>"); private static List<String> getTokens(CSVRecord record) { List<String> result = new ArrayList<String>(); String s = record.get("processed_text"); Matcher m = TOKEN_PATTERN.matcher(s); while (m.find()) { String t = m.group(1); if (t.equals("<br />")) { t = "\n"; } result.add(t); } return result; } @Override protected ResolvedObjects createResolvedObjects(ProcessingContext<Corpus> ctx) throws ResolverException { return new ResolvedObjects(ctx, this); } @Param public SourceStream getDocStream() { return docStream; } @Param public SourceStream getEntitiesStream() { return entitiesStream; } @Param(nameType=NameType.LAYER) public String getTokenLayerName() { return tokenLayerName; } @Param(nameType=NameType.FEATURE) public String getOrdFeatureKey() { return ordFeatureKey; } @Param(nameType=NameType.SECTION) public String getSectionName() { return sectionName; } @Param(nameType=NameType.LAYER) public String getEntityLayerName() { return entityLayerName; } @Param(nameType=NameType.FEATURE) public String getPropertiesFeatureKey() { return propertiesFeatureKey; } public void setEntitiesStream(SourceStream entitiesStream) { this.entitiesStream = entitiesStream; } public void setTokenLayerName(String tokenLayerName) { this.tokenLayerName = tokenLayerName; } public void setOrdFeatureKey(String ordFeatureKey) { this.ordFeatureKey = ordFeatureKey; } public void setSectionName(String sectionName) { this.sectionName = sectionName; } public void setEntityLayerName(String entityLayerName) { this.entityLayerName = entityLayerName; } public void setPropertiesFeatureKey(String propertiesFeatureKey) { this.propertiesFeatureKey = propertiesFeatureKey; } public void setDocStream(SourceStream docStream) { this.docStream = docStream; } }
{ "content_hash": "7f7ccf48e3f3f0576501fc8ca600ae1e", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 134, "avg_line_length": 34.09349593495935, "alnum_prop": 0.7498509598187671, "repo_name": "Bibliome/alvisnlp", "id": "1439b747e2aaad820b20fd8ab99caeec3dcdff44", "size": "8387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alvisnlp-bibliome/src/main/java/fr/inra/maiage/bibliome/alvisnlp/bibliomefactory/modules/pesv/PESVReader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1885" }, { "name": "CSS", "bytes": "64310" }, { "name": "HTML", "bytes": "15625" }, { "name": "Java", "bytes": "2317082" }, { "name": "JavaScript", "bytes": "764121" }, { "name": "PowerShell", "bytes": "1881" }, { "name": "Python", "bytes": "43221" }, { "name": "Shell", "bytes": "18569" }, { "name": "XSLT", "bytes": "73201" } ], "symlink_target": "" }
The DataTorrent Console (aka dtManage) is a web-based user interface that allows you to monitor and interact with the DataTorrent platform running on your Hadoop cluster. It is a web-based dashboard that is served by the DataTorrent Gateway, and has five areas: configuration, monitoring, development, and , visualization, and learning. To download the platform or the VM sandbox, go to [http://www.datatorrent.com/download](http://www.datatorrent.com/download). ![Console Screenshot](images/dtmanage/console-welcome-screen.png) ### Connection Requirements When you install DataTorrent RTS on your Hadoop cluster using the installer binary, the DataTorrent Gateway service is started on the node where the installer is executed. By default, the Gateway serves the console from port 9090. The ability to connect to this node and port depends on your environment, and may require special setup such as an ssh tunnel, firewall configuration changes, VPN access, etc. ![Architectural Diagram](images/dtmanage/console-gateway-diagram.png) ### Browser Requirements The Console currently supports Chrome, Firefox, Safari, and IE (version 10 and up). ### Installation Wizard The first time you open the Console, after installing DataTorrent RTS on your cluster, it will take you to the Installation Wizard. This walks you through the initial configuration of your DataTorrent installation, by confirming the following: * Location of the hadoop executable * DFS location where all the DataTorrent files are stored * DataTorrent license * Summary and review of any remaining configuration items ![](images/dtmanage/hadoop-config-screenshot.png) #### When Kerberos Security is Enabled When your hadoop cluster has security enabled with Kerberos, there will be four additional controls in the installation wizard: - **Kerberos Principal**: The Kerberos principal (e.g. primary/instance@REALM) to use on behalf of the management console. - **Kerberos Keytab**: The location (path) of the Kerberos keytab file to use on the gateway node's local file system. - **YARN delegation token lifetime**: If the value of the `yarn.resourcemanager.delegation.token.max-lifetime` property in your cluster configuration has been changed from the default, enter it here. Otherwise, leave this blank and the default will be assumed. - **Namenode delegation token lifetime**: If the value of the `dfs.namenode.delegation.token.max-lifetime` property in your cluster configuration has been changed from the default, enter it here. Otherwise, leave this blank and the default will be assumed. > **Note:** The token lifetime values you enter will not actually set these values in your hadoop configuration, it is only meant to inform the DataTorrent platform of these values. ## Configure Tab The configuration page can be found by clicking the “Configure” link in the main navigation bar at the top. There are links to various tools to help you configure and troubleshoot your DataTorrent installation. _The configuration page links may differ depending on your cluster setup. The following is a screenshot with a cluster that has simple authentication/authorization enabled._ ![](images/dtmanage/console-config-screen.png) ### System Configuration This page shows diagnostic information regarding the gateway and console, as well as any issues that the gateway may detect. ![System Configuration Page](images/dtmanage/console-system-screen1.png) In addition, you can perform the following actions from this page: #### Restart the Gateway ![](images/dtmanage/console-gateway-restart.png) This can be useful when Hadoop configuration has changed or some other factor of your cluster environment has changed. #### Toggle Reporting ![](images/dtmanage/console-reporting.png) If enabled, your DataTorrent installation will send various pieces of information such as bug reporting and usage statistics back to our servers. ### License Information Use the License Information page to view how much of your DataTorrent license capacity your cluster is consuming as well as what capabilities your license permits. You can also upload new license files here. ![License Screen](images/dtmanage/console-license.png) ### User Profile The User Profile page displays information about the current user, including their username, the authentication scheme being used, and the roles that the current user has. In addition, users can perform the following actions: - change password - change the default home page - change the theme of the console - restore the default options of the console ![User Profile](images/dtmanage/console-profile.png) ### User Management Use this page to manage users and roles of your DataTorrent cluster: * add users * change users’ roles * change users’ password * delete users * add roles * edit role permissions * delete roles ![User Management Screen](images/dtmanage/console-user-mgmt.png) > **Note:** With most authentication schemes, the admin role cannot be deleted. ### Installation Wizard At any time, you can go back to the installation wizard from the Configuration Tab. It can help diagnose issues and reconfigure your cluster and gateway. ## Develop Tab The development area of dtManage is mainly geared towards the creation, upload, configuration, and launch of DataTorrent applications. The development home can be viewed by clicking the “Develop” tab in the main navigation bar on the top of the screen. A prerequisite to using the development tools of the UI is an understanding of what Apex Application Packages are. For more information, see the [Application Packages Guide](https://www.datatorrent.com/docs/guides/ApplicationDeveloperGuide.html). ![Development Tab](images/dtmanage/console-dev-screen.png) ### Application Packages To access the application package listing, click on the "Apps" link from the Develop Tab index page. From here, you can perform several operators directly on application packages: - Download the app package - Delete the app package - Create a new application in an application package via dtAssemble (requires enterprise license) - Launch applications in the app package - Import default packages (see below) ![Application Packages](images/dtmanage/console-dev-apps.png) > **Note:** If authentication is enabled, you may not be able to see others’ app packages, depending on your permissions. #### Importing Default Packages When you install the DataTorrent platform, a folder located in the installation directory called `demos/app-packages` will contain various default app packages that can be imported into HDFS for use. Just above the list of Application Packages, there should be a button that says **Import default packages**. Clicking this will take you to a page that shows the list of these demo app packages. Select one or more to import and click the **Import** button. This will upload the selected app package to HDFS. ![](images/dtmanage/import-default-packages.png) ### Application Package Page Once you have uploaded or imported an App Package, clicking on the package name in the list will take you to the Application Package Page, where you can view all the package details. ![Application Package Page](images/dtmanage/console-package.png) Aside from various pieces of meta information (owner, DataTorrent version, required properties, etc), you will see a list of apps found in this package. #### Launching Apps To launch an app in an App Package, click on the launch button to the far right of the list. A dialog box will appear with several options: - **Specify a name for the running app** The console will pre-populate this field with an appropriate name, but you can specify your own name. Just be weary that it must be unique compared to the other applications running on your DataTorrent installation. - **Specify the [scheduler queue](https://hadoop.apache.org/docs/r2.4.1/hadoop-yarn/hadoop-yarn-site/CapacityScheduler.html)** This input allows you to specify which queue you want the application to be launched under. The default behavior depends on your Hadoop installation, but typically will be `root.[USER_NAME]`. - **Use a config file when launching** App Package config files are xml files that contain `<properties>` that get interpreted and used for launching an application. To choose one, enable the check box and choose the config file you want to use for launch. - **Specify custom properties** In addition to choosing a config file, you may also specify properties directly in the launch popup by selecting this option. Note that there are three helpful functions when specifying custom properties: - *add required properties* - App Packages can have required properties (for example, twitter API access keys for the twitter demo). This function adds a new property with the required property name to the form, making it easy to fill in. - *add default properties* - App Packages can also have default properties. This function will add the default properties to the list, making it easy for you to override the defaults - *save this configuration as…* - This function creates a new config file and saves it to the App Package, which can then be used later to launch the app with. That way, you can relaunch the app with the same properties without having to re-enter them. ![Launch app modal](images/dtmanage/console-launch-app.png) > **Note:** For more information about config files and custom properties, see the [Application Packages Guide](https://www.datatorrent.com/docs/guides/ApplicationDeveloperGuide.html) ### Viewing an Application DAG All DataTorrent applications are made up of operators that connect together via streams to form a Directed Acyclic Graph (DAG). To see a visualization of this DAG, click on the application name in the list of applications. ![DAG View](images/dtmanage/console-dag-view.png) ### Creating apps with dtAssemble If you have an Enterprise license, you will have access to the dtAssemble tool. Using this tool is outside the scope of this guide, but check out the [dtAssemble guide](http://docs.datatorrent.com/dtassemble/). ## Monitor Tab The main operations dashboard can be visited by clicking on the “Monitor” link in the main top navigation bar. This section of the Console can be used to monitor, debug, and kill running DataTorrent applications. ### Operations Home The operations home page shows overall cluster statistics as well as a list of running DataTorrent applications. ![Operations Home Page](images/dtmanage/console-monitor-home.png) The cluster statistics include some performance statistics and memory usage information. As for the application list, there are two options to take note of: **retrieve ended apps** and **include system apps**. The first option will include all ended applications that are still in the resource manager history. The second option will include system apps, which are apps like the App Data Tracker that are developed by DataTorrent and used to add functionality to your DataTorrent cluster. ### Instance Page To get to an application instance page, click on either the app name or the app id in the list of running applications. ![Instance Page View](images/dtmanage/console-monitor-instance.png) All sections and subsections of the instance page currently use a dashboard/widget system. The controls for this system are located near the top of the screen, below the breadcrumbs: ![widget controls](images/dtmanage/console-widget-ctrls.png) There are tool tips to help you understand how to work with dashboards and widgets. For most users, the default dashboard configurations (*logical*, *physical*, *physical-dag-view*, *metric-view*) will suffice. The following is a list of widgets available on an app instance page: #### Application Overview Widget All the default dashboard tabs have this widget. It contains basic information regarding the app plus a few controls. To end a running application, use either the “shutdown” or “kill” buttons in this widget: ![shutdown and kill buttons](images/dtmanage/console-instance-kill-shutdown.png) The “shutdown” function tries to gracefully stop the application, while “kill” forces the application to end. In either case, you will need to confirm your action. You can also use the **set logging level** button on this widget to specify what logging level gets written to the dt.log files. ![Application Overview widget](images/dtmanage/console-set-level-instance.png) You will then be presented with a dialog where you can specify either fully-qualified class names or package identifiers with wildcards: ![set log level modal](images/dtmanage/console-set-level-modal.png) #### Stram Events Widget Each application has a stream of notable events that can be viewed with the StrAM Events widget: ![Stram Events](images/dtmanage/console-events.png) Some events have additional information attached to it, which can be viewed by clicking the “details” button in the list: ![Event Detail Modal](images/dtmanage/console-events-modal.png) #### Logical DAG Widget This widget visualizes the logical plan of the application being viewed: ![](images/dtmanage/logical-dag.png) Additionally, you can cycle through various metrics aggregated by logical operator. In the screenshot above, processed tuples per second and emitted tuples per second are shown. >**Pro tip:** Hold the alt/option key while using your mouse scroll wheel to zoom in and out on the DAG. #### Physical DAG Widget This is similar to the Logical DAG Widget, except it shows the fully deployed "physical" operators. Depending on the partitioning of your application, this could be significantly more complex than the Logical DAG view. ![](images/dtmanage/physical-dag.png) Same-colored physical operators in this widget indicates that these operators are in the same container. #### Logical Operators List Widget This widget shows a list of logical operators in the application. This table, like others, has live updates, filtering, column ordering, stacked row sorting, and column resizing. One nice feature specific to this widget is the ability to set the logging level for the Java class of a logical operator by selecting it in this list and using the provided dropdown, like so: ![](images/dtmanage/console-set-level-from-oplist.png) #### Physical Operators List Widget Shows the physical operators in the application. #### Containers List Widget Shows the containers in the application. From this widget you can: select a container and go to one of its logs, fetch non-running containers and view information about them, and even kill selected containers. #### Logical Streams List Widget Shows a list of the streams in the application. There are also links to the logical operator pages for the sources and sinks of each stream. #### Metrics Chart Shows various metrics of your application on a real-time line chart. Single-click a metric to toggle its visibility. Double-click a metric to toggle all other keys' visibility. ### Recording and Viewing Sample Tuples There is a mechanism called tuple recording that can be used to easily look at the content of tuples flowing through your application. To use this feature, select a physical operator from the Physical Operators List widget and click on the “record a sample” button. This will bring up a modal window which you can then use to traverse the sample and look at the actual content of the tuple (converted to a JSON structure): ![](images/dtmanage/console-record-tuples.gif) ### Viewing Logs Another useful feature of the Console is the ability to view container logs of a given application. To do this, select a container from the Containers List widget (default location of this widget is in the “physical” dashboard). Then click the logs dropdown and select the log you want to look at: ![](images/dtmanage/console-log-viewing.gif) Once you are viewing a log file in the console, there are few tricks to traversing it. You can scroll to the top to fetch earlier content, scroll to the bottom for later content, grep for strings in the selected range or over the entire log, and click the “eye” icon to the far left of every line to go to that location of the log: ![](images/dtmanage/console-log-viewing-adv.gif) There are numerous improvements in store for dtManage, and user feedback is highly valued in the planning, so please provide any that will help in your usage of the tool! ~The DataTorrent UI Team
{ "content_hash": "1b0edfd4793637a3997318e091602b1e", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 507, "avg_line_length": 57.395833333333336, "alnum_prop": 0.7891107078039927, "repo_name": "chinmaykolhatkar/docs", "id": "9dd1723d20645807288880c63b299dc6b12e954e", "size": "16617", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/dtmanage.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
(function() { 'use strict'; var module = angular.module('bk.notebook'); module.directive('bkCodeCell', function( bkUtils, bkEvaluatorManager, bkCellMenuPluginManager, bkSessionManager, bkCoreManager, $timeout) { var notebookCellOp = bkSessionManager.getNotebookCellOp(); var getBkNotebookWidget = function() { return bkCoreManager.getBkApp().getBkNotebookWidget(); }; var CELL_TYPE = 'code'; return { restrict: 'E', template: JST['mainapp/components/notebook/codecell'](), scope: {cellmodel: '=', cellmenu: '='}, controller: function($scope) { $scope.cellview = { inputMenu: [], displays: [] }; $scope.isLocked = function() { return bkSessionManager.isNotebookLocked(); }; $scope.isEmpty = function() { return !($scope.cellmodel.output.result); }; $scope.isError = function() { //jscs:disable if ($scope.cellmodel === undefined || $scope.cellmodel.output === undefined || $scope.cellmodel.output.result === undefined) { //jscs:enable return false; } var type = $scope.cellmodel.output.result.innertype; if (!type && $scope.cellmodel.output.result.payload !== undefined) { type = $scope.cellmodel.output.result.payload.innertype; } return type == 'Error'; }; $scope.isShowInput = function() { if ($scope.isLocked()) { return false; } if ($scope.cellmodel.input.hidden === true) { return false; } return true; }; $scope.bkNotebook = getBkNotebookWidget(); // ensure cm refreshes when 'unhide' $scope.$watch('isShowInput()', function(newValue, oldValue) { if ($scope.cm && newValue === true && newValue !== oldValue) { bkUtils.fcall(function() { $scope.cm.refresh(); }); } }); $scope.isHiddenOutput = function() { return $scope.cellmodel.output.selectedType == 'Hidden'; }; $scope.hasOutput = function() { return $scope.cellmodel.output.result !== undefined; }; $scope.backgroundClick = function(event) { if (!$scope.isShowInput() || $(event.toElement).parents().hasClass('code-cell-output')) { return; } var top = $(event.delegateTarget).offset().top; var outputElement = $(event.delegateTarget).children('.code-cell-output:first'); var bottom; if (outputElement.length > 0) { bottom = outputElement.offset().top; } else { bottom = top + $(event.delegateTarget).height(); } // Even better would be to detect left/right and move to // beginning or end of line, but we can live with this for now. var cm = $scope.cm; if (event.pageY < (top + bottom) / 2) { cm.setCursor(0, 0); } else { cm.setCursor(cm.lineCount() - 1, cm.getLine(cm.lastLine()).length); } cm.focus(); }; $scope.isShowOutput = function() { if ($scope.cellmodel.output.hidden === true) { return false; } var result = $scope.cellmodel.output.result; if (result && result.hidden === true) { return false; } return !(result === undefined || result === null); }; $scope.outputTitle = function() { return $scope.isError() ? 'Error' : null; }; $scope.evaluate = function($event) { if ($event) { $event.stopPropagation(); } $scope.cellmodel.output.state = {}; bkCoreManager.getBkApp().evaluateRoot($scope.cellmodel). catch(function(data) { console.log('Evaluation failed'); }); }; var editedListener = function(newValue, oldValue) { if (newValue !== oldValue) { bkSessionManager.setNotebookModelEdited(true); } }; $scope.$watch('cellmodel.id', editedListener); $scope.$watch('cellmodel.evaluator', editedListener); $scope.$watch('cellmodel.initialization', editedListener); $scope.$watch('cellmodel.input.body', editedListener); $scope.$watch('cellmodel.output.result', editedListener); $scope.autocomplete = function(cpos, onResults) { var evaluator = bkEvaluatorManager.getEvaluator($scope.cellmodel.evaluator); if (!evaluator) { return; } if (evaluator.autocomplete) { evaluator.autocomplete($scope.cellmodel.input.body, cpos, onResults); } else if (evaluator.autocomplete2) { // used by JavaScript evaluator evaluator.autocomplete2($scope.cm, null, onResults); } }; $scope.showDocs = function(cpos) { var cb = function(doc) { $scope.$broadcast('showTooltip', doc); }; var evaluator = bkEvaluatorManager.getEvaluator($scope.cellmodel.evaluator); if (!evaluator) { return; } if (evaluator.showDocs) { evaluator.showDocs($scope.cellmodel.input.body, cpos, cb); } }; $scope.getEvaluators = function() { return bkEvaluatorManager.getAllEvaluators(); }; $scope.getEvaluator = function() { return bkEvaluatorManager.getEvaluator($scope.cellmodel.evaluator); }; $scope.updateUI = function(evaluator) { $scope.cellmodel.evaluatorReader = Boolean(evaluator); if ($scope.cm && evaluator) { $scope.cm.setOption('mode', evaluator.cmMode); if (evaluator.indentSpaces) { $scope.cm.setOption('indentUnit', evaluator.indentSpaces); } } }; $scope.$watch('getEvaluator()', function(newValue, oldValue) { $scope.updateUI(newValue); }); $scope.appendCodeCell = function(evaluatorName) { var thisCellId = $scope.cellmodel.id; if (!evaluatorName) { // if no evaluator specified, use the current evaluator evaluatorName = $scope.cellmodel.evaluator; } var newCell = bkSessionManager.getNotebookNewCellFactory().newCodeCell(evaluatorName); notebookCellOp.appendAfter(thisCellId, newCell); bkUtils.refreshRootScope(); }; $scope.getShareMenuPlugin = function() { return bkCellMenuPluginManager.getPlugin(CELL_TYPE); }; var shareMenu = { name: 'Share', items: [] }; $scope.cellmenu.addItem(shareMenu); $scope.$watch('getShareMenuPlugin()', function() { shareMenu.items = bkCellMenuPluginManager.getMenuItems(CELL_TYPE, $scope); }); $scope.cellmenu.addItem({ name: 'Show input cell', isChecked: function() { return !$scope.cellmodel.input.hidden; }, action: function() { if ($scope.cellmodel.input.hidden) { delete $scope.cellmodel.input.hidden; } else { $scope.cellmodel.input.hidden = true; } } }); $scope.cellmenu.addItem({ name: 'Show output cell (if available)', isChecked: function() { return !$scope.cellmodel.output.hidden; }, action: function() { if ($scope.cellmodel.output.hidden) { delete $scope.cellmodel.output.hidden; } else { $scope.cellmodel.output.hidden = true; } } }); $scope.isInitializationCell = function() { return $scope.cellmodel.initialization; }; $scope.cellmenu.addItem({ name: 'Initialization Cell', isChecked: function() { return $scope.isInitializationCell(); }, action: function() { if ($scope.isInitializationCell()) { $scope.cellmodel.initialization = undefined; } else { $scope.cellmodel.initialization = true; } notebookCellOp.reset(); } }); $scope.cellmenu.addItem({ name: 'Options', action: function() { bkCoreManager.showFullModalDialog(function cb(r) { } , 'app/mainapp/dialogs/codecelloptions.jst.html', 'CodeCellOptionsController', $scope.cellmodel); } }); }, link: function(scope, element, attrs) { scope.showDebug = false; function isFullScreen(cm) { return /\bCodeMirror-fullscreen\b/.test(cm.getWrapperElement().className); } function winHeight() { return window.innerHeight || (document.documentElement || document.body).clientHeight; } function setFullScreen(cm, full) { var wrap = cm.getWrapperElement(); if (full) { wrap.className += ' CodeMirror-fullscreen'; wrap.style.height = winHeight() + 'px'; document.documentElement.style.overflow = 'hidden'; } else { wrap.className = wrap.className.replace(' CodeMirror-fullscreen', ''); wrap.style.height = ''; document.documentElement.style.overflow = ''; } cm.refresh(); } var resizeHandler = function() { var showing = document.body.getElementsByClassName('CodeMirror-fullscreen')[0]; if (!showing) { return; } showing.CodeMirror.getWrapperElement().style.height = winHeight() + 'px'; }; scope.scrollTo = function(){ window.scrollTo(0, element.offset().top - 100); scope.focus(); }; scope.focus = function() { if (scope.cm === undefined) { initCodeMirror(); } scope.cm.focus(); }; CodeMirror.on(window, 'resize', resizeHandler); var codeMirrorOptions = bkCoreManager.codeMirrorOptions(scope, notebookCellOp); _.extend(codeMirrorOptions.extraKeys, { 'Esc' : function(cm) { cm.execCommand('singleSelection'); if (cm.state.vim && cm.state.vim.insertMode) { return; } else { if (isFullScreen(cm)) { setFullScreen(cm, false); } } }, 'Alt-F11': function(cm) { setFullScreen(cm, !isFullScreen(cm)); }, 'Shift-Ctrl-A': function(cm) { scope.appendCodeCell(); }, 'Shift-Cmd-A': function(cm) { scope.appendCodeCell(); }, 'Shift-Ctrl-E': function(cm) { scope.popupMenu(); element.find('.inputcellmenu').find('li').find('a')[0].focus(); }, 'Shift-Cmd-E': function(cm) { scope.popupMenu(); element.find('.inputcellmenu').find('li').find('a')[0].focus(); }, 'Ctrl-Alt-H': function(cm) { // cell hide scope.cellmodel.input.hidden = true; bkUtils.refreshRootScope(); }, 'Cmd-Alt-H': function(cm) { // cell hide scope.cellmodel.input.hidden = true; bkUtils.refreshRootScope(); }, 'Shift-Ctrl-Enter': function(cm) { scope.evaluateSelection(cm); }, 'Shift-Cmd-Enter': function(cm) { scope.evaluateSelection(cm); } }); var initCodeMirror = function(){ var template = '<textarea class="bkcelltextarea" ng-model="cellmodel.input.body">' + scope.cellmodel.input.body + '</textarea>'; $(element.find('.bkcelltextarea')[0]).replaceWith($(template)); scope.cm = CodeMirror.fromTextArea(element.find('textarea')[0], codeMirrorOptions); scope.bkNotebook.registerCM(scope.cellmodel.id, scope.cm); scope.cm.on('change', changeHandler); scope.cm.on('blur', function () { if ($('.CodeMirror-hint').length > 0) { //codecomplete is up, skip return; } CodeMirror.signal(scope.cm, "cursorActivity", scope.cm); }); scope.cm.on('focus', function () { if ($('.CodeMirror-hint').length > 0) { //codecomplete is up, skip return; } CodeMirror.signal(scope.cm, "cursorActivity", scope.cm); }); scope.updateUI(scope.getEvaluator()); // Since the instantiation of codemirror instances is now lazy, // we need to track and handle focusing on an async cell add if (scope._shouldFocusCodeMirror) { delete scope._shouldFocusCodeMirror; return scope.cm.focus(); } }; Scrollin.track(element[0], function() { if (scope.cm === undefined) { initCodeMirror(); } }); scope.bkNotebook.registerFocusable(scope.cellmodel.id, scope); // cellmodel.body --> CodeMirror scope.$watch('cellmodel.input.body', function(newVal, oldVal) { if (scope.cm && newVal !== scope.cm.getValue()) { if (newVal === null) { newVal = ''; } scope.cm.setValue(newVal); scope.cm.clearHistory(); } }); // cellmodel.body <-- CodeMirror var changeHandler = function(cm, e) { if (scope.cellmodel.input.body !== cm.getValue()) { scope.cellmodel.lineCount = cm.lineCount(); scope.cellmodel.input.body = cm.getValue(); if (!bkSessionManager.isNotebookModelEdited()) { bkSessionManager.setNotebookModelEdited(true); bkUtils.refreshRootScope(); } } }; var inputMenuDiv = element.find('.bkcell').first(); scope.popupMenu = function(event) { var menu = inputMenuDiv.find('.dropdown').first(); menu.find('.dropdown-toggle').first().dropdown('toggle'); }; if (scope.isInitializationCell()) { element.closest('.bkcell').addClass('initcell'); } else { element.closest('.bkcell').removeClass('initcell'); } scope.$watch('isInitializationCell()', function(newValue, oldValue) { if (newValue !== oldValue) { if (newValue) { element.closest('.bkcell').addClass('initcell'); } else { element.closest('.bkcell').removeClass('initcell'); } } }); scope.getShareData = function() { var evaluator = _(bkSessionManager.getRawNotebookModel().evaluators) .find(function(evaluator) { return evaluator.name === scope.cellmodel.evaluator; }); var cells = [scope.cellmodel]; return bkUtils.generateNotebook([evaluator], cells); }; scope.$on('beaker.cell.added', function(e, cellmodel) { if (cellmodel === scope.cellmodel) { if (scope.cm) { return scope.cm.focus(); } scope._shouldFocusCodeMirror = true; } }); scope.evaluateSelection = function(cm) { var evalCode; var currentLine; if (cm.somethingSelected()) { evalCode = cm.getSelection(); } else { currentLine = cm.getCursor().line; evalCode = cm.getLine(currentLine); } scope.cellmodel.output.state = {}; bkCoreManager.getBkApp().evaluateCellCode(scope.cellmodel, evalCode) .then(function(data) { if (currentLine != null) { if (currentLine !== cm.lastLine()) { cm.setCursor(currentLine + 1, 0); } else { codeMirrorOptions.goToNextCell(cm); } } }) .catch(function(data) { console.log('Evaluation failed'); }); }; scope.$on('beaker.section.toggled', function(e, isCollapsed) { if (!isCollapsed) { $timeout(function() { if (scope.cm === undefined) { initCodeMirror(); } else { scope.cm.refresh(); } }); } }); scope.$on('$destroy', function() { Scrollin.untrack(element[0]); CodeMirror.off(window, 'resize', resizeHandler); CodeMirror.off('change', changeHandler); if (scope.cm) { scope.cm.off(); } scope.bkNotebook.unregisterFocusable(scope.cellmodel.id); scope.bkNotebook.unregisterCM(scope.cellmodel.id); scope.bkNotebook = null; }); } }; }); })();
{ "content_hash": "d160d62c32a38911194eef3c9d5eb779", "timestamp": "", "source": "github", "line_count": 512, "max_line_length": 138, "avg_line_length": 33.79296875, "alnum_prop": 0.5257195699919085, "repo_name": "brosander/beaker-notebook", "id": "a773cdacce9f4fd2ed4dee2d5d93d39e2f4fe576", "size": "17924", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/web/app/mainapp/components/notebook/codecell-directive.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "68594" }, { "name": "AppleScript", "bytes": "1998" }, { "name": "Batchfile", "bytes": "1361" }, { "name": "C++", "bytes": "9890" }, { "name": "CSS", "bytes": "442675" }, { "name": "Groovy", "bytes": "2162" }, { "name": "HTML", "bytes": "93870" }, { "name": "Inno Setup", "bytes": "2234" }, { "name": "Java", "bytes": "990529" }, { "name": "JavaScript", "bytes": "7307940" }, { "name": "Objective-C", "bytes": "7449" }, { "name": "Python", "bytes": "67880" }, { "name": "R", "bytes": "20921" }, { "name": "Scala", "bytes": "3682" }, { "name": "Shell", "bytes": "13085" } ], "symlink_target": "" }
ThroughBox
{ "content_hash": "48d670d66839678b5e6e13d7bf7cf88a", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 10, "avg_line_length": 11, "alnum_prop": 0.9090909090909091, "repo_name": "yazver/throughbox", "id": "1336229ce25acde0b8190f9e5fcf3d7942d70ac9", "size": "24", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "27171" } ], "symlink_target": "" }
class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.string :username t.string :password_digest t.timestamps end end end
{ "content_hash": "4e75659b1d353f0c99c96c92830c0805", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 48, "avg_line_length": 16.333333333333332, "alnum_prop": 0.6275510204081632, "repo_name": "xyn12/sinatra-fladdit-project", "id": "cd3813f38e698ffa7c969c164d14463abcd5fcef", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20170803220505_create_users.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "14811" }, { "name": "Ruby", "bytes": "15677" } ], "symlink_target": "" }
struct sample_state { struct wl_display *display; struct compositor_state *compositor; struct wlr_xcursor_manager *xcursor_manager; struct wlr_cursor *cursor; double cur_x, cur_y; float default_color[4]; float clear_color[4]; struct wlr_output_layout *layout; struct wl_list devices; struct timespec last_frame; struct wl_listener new_output; struct wl_listener new_input; struct wl_listener cursor_motion; struct wl_listener cursor_motion_absolute; struct wl_listener cursor_button; struct wl_listener cursor_axis; struct wl_listener touch_motion; struct wl_listener touch_up; struct wl_listener touch_down; struct wl_listener touch_cancel; struct wl_list touch_points; struct wl_listener tablet_tool_axis; struct wl_listener tablet_tool_proxmity; struct wl_listener tablet_tool_tip; struct wl_listener tablet_tool_button; }; struct touch_point { int32_t touch_id; double x, y; struct wl_list link; }; struct sample_output { struct sample_state *state; struct wlr_output *output; struct wl_listener frame; struct wl_listener destroy; }; struct sample_keyboard { struct sample_state *state; struct wlr_input_device *device; struct wl_listener key; struct wl_listener destroy; }; static void warp_to_touch(struct sample_state *state, struct wlr_input_device *dev) { if (wl_list_empty(&state->touch_points)) { return; } double x = 0, y = 0; size_t n = 0; struct touch_point *point; wl_list_for_each(point, &state->touch_points, link) { x += point->x; y += point->y; n++; } x /= n; y /= n; wlr_cursor_warp_absolute(state->cursor, dev, x, y); } static void output_frame_notify(struct wl_listener *listener, void *data) { struct sample_output *sample_output = wl_container_of(listener, sample_output, frame); struct sample_state *state = sample_output->state; struct wlr_output *wlr_output = sample_output->output; struct wlr_renderer *renderer = wlr_backend_get_renderer(wlr_output->backend); assert(renderer); wlr_output_attach_render(wlr_output, NULL); wlr_renderer_begin(renderer, wlr_output->width, wlr_output->height); wlr_renderer_clear(renderer, state->clear_color); wlr_output_render_software_cursors(wlr_output, NULL); wlr_renderer_end(renderer); wlr_output_commit(wlr_output); } static void handle_cursor_motion(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, cursor_motion); struct wlr_event_pointer_motion *event = data; wlr_cursor_move(sample->cursor, event->device, event->delta_x, event->delta_y); } static void handle_cursor_motion_absolute(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, cursor_motion_absolute); struct wlr_event_pointer_motion_absolute *event = data; sample->cur_x = event->x; sample->cur_y = event->y; wlr_cursor_warp_absolute(sample->cursor, event->device, sample->cur_x, sample->cur_y); } static void handle_cursor_button(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, cursor_button); struct wlr_event_pointer_button *event = data; float (*color)[4]; if (event->state == WLR_BUTTON_RELEASED) { color = &sample->default_color; memcpy(&sample->clear_color, color, sizeof(*color)); } else { float red[4] = { 0.25f, 0.25f, 0.25f, 1 }; red[event->button % 3] = 1; color = &red; memcpy(&sample->clear_color, color, sizeof(*color)); } } static void handle_cursor_axis(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, cursor_axis); struct wlr_event_pointer_axis *event = data; for (size_t i = 0; i < 3; ++i) { sample->default_color[i] += event->delta > 0 ? -0.05f : 0.05f; if (sample->default_color[i] > 1.0f) { sample->default_color[i] = 1.0f; } if (sample->default_color[i] < 0.0f) { sample->default_color[i] = 0.0f; } } memcpy(&sample->clear_color, &sample->default_color, sizeof(sample->clear_color)); } static void handle_touch_up(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, touch_up); struct wlr_event_touch_up *event = data; struct touch_point *point, *tmp; wl_list_for_each_safe(point, tmp, &sample->touch_points, link) { if (point->touch_id == event->touch_id) { wl_list_remove(&point->link); break; } } warp_to_touch(sample, event->device); } static void handle_touch_down(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, touch_down); struct wlr_event_touch_down *event = data; struct touch_point *point = calloc(1, sizeof(struct touch_point)); point->touch_id = event->touch_id; point->x = event->x; point->y = event->y; wl_list_insert(&sample->touch_points, &point->link); warp_to_touch(sample, event->device); } static void handle_touch_motion(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, touch_motion); struct wlr_event_touch_motion *event = data; struct touch_point *point; wl_list_for_each(point, &sample->touch_points, link) { if (point->touch_id == event->touch_id) { point->x = event->x; point->y = event->y; break; } } warp_to_touch(sample, event->device); } static void handle_touch_cancel(struct wl_listener *listener, void *data) { wlr_log(WLR_DEBUG, "TODO: touch cancel"); } static void handle_tablet_tool_axis(struct wl_listener *listener, void *data) { struct sample_state *sample = wl_container_of(listener, sample, tablet_tool_axis); struct wlr_event_tablet_tool_axis *event = data; if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_X) && (event->updated_axes & WLR_TABLET_TOOL_AXIS_Y)) { wlr_cursor_warp_absolute(sample->cursor, event->device, event->x, event->y); } } static void keyboard_key_notify(struct wl_listener *listener, void *data) { struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, key); struct sample_state *sample = keyboard->state; struct wlr_event_keyboard_key *event = data; uint32_t keycode = event->keycode + 8; const xkb_keysym_t *syms; int nsyms = xkb_state_key_get_syms(keyboard->device->keyboard->xkb_state, keycode, &syms); for (int i = 0; i < nsyms; i++) { xkb_keysym_t sym = syms[i]; if (sym == XKB_KEY_Escape) { wl_display_terminate(sample->display); } } } static void output_remove_notify(struct wl_listener *listener, void *data) { struct sample_output *sample_output = wl_container_of(listener, sample_output, destroy); struct sample_state *sample = sample_output->state; wlr_output_layout_remove(sample->layout, sample_output->output); wl_list_remove(&sample_output->frame.link); wl_list_remove(&sample_output->destroy.link); free(sample_output); } static void new_output_notify(struct wl_listener *listener, void *data) { struct wlr_output *output = data; struct sample_state *sample = wl_container_of(listener, sample, new_output); struct sample_output *sample_output = calloc(1, sizeof(struct sample_output)); if (!wl_list_empty(&output->modes)) { struct wlr_output_mode *mode = wl_container_of(output->modes.prev, mode, link); wlr_output_set_mode(output, mode); } sample_output->output = output; sample_output->state = sample; wl_signal_add(&output->events.frame, &sample_output->frame); sample_output->frame.notify = output_frame_notify; wl_signal_add(&output->events.destroy, &sample_output->destroy); sample_output->destroy.notify = output_remove_notify; wlr_output_layout_add_auto(sample->layout, sample_output->output); wlr_xcursor_manager_load(sample->xcursor_manager, output->scale); wlr_xcursor_manager_set_cursor_image(sample->xcursor_manager, "left_ptr", sample->cursor); wlr_output_commit(output); } static void keyboard_destroy_notify(struct wl_listener *listener, void *data) { struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, destroy); wl_list_remove(&keyboard->destroy.link); wl_list_remove(&keyboard->key.link); free(keyboard); } static void new_input_notify(struct wl_listener *listener, void *data) { struct wlr_input_device *device = data; struct sample_state *state = wl_container_of(listener, state, new_input); switch (device->type) { case WLR_INPUT_DEVICE_POINTER: case WLR_INPUT_DEVICE_TOUCH: case WLR_INPUT_DEVICE_TABLET_TOOL: wlr_cursor_attach_input_device(state->cursor, device); break; case WLR_INPUT_DEVICE_KEYBOARD:; struct sample_keyboard *keyboard = calloc(1, sizeof(struct sample_keyboard)); keyboard->device = device; keyboard->state = state; wl_signal_add(&device->events.destroy, &keyboard->destroy); keyboard->destroy.notify = keyboard_destroy_notify; wl_signal_add(&device->keyboard->events.key, &keyboard->key); keyboard->key.notify = keyboard_key_notify; struct xkb_rule_names rules = { 0 }; rules.rules = getenv("XKB_DEFAULT_RULES"); rules.model = getenv("XKB_DEFAULT_MODEL"); rules.layout = getenv("XKB_DEFAULT_LAYOUT"); rules.variant = getenv("XKB_DEFAULT_VARIANT"); rules.options = getenv("XKB_DEFAULT_OPTIONS"); struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); if (!context) { wlr_log(WLR_ERROR, "Failed to create XKB context"); exit(1); } struct xkb_keymap *keymap = xkb_map_new_from_names(context, &rules, XKB_KEYMAP_COMPILE_NO_FLAGS); if (!keymap) { wlr_log(WLR_ERROR, "Failed to create XKB keymap"); exit(1); } wlr_keyboard_set_keymap(device->keyboard, keymap); xkb_keymap_unref(keymap); xkb_context_unref(context); break; default: break; } } int main(int argc, char *argv[]) { wlr_log_init(WLR_DEBUG, NULL); struct wl_display *display = wl_display_create(); struct sample_state state = { .default_color = { 0.25f, 0.25f, 0.25f, 1 }, .clear_color = { 0.25f, 0.25f, 0.25f, 1 }, .display = display }; struct wlr_backend *wlr = wlr_backend_autocreate(display, NULL); if (!wlr) { exit(1); } state.cursor = wlr_cursor_create(); state.layout = wlr_output_layout_create(); wlr_cursor_attach_output_layout(state.cursor, state.layout); //wlr_cursor_map_to_region(state.cursor, state.config->cursor.mapped_box); wl_list_init(&state.devices); wl_list_init(&state.touch_points); // pointer events wl_signal_add(&state.cursor->events.motion, &state.cursor_motion); state.cursor_motion.notify = handle_cursor_motion; wl_signal_add(&state.cursor->events.motion_absolute, &state.cursor_motion_absolute); state.cursor_motion_absolute.notify = handle_cursor_motion_absolute; wl_signal_add(&state.cursor->events.button, &state.cursor_button); state.cursor_button.notify = handle_cursor_button; wl_signal_add(&state.cursor->events.axis, &state.cursor_axis); state.cursor_axis.notify = handle_cursor_axis; // touch events wl_signal_add(&state.cursor->events.touch_up, &state.touch_up); state.touch_up.notify = handle_touch_up; wl_signal_add(&state.cursor->events.touch_down, &state.touch_down); state.touch_down.notify = handle_touch_down; wl_signal_add(&state.cursor->events.touch_motion, &state.touch_motion); state.touch_motion.notify = handle_touch_motion; wl_signal_add(&state.cursor->events.touch_cancel, &state.touch_cancel); state.touch_cancel.notify = handle_touch_cancel; wl_signal_add(&wlr->events.new_input, &state.new_input); state.new_input.notify = new_input_notify; wl_signal_add(&wlr->events.new_output, &state.new_output); state.new_output.notify = new_output_notify; // tool events wl_signal_add(&state.cursor->events.tablet_tool_axis, &state.tablet_tool_axis); state.tablet_tool_axis.notify = handle_tablet_tool_axis; state.xcursor_manager = wlr_xcursor_manager_create("default", 24); if (!state.xcursor_manager) { wlr_log(WLR_ERROR, "Failed to load left_ptr cursor"); return 1; } wlr_xcursor_manager_set_cursor_image(state.xcursor_manager, "left_ptr", state.cursor); clock_gettime(CLOCK_MONOTONIC, &state.last_frame); if (!wlr_backend_start(wlr)) { wlr_log(WLR_ERROR, "Failed to start backend"); wlr_backend_destroy(wlr); exit(1); } wl_display_run(display); wl_display_destroy(display); wlr_xcursor_manager_destroy(state.xcursor_manager); wlr_cursor_destroy(state.cursor); wlr_output_layout_destroy(state.layout); }
{ "content_hash": "e8160eb9be6d9e1e1c9452758b6d536c", "timestamp": "", "source": "github", "line_count": 383, "max_line_length": 89, "avg_line_length": 32.099216710182766, "alnum_prop": 0.7130307467057101, "repo_name": "ascent12/wlroots", "id": "a6080716318e1140b6f76e20bfd93a61f4378764", "size": "12899", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/pointer.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1677469" }, { "name": "Makefile", "bytes": "1037" }, { "name": "Meson", "bytes": "17572" }, { "name": "Shell", "bytes": "602" } ], "symlink_target": "" }
/* IupFill: Example in C Uses the Fill element to horizontally centralize a button and to justify it to the left and right. */ #include <stdlib.h> #include <stdio.h> #include <iup.h> int main(int argc, char **argv) { /* IUP handles */ Ihandle *frame_left; Ihandle *frame_right; Ihandle *frame_center; Ihandle *dialog; /* Initializes IUP */ IupOpen(&argc, &argv); /* Creates frame with left aligned button */ frame_left = IupFrame ( IupHbox ( IupButton( "Ok" , "" ), IupFill(), NULL ) ); /* Sets frame's title */ IupSetAttribute( frame_left, "TITLE", "Left aligned" ); /* Creates frame with centered button */ frame_center = IupFrame ( IupHbox ( IupFill (), IupButton ( "Ok", "" ), IupFill (), NULL ) ); /* Sets frame's title */ IupSetAttribute( frame_center, "TITLE", "Centered" ); /* Creates frame with right aligned button */ frame_right = IupFrame ( IupHbox ( IupFill (), IupButton ( "Ok", "" ), NULL ) ); /* Sets frame's title */ IupSetAttribute( frame_right, "TITLE", "Right aligned" ); /* Creates dialog with these three frames */ dialog = IupDialog ( IupVbox ( frame_left, frame_center, frame_right, NULL ) ); /* Sets dialog's size and title */ IupSetAttributes( dialog, "SIZE=120, TITLE=IupFill"); IupShow( dialog ); /* Shows dialog in the center of the screen */ IupMainLoop(); /* Initializes IUP main loop */ IupClose(); /* Finishes IUP */ return EXIT_SUCCESS; }
{ "content_hash": "b060d7febbe56ca31fa423e855feb1f2", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 101, "avg_line_length": 19.154761904761905, "alnum_prop": 0.5835922933499068, "repo_name": "ivanceras/iup-mirror", "id": "83ba6b0e49a9058c82e325b1b91dc7a27f2ec658", "size": "1609", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "html/examples/C/fill.c", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "51" }, { "name": "Batchfile", "bytes": "10657" }, { "name": "C", "bytes": "10805242" }, { "name": "C++", "bytes": "7443129" }, { "name": "CSS", "bytes": "14478" }, { "name": "HTML", "bytes": "2313042" }, { "name": "Lua", "bytes": "729555" }, { "name": "Makefile", "bytes": "139501" }, { "name": "Shell", "bytes": "11775" } ], "symlink_target": "" }
#include "config.h" #if ENABLE(SVG) #include "SVGForeignObjectElement.h" #include "Attribute.h" #include "CSSPropertyNames.h" #include "NodeRenderingContext.h" #include "RenderSVGForeignObject.h" #include "RenderSVGResource.h" #include "SVGElementInstance.h" #include "SVGLength.h" #include "SVGNames.h" #include <wtf/Assertions.h> namespace WebCore { // Animated property definitions DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::xAttr, X, x) DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::yAttr, Y, y) DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::widthAttr, Width, width) DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::heightAttr, Height, height) DEFINE_ANIMATED_STRING(SVGForeignObjectElement, XLinkNames::hrefAttr, Href, href) DEFINE_ANIMATED_BOOLEAN(SVGForeignObjectElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired) BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGForeignObjectElement) REGISTER_LOCAL_ANIMATED_PROPERTY(x) REGISTER_LOCAL_ANIMATED_PROPERTY(y) REGISTER_LOCAL_ANIMATED_PROPERTY(width) REGISTER_LOCAL_ANIMATED_PROPERTY(height) REGISTER_LOCAL_ANIMATED_PROPERTY(href) REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired) REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement) REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests) END_REGISTER_ANIMATED_PROPERTIES inline SVGForeignObjectElement::SVGForeignObjectElement(const QualifiedName& tagName, Document* document) : SVGStyledTransformableElement(tagName, document) , m_x(LengthModeWidth) , m_y(LengthModeHeight) , m_width(LengthModeWidth) , m_height(LengthModeHeight) { ASSERT(hasTagName(SVGNames::foreignObjectTag)); registerAnimatedPropertiesForSVGForeignObjectElement(); } PassRefPtr<SVGForeignObjectElement> SVGForeignObjectElement::create(const QualifiedName& tagName, Document* document) { return adoptRef(new SVGForeignObjectElement(tagName, document)); } bool SVGForeignObjectElement::isSupportedAttribute(const QualifiedName& attrName) { DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); if (supportedAttributes.isEmpty()) { SVGTests::addSupportedAttributes(supportedAttributes); SVGLangSpace::addSupportedAttributes(supportedAttributes); SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes); supportedAttributes.add(SVGNames::xAttr); supportedAttributes.add(SVGNames::yAttr); supportedAttributes.add(SVGNames::widthAttr); supportedAttributes.add(SVGNames::heightAttr); } return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName); } void SVGForeignObjectElement::parseAttribute(const Attribute& attribute) { SVGParsingError parseError = NoError; const AtomicString& value = attribute.value(); if (!isSupportedAttribute(attribute.name())) SVGStyledTransformableElement::parseAttribute(attribute); else if (attribute.name() == SVGNames::xAttr) setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError)); else if (attribute.name() == SVGNames::yAttr) setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError)); else if (attribute.name() == SVGNames::widthAttr) setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError)); else if (attribute.name() == SVGNames::heightAttr) setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError)); else if (SVGTests::parseAttribute(attribute) || SVGLangSpace::parseAttribute(attribute) || SVGExternalResourcesRequired::parseAttribute(attribute)) { } else ASSERT_NOT_REACHED(); reportAttributeParsingError(parseError, attribute); } void SVGForeignObjectElement::svgAttributeChanged(const QualifiedName& attrName) { if (!isSupportedAttribute(attrName)) { SVGStyledTransformableElement::svgAttributeChanged(attrName); return; } SVGElementInstance::InvalidationGuard invalidationGuard(this); bool isLengthAttribute = attrName == SVGNames::xAttr || attrName == SVGNames::yAttr || attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr; if (isLengthAttribute) updateRelativeLengthsInformation(); if (SVGTests::handleAttributeChange(this, attrName)) return; if (RenderObject* renderer = this->renderer()) RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer); } RenderObject* SVGForeignObjectElement::createRenderer(RenderArena* arena, RenderStyle*) { return new (arena) RenderSVGForeignObject(this); } bool SVGForeignObjectElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const { // Disallow arbitary SVG content. Only allow proper <svg xmlns="svgNS"> subdocuments. if (childContext.node()->isSVGElement()) return childContext.node()->hasTagName(SVGNames::svgTag); // Skip over SVG rules which disallow non-SVG kids return StyledElement::childShouldCreateRenderer(childContext); } bool SVGForeignObjectElement::selfHasRelativeLengths() const { return x().isRelative() || y().isRelative() || width().isRelative() || height().isRelative(); } } #endif
{ "content_hash": "0f14a35f1df7d137ead0bdd4372a54de", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 143, "avg_line_length": 38, "alnum_prop": 0.7517482517482518, "repo_name": "yoavweiss/RespImg-WebCore", "id": "f2376aff29ccdb2cec95747fb9c1e1e12eb7f8d3", "size": "6331", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "svg/SVGForeignObjectElement.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "1301" }, { "name": "C", "bytes": "2369715" }, { "name": "C++", "bytes": "39064862" }, { "name": "JavaScript", "bytes": "3763760" }, { "name": "Objective-C", "bytes": "2038598" }, { "name": "Perl", "bytes": "768866" }, { "name": "Prolog", "bytes": "519" }, { "name": "Python", "bytes": "210630" }, { "name": "Ruby", "bytes": "1927" }, { "name": "Shell", "bytes": "8214" } ], "symlink_target": "" }
package com.google.android.exoplayer2.text.ttml; import static android.graphics.Color.BLACK; import static android.graphics.Color.WHITE; import static com.google.android.exoplayer2.text.ttml.TtmlStyle.STYLE_BOLD; import static com.google.android.exoplayer2.text.ttml.TtmlStyle.STYLE_BOLD_ITALIC; import static com.google.android.exoplayer2.text.ttml.TtmlStyle.STYLE_ITALIC; import static com.google.android.exoplayer2.text.ttml.TtmlStyle.STYLE_NORMAL; import static com.google.android.exoplayer2.text.ttml.TtmlStyle.UNSPECIFIED; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import android.graphics.Color; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; /** Unit test for {@link TtmlStyle}. */ @RunWith(RobolectricTestRunner.class) @Config(sdk = Config.TARGET_SDK, manifest = Config.NONE) public final class TtmlStyleTest { private static final String FONT_FAMILY = "serif"; private static final String ID = "id"; public static final int FOREGROUND_COLOR = Color.WHITE; public static final int BACKGROUND_COLOR = Color.BLACK; private TtmlStyle style; @Before public void setUp() throws Exception { style = new TtmlStyle(); } @Test public void testInheritStyle() { style.inherit(createAncestorStyle()); assertWithMessage("id must not be inherited").that(style.getId()).isNull(); assertThat(style.isUnderline()).isTrue(); assertThat(style.isLinethrough()).isTrue(); assertThat(style.getStyle()).isEqualTo(STYLE_BOLD_ITALIC); assertThat(style.getFontFamily()).isEqualTo(FONT_FAMILY); assertThat(style.getFontColor()).isEqualTo(WHITE); assertWithMessage("do not inherit backgroundColor").that(style.hasBackgroundColor()).isFalse(); } @Test public void testChainStyle() { style.chain(createAncestorStyle()); assertWithMessage("id must not be inherited").that(style.getId()).isNull(); assertThat(style.isUnderline()).isTrue(); assertThat(style.isLinethrough()).isTrue(); assertThat(style.getStyle()).isEqualTo(STYLE_BOLD_ITALIC); assertThat(style.getFontFamily()).isEqualTo(FONT_FAMILY); assertThat(style.getFontColor()).isEqualTo(FOREGROUND_COLOR); // do inherit backgroundColor when chaining assertWithMessage("do not inherit backgroundColor when chaining") .that(style.getBackgroundColor()).isEqualTo(BACKGROUND_COLOR); } private static TtmlStyle createAncestorStyle() { TtmlStyle ancestor = new TtmlStyle(); ancestor.setId(ID); ancestor.setItalic(true); ancestor.setBold(true); ancestor.setBackgroundColor(BACKGROUND_COLOR); ancestor.setFontColor(FOREGROUND_COLOR); ancestor.setLinethrough(true); ancestor.setUnderline(true); ancestor.setFontFamily(FONT_FAMILY); return ancestor; } @Test public void testStyle() { assertThat(style.getStyle()).isEqualTo(UNSPECIFIED); style.setItalic(true); assertThat(style.getStyle()).isEqualTo(STYLE_ITALIC); style.setBold(true); assertThat(style.getStyle()).isEqualTo(STYLE_BOLD_ITALIC); style.setItalic(false); assertThat(style.getStyle()).isEqualTo(STYLE_BOLD); style.setBold(false); assertThat(style.getStyle()).isEqualTo(STYLE_NORMAL); } @Test public void testLinethrough() { assertThat(style.isLinethrough()).isFalse(); style.setLinethrough(true); assertThat(style.isLinethrough()).isTrue(); style.setLinethrough(false); assertThat(style.isLinethrough()).isFalse(); } @Test public void testUnderline() { assertThat(style.isUnderline()).isFalse(); style.setUnderline(true); assertThat(style.isUnderline()).isTrue(); style.setUnderline(false); assertThat(style.isUnderline()).isFalse(); } @Test public void testFontFamily() { assertThat(style.getFontFamily()).isNull(); style.setFontFamily(FONT_FAMILY); assertThat(style.getFontFamily()).isEqualTo(FONT_FAMILY); style.setFontFamily(null); assertThat(style.getFontFamily()).isNull(); } @Test public void testColor() { assertThat(style.hasFontColor()).isFalse(); style.setFontColor(Color.BLACK); assertThat(style.getFontColor()).isEqualTo(BLACK); assertThat(style.hasFontColor()).isTrue(); } @Test public void testBackgroundColor() { assertThat(style.hasBackgroundColor()).isFalse(); style.setBackgroundColor(Color.BLACK); assertThat(style.getBackgroundColor()).isEqualTo(BLACK); assertThat(style.hasBackgroundColor()).isTrue(); } @Test public void testId() { assertThat(style.getId()).isNull(); style.setId(ID); assertThat(style.getId()).isEqualTo(ID); style.setId(null); assertThat(style.getId()).isNull(); } }
{ "content_hash": "da9ac276e499bc2cf3d64b7be7531398", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 99, "avg_line_length": 34.40425531914894, "alnum_prop": 0.7351061636775923, "repo_name": "KiminRyu/ExoPlayer", "id": "4c35e259ffeca9118d9475bfaebd02e8fbfb9a41", "size": "5470", "binary": false, "copies": "1", "ref": "refs/heads/dev-v2", "path": "library/core/src/test/java/com/google/android/exoplayer2/text/ttml/TtmlStyleTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "8885" }, { "name": "Java", "bytes": "2056672" }, { "name": "Makefile", "bytes": "7479" }, { "name": "Shell", "bytes": "5513" } ], "symlink_target": "" }
package androidx.core.view; import android.content.Context; import android.content.res.Resources; import android.os.Build; import android.util.Log; import android.util.TypedValue; import android.view.ViewConfiguration; import androidx.annotation.DoNotInline; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import java.lang.reflect.Method; /** * Helper for accessing features in {@link ViewConfiguration}. */ @SuppressWarnings("JavaReflectionMemberAccess") public final class ViewConfigurationCompat { private static final String TAG = "ViewConfigCompat"; private static Method sGetScaledScrollFactorMethod; static { if (Build.VERSION.SDK_INT == 25) { try { sGetScaledScrollFactorMethod = ViewConfiguration.class.getDeclaredMethod("getScaledScrollFactor"); } catch (Exception e) { Log.i(TAG, "Could not find method getScaledScrollFactor() on ViewConfiguration"); } } } /** * Call {@link ViewConfiguration#getScaledPagingTouchSlop()}. * * @deprecated Call {@link ViewConfiguration#getScaledPagingTouchSlop()} directly. * This method will be removed in a future release. */ @Deprecated public static int getScaledPagingTouchSlop(ViewConfiguration config) { return config.getScaledPagingTouchSlop(); } /** * Report if the device has a permanent menu key available to the user, in a backwards * compatible way. * * @deprecated Use {@link ViewConfiguration#hasPermanentMenuKey()} directly. */ @Deprecated public static boolean hasPermanentMenuKey(ViewConfiguration config) { return config.hasPermanentMenuKey(); } /** * @param config Used to get the scaling factor directly from the {@link ViewConfiguration}. * @param context Used to locate a resource value. * * @return Amount to scroll in response to a horizontal {@link MotionEventCompat#ACTION_SCROLL} * event. Multiply this by the event's axis value to obtain the number of pixels to be * scrolled. */ public static float getScaledHorizontalScrollFactor(@NonNull ViewConfiguration config, @NonNull Context context) { if (Build.VERSION.SDK_INT >= 26) { return Api26Impl.getScaledHorizontalScrollFactor(config); } else { return getLegacyScrollFactor(config, context); } } /** * @param config Used to get the scaling factor directly from the {@link ViewConfiguration}. * @param context Used to locate a resource value. * * @return Amount to scroll in response to a vertical {@link MotionEventCompat#ACTION_SCROLL} * event. Multiply this by the event's axis value to obtain the number of pixels to be * scrolled. */ public static float getScaledVerticalScrollFactor(@NonNull ViewConfiguration config, @NonNull Context context) { if (Build.VERSION.SDK_INT >= 26) { return Api26Impl.getScaledVerticalScrollFactor(config); } else { return getLegacyScrollFactor(config, context); } } @SuppressWarnings("ConstantConditions") private static float getLegacyScrollFactor(ViewConfiguration config, Context context) { if (Build.VERSION.SDK_INT >= 25 && sGetScaledScrollFactorMethod != null) { try { return (int) sGetScaledScrollFactorMethod.invoke(config); } catch (Exception e) { Log.i(TAG, "Could not find method getScaledScrollFactor() on ViewConfiguration"); } } // Fall back to pre-API-25 behavior. TypedValue outValue = new TypedValue(); if (context.getTheme().resolveAttribute( android.R.attr.listPreferredItemHeight, outValue, true)) { return outValue.getDimension(context.getResources().getDisplayMetrics()); } return 0; } /** * @param config Used to get the hover slop directly from the {@link ViewConfiguration}. * * @return The hover slop value. */ public static int getScaledHoverSlop(@NonNull ViewConfiguration config) { if (Build.VERSION.SDK_INT >= 28) { return Api28Impl.getScaledHoverSlop(config); } return config.getScaledTouchSlop() / 2; } /** * Check if shortcuts should be displayed in menus. * * @return {@code True} if shortcuts should be displayed in menus. */ public static boolean shouldShowMenuShortcutsWhenKeyboardPresent( @NonNull ViewConfiguration config, @NonNull Context context) { if (Build.VERSION.SDK_INT >= 28) { return Api28Impl.shouldShowMenuShortcutsWhenKeyboardPresent(config); } final Resources res = context.getResources(); final int platformResId = res.getIdentifier( "config_showMenuShortcutsWhenKeyboardPresent", "bool", "android"); return platformResId != 0 && res.getBoolean(platformResId); } private ViewConfigurationCompat() { } @RequiresApi(26) static class Api26Impl { private Api26Impl() { // This class is not instantiable. } @DoNotInline static float getScaledHorizontalScrollFactor(ViewConfiguration viewConfiguration) { return viewConfiguration.getScaledHorizontalScrollFactor(); } @DoNotInline static float getScaledVerticalScrollFactor(ViewConfiguration viewConfiguration) { return viewConfiguration.getScaledVerticalScrollFactor(); } } @RequiresApi(28) static class Api28Impl { private Api28Impl() { // This class is not instantiable. } @DoNotInline static int getScaledHoverSlop(ViewConfiguration viewConfiguration) { return viewConfiguration.getScaledHoverSlop(); } @DoNotInline static boolean shouldShowMenuShortcutsWhenKeyboardPresent( ViewConfiguration viewConfiguration) { return viewConfiguration.shouldShowMenuShortcutsWhenKeyboardPresent(); } } }
{ "content_hash": "9cedd5ec75e61e310f94a0da85c83c32", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 99, "avg_line_length": 35.258426966292134, "alnum_prop": 0.6574251115360102, "repo_name": "androidx/androidx", "id": "628a379af96347fa6af131eeda133e885c377a7a", "size": "6891", "binary": false, "copies": "3", "ref": "refs/heads/androidx-main", "path": "core/core/src/main/java/androidx/core/view/ViewConfigurationCompat.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "263978" }, { "name": "ANTLR", "bytes": "19860" }, { "name": "C", "bytes": "4764" }, { "name": "C++", "bytes": "9020585" }, { "name": "CMake", "bytes": "11999" }, { "name": "HTML", "bytes": "21175" }, { "name": "Java", "bytes": "59499889" }, { "name": "JavaScript", "bytes": "1343" }, { "name": "Kotlin", "bytes": "66123157" }, { "name": "Python", "bytes": "292398" }, { "name": "Shell", "bytes": "167367" }, { "name": "Swift", "bytes": "3153" }, { "name": "TypeScript", "bytes": "7599" } ], "symlink_target": "" }
package org.apache.shardingsphere.example.db.discovery.spring.namespace.jdbc.entity; import java.io.Serializable; public class Address implements Serializable { private static final long serialVersionUID = 4743102234543827855L; private Long addressId; private String addressName; public Long getAddressId() { return addressId; } public void setAddressId(Long addressId) { this.addressId = addressId; } public String getAddressName() { return addressName; } public void setAddressName(String addressName) { this.addressName = addressName; } @Override public String toString() { return String.format("address_id: %s, address_name: %s", addressId, addressName); } }
{ "content_hash": "ee66e610932b83f9176c86623227ce20", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 89, "avg_line_length": 22.942857142857143, "alnum_prop": 0.6612702366127023, "repo_name": "apache/incubator-shardingsphere", "id": "e347f9be6fd700f50ee96a0c254ca9944449455c", "size": "1604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/shardingsphere-sample/shardingsphere-example-generated/shardingsphere-jdbc-sample/shardingsphere-jdbc-memory-local-db-discovery-spring-namespace-jdbc-example/src/main/java/org/apache/shardingsphere/example/db/discovery/spring/namespace/jdbc/entity/Address.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "269258" }, { "name": "Batchfile", "bytes": "3280" }, { "name": "CSS", "bytes": "2842" }, { "name": "Dockerfile", "bytes": "1485" }, { "name": "HTML", "bytes": "2146" }, { "name": "Java", "bytes": "7542761" }, { "name": "JavaScript", "bytes": "92884" }, { "name": "Shell", "bytes": "9837" }, { "name": "TSQL", "bytes": "68705" }, { "name": "Vue", "bytes": "81855" } ], "symlink_target": "" }
<!DOCTYPE html> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <link rel="stylesheet" href="style/global.css"> <title>This is demo</title> </head> <body> <h1> hello world </h1> <script src="lib/require.js" data-main="src/main.js"></script> </body>
{ "content_hash": "6d78bb6932b6eafd994e1acec867693f", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 90, "avg_line_length": 24.714285714285715, "alnum_prop": 0.638728323699422, "repo_name": "vastwu/vast-project", "id": "1dac343e75a920083fcccf851da752a3c938e936", "size": "346", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/demo/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2991" }, { "name": "HTML", "bytes": "346" }, { "name": "JavaScript", "bytes": "16458" }, { "name": "Shell", "bytes": "143" } ], "symlink_target": "" }
.class Lcom/android/server/NsdService$NsdStateMachine; .super Lcom/android/internal/util/StateMachine; .source "NsdService.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lcom/android/server/NsdService; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x2 name = "NsdStateMachine" .end annotation .annotation system Ldalvik/annotation/MemberClasses; value = { Lcom/android/server/NsdService$NsdStateMachine$DefaultState;, Lcom/android/server/NsdService$NsdStateMachine$DisabledState;, Lcom/android/server/NsdService$NsdStateMachine$EnabledState; } .end annotation # instance fields .field private final mDefaultState:Lcom/android/server/NsdService$NsdStateMachine$DefaultState; .field private final mDisabledState:Lcom/android/server/NsdService$NsdStateMachine$DisabledState; .field private final mEnabledState:Lcom/android/server/NsdService$NsdStateMachine$EnabledState; .field final synthetic this$0:Lcom/android/server/NsdService; # direct methods .method static synthetic -get0(Lcom/android/server/NsdService$NsdStateMachine;)Lcom/android/server/NsdService$NsdStateMachine$DisabledState; .locals 1 iget-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDisabledState:Lcom/android/server/NsdService$NsdStateMachine$DisabledState; return-object v0 .end method .method static synthetic -get1(Lcom/android/server/NsdService$NsdStateMachine;)Lcom/android/server/NsdService$NsdStateMachine$EnabledState; .locals 1 iget-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mEnabledState:Lcom/android/server/NsdService$NsdStateMachine$EnabledState; return-object v0 .end method .method constructor <init>(Lcom/android/server/NsdService;Ljava/lang/String;)V .locals 2 iput-object p1, p0, Lcom/android/server/NsdService$NsdStateMachine;->this$0:Lcom/android/server/NsdService; invoke-direct {p0, p2}, Lcom/android/internal/util/StateMachine;-><init>(Ljava/lang/String;)V new-instance v0, Lcom/android/server/NsdService$NsdStateMachine$DefaultState; invoke-direct {v0, p0}, Lcom/android/server/NsdService$NsdStateMachine$DefaultState;-><init>(Lcom/android/server/NsdService$NsdStateMachine;)V iput-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDefaultState:Lcom/android/server/NsdService$NsdStateMachine$DefaultState; new-instance v0, Lcom/android/server/NsdService$NsdStateMachine$DisabledState; invoke-direct {v0, p0}, Lcom/android/server/NsdService$NsdStateMachine$DisabledState;-><init>(Lcom/android/server/NsdService$NsdStateMachine;)V iput-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDisabledState:Lcom/android/server/NsdService$NsdStateMachine$DisabledState; new-instance v0, Lcom/android/server/NsdService$NsdStateMachine$EnabledState; invoke-direct {v0, p0}, Lcom/android/server/NsdService$NsdStateMachine$EnabledState;-><init>(Lcom/android/server/NsdService$NsdStateMachine;)V iput-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mEnabledState:Lcom/android/server/NsdService$NsdStateMachine$EnabledState; iget-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDefaultState:Lcom/android/server/NsdService$NsdStateMachine$DefaultState; invoke-virtual {p0, v0}, Lcom/android/server/NsdService$NsdStateMachine;->addState(Lcom/android/internal/util/State;)V iget-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDisabledState:Lcom/android/server/NsdService$NsdStateMachine$DisabledState; iget-object v1, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDefaultState:Lcom/android/server/NsdService$NsdStateMachine$DefaultState; invoke-virtual {p0, v0, v1}, Lcom/android/server/NsdService$NsdStateMachine;->addState(Lcom/android/internal/util/State;Lcom/android/internal/util/State;)V iget-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mEnabledState:Lcom/android/server/NsdService$NsdStateMachine$EnabledState; iget-object v1, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDefaultState:Lcom/android/server/NsdService$NsdStateMachine$DefaultState; invoke-virtual {p0, v0, v1}, Lcom/android/server/NsdService$NsdStateMachine;->addState(Lcom/android/internal/util/State;Lcom/android/internal/util/State;)V invoke-static {p1}, Lcom/android/server/NsdService;->-wrap2(Lcom/android/server/NsdService;)Z move-result v0 if-eqz v0, :cond_0 iget-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mEnabledState:Lcom/android/server/NsdService$NsdStateMachine$EnabledState; invoke-virtual {p0, v0}, Lcom/android/server/NsdService$NsdStateMachine;->setInitialState(Lcom/android/internal/util/State;)V :goto_0 const/16 v0, 0x19 invoke-virtual {p0, v0}, Lcom/android/server/NsdService$NsdStateMachine;->setLogRecSize(I)V invoke-direct {p0}, Lcom/android/server/NsdService$NsdStateMachine;->registerForNsdSetting()V return-void :cond_0 iget-object v0, p0, Lcom/android/server/NsdService$NsdStateMachine;->mDisabledState:Lcom/android/server/NsdService$NsdStateMachine$DisabledState; invoke-virtual {p0, v0}, Lcom/android/server/NsdService$NsdStateMachine;->setInitialState(Lcom/android/internal/util/State;)V goto :goto_0 .end method .method private registerForNsdSetting()V .locals 4 new-instance v0, Lcom/android/server/NsdService$NsdStateMachine$1; invoke-virtual {p0}, Lcom/android/server/NsdService$NsdStateMachine;->getHandler()Landroid/os/Handler; move-result-object v1 invoke-direct {v0, p0, v1}, Lcom/android/server/NsdService$NsdStateMachine$1;-><init>(Lcom/android/server/NsdService$NsdStateMachine;Landroid/os/Handler;)V iget-object v1, p0, Lcom/android/server/NsdService$NsdStateMachine;->this$0:Lcom/android/server/NsdService; invoke-static {v1}, Lcom/android/server/NsdService;->-get1(Lcom/android/server/NsdService;)Landroid/content/Context; move-result-object v1 invoke-virtual {v1}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver; move-result-object v1 const-string/jumbo v2, "nsd_on" invoke-static {v2}, Landroid/provider/Settings$Global;->getUriFor(Ljava/lang/String;)Landroid/net/Uri; move-result-object v2 const/4 v3, 0x0 invoke-virtual {v1, v2, v3, v0}, Landroid/content/ContentResolver;->registerContentObserver(Landroid/net/Uri;ZLandroid/database/ContentObserver;)V return-void .end method # virtual methods .method protected getWhatToString(I)Ljava/lang/String; .locals 1 invoke-static {p1}, Landroid/net/nsd/NsdManager;->nameOf(I)Ljava/lang/String; move-result-object v0 return-object v0 .end method
{ "content_hash": "38809f60ba82acab7ddd54e989f37a78", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 159, "avg_line_length": 41.548780487804876, "alnum_prop": 0.7857352509539184, "repo_name": "BatMan-Rom/ModdedFiles", "id": "c04a08d90db275bf2d59680752d71a046cdacca4", "size": "6814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services.jar.out/smali/com/android/server/NsdService$NsdStateMachine.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
title: ahp30 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: p30 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
{ "content_hash": "a6138a45a7dba8592defeba3bdb975e3", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 22.333333333333332, "alnum_prop": 0.6656716417910448, "repo_name": "pblack/kaldi-hugo-cms-template", "id": "a074a15c8ad71aa00b12df3c96467b9b32229abf", "size": "339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/content/pages2/ahp30.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "94394" }, { "name": "HTML", "bytes": "18889" }, { "name": "JavaScript", "bytes": "10014" } ], "symlink_target": "" }
package org.fxapps.bpms.local.bc; import java.io.IOException; import java.io.InputStream; import org.drools.core.io.impl.UrlResource; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieModule; import org.kie.api.builder.KieRepository; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * * Fire all rules of a kjar created in BRMS and available in its maven repository. <br /> * If the BRMS is in a remote server, make sure to update your maven configuration to point to its repository. <br /> * To have access to the facts or events definition present on this kjar declare a dependency to this module in your pom.xml * @author wsiqueir * */ public class MavenArtifactTest { // We could instead load the URL use the GAV of the artifact and use KieScanner to load it private static final String PASSWORD = "redhat2014!"; private static final String USER = "jesuino"; private static final String URL = "http://localhost:8080/business-central/maven2/org/kie/example/project1/1.0/project1-1.0.jar"; @Test public void doTest() throws IOException { KieServices ks = KieServices.Factory.get(); KieRepository kr = ks.getRepository(); UrlResource urlResource = (UrlResource) ks.getResources().newUrlResource(URL); urlResource.setUsername(USER); urlResource.setPassword(PASSWORD); urlResource.setBasicAuthentication("enabled"); InputStream is = urlResource.getInputStream(); KieModule kModule = kr.addKieModule(ks.getResources().newInputStreamResource(is)); KieContainer kc = ks.newKieContainer(kModule.getReleaseId()); // This fact was created using Data Modeller in business central // Product p = new Product(); // p.setName("Table"); // p.setPrice(500f); KieSession kSession = kc.newKieSession(); // kSession.insert(p); kSession.fireAllRules(); } }
{ "content_hash": "594da107a8c88cd2ad5e27b68c944f03", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 129, "avg_line_length": 37.97959183673469, "alnum_prop": 0.7571198280494358, "repo_name": "jesuino/bpms6-examples", "id": "e527ff215b216bf792ed21aa42a34a7bddb3c91f", "size": "1861", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bpms62/bpms62-local-api/src/test/java/org/fxapps/bpms/local/bc/MavenArtifactTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "218130" } ], "symlink_target": "" }
(function() { /* * Utils * Let's start by defining some useful functions */ var Utils = {}; /* * Utils.cloneObject * Create an immutable copy of a given object */ Utils.cloneObject = function(object) { var result = {}; for(var key in object) { if(object.hasOwnProperty(key)) { result[key] = object[key]; } } return result; }; /* * Utils.cloneLocation * Create an immutable copy of window.location */ Utils.cloneLocation = function() { var result = {}; var loc = window.location; /* None of window.location keys is owned by window.location, so no check here */ for(var key in loc) { result[key] = loc[key]; } return result; }; /* * Utils.compact * Remove "falsey" values from a given array */ Utils.compact = function(array) { if(typeof array.filter == "function") { return array.filter(function(item) { return item; }); } else { var result = []; for(var i = 0, l = array.length; i < l; i++) { if(array[i]) { result.push(array[i]); } } return result; } }; /* * Utils.extractParams * Return path parameters if the given splitted path does match the given splitted route. Return null otherwise. * ex: Utils.extractParams(["users", ":userId"])(["users", "john-smith"]) => {"userId": "john-smith"} */ Utils.extractParams = function(routeSegments) { return function(pathSegments) { if(routeSegments.length != pathSegments.length) { return null; } else { var params = {}; for(var i = 0, l = routeSegments.length; i < l; i++) { if(routeSegments[i][0] == ":") { params[routeSegments[i].substring(1)] = decodeURIComponent(pathSegments[i]); } else if(routeSegments[i] != pathSegments[i]) { return null; } } return params; } }; }; /* * s_history * Stream emitting history states */ var s_historyBus = new Bacon.Bus(); var s_history = Bacon.fromEventTarget(window, "popstate").merge(s_historyBus).map(function() { return { state: history.state, location: Utils.cloneLocation() }; }); /* * Bacon.history * Create a bacon property of the history state */ Bacon.history = s_history.toProperty({ state: history.state, location: Utils.cloneLocation() }); Bacon.history.pushState = function(stateObj, title, url) { history.pushState(stateObj, title, url); s_historyBus.push(); }; /* Push the initial state */ Bacon.history.pushState(null, null, window.location.href); /* * Bacon.fromRoutes * Return one bacon stream per defined route */ Bacon.fromRoutes = function(settings) { settings.routes = settings.routes || {}; var ready = (settings.ready || Bacon.constant(true)).toEventStream().skipWhile(function(value) { return value !== true; }).take(1); var routes = {}; var buses = {}; var streams = {}; var filters = {}; for(var name in settings.routes) { if(settings.routes.hasOwnProperty(name) && typeof settings.routes[name] == "string") { routes[name] = Utils.compact(settings.routes[name].split("/")); buses[name] = new Bacon.Bus(); filters[name] = Utils.extractParams(routes[name]); /* Prevent final user to push any data in the returned streams */ streams[name] = buses[name].map(function(value) { return value; }); } } /* Dedicate "errors" stream to 404 occurences */ var s_errors = new Bacon.Bus(); streams.errors = s_errors.map(function(value) { return value; }); ready.onValue(function(value) { Bacon.history.onValue(function(history) { var pathSegments = Utils.compact(history.location.pathname.split("/")); var result = Utils.cloneObject(history); for(var name in buses) { if(buses.hasOwnProperty(name)) { var params = filters[name](pathSegments); if(params) { result.params = params; buses[name].push(result); return; } } } s_errors.push(result); }); }); return streams; }; })();
{ "content_hash": "8ae755e6b7de4fb81bbad7a8882a981c", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 114, "avg_line_length": 24.44632768361582, "alnum_prop": 0.5763808643401895, "repo_name": "rbelouin/bacon-routes", "id": "6501246d6b3f824b29495d93d8c8113ebe616f28", "size": "4327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bacon-routes.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "11320" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace LocalReportsEngine.RdlElements { public class RdlDataSource { [XmlAttribute] public string Name { get; set; } public string Transaction { get; set; } public string DataSourceReference { get; set; } public RdlConnectionProperties ConnectionProperties { get; set; } } }
{ "content_hash": "b068546b853a3123a0b337b0389fa62d", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 73, "avg_line_length": 22.65, "alnum_prop": 0.6931567328918322, "repo_name": "taspeotis/LocalReportsEngine", "id": "dd7e7048632951b2b7f447cd1ffabfb57b2cad05", "size": "455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LocalReportsEngine/RdlElements/RdlDataSource.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "45678" } ], "symlink_target": "" }
console.log(libraryName)
{ "content_hash": "ef133310c80e4a0991a1a72dcfa79f57", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 24, "avg_line_length": 25, "alnum_prop": 0.84, "repo_name": "kiriakosv/learn-vanilla-javascript", "id": "6de483bf47f53fc3de9695702f39c4fcf68ab0e6", "size": "25", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework-asides/framework-aside-1/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1683" }, { "name": "JavaScript", "bytes": "65932" } ], "symlink_target": "" }
package graph import "fmt" type Node interface { ID() int Edges() []Edge Degree() int Neighbors(EdgeFilter) []Node Hops(EdgeFilter) []*Hop add(Edge) drop(Edge) dropAll() index() int setIndex(int) setID(int) } var _ Node = (*node)(nil) // NodeFilter is a function type used for assessment of nodes during graph traversal. type NodeFilter func(Node) bool // A Node is a node in a graph. type node struct { id int i int edges Edges } // newNode creates a new *Nodes with ID id. Nodes should only ever exist in the context of a // graph, so this is not a public function. func newNode(id int) Node { return &node{ id: id, } } // A Hop is an edge/node pair where the edge leads to the node from a neighbor. type Hop struct { Edge Edge Node Node } // ID returns the id of a node. func (n *node) ID() int { return n.id } // Edges returns a slice of edges that are incident on the node. func (n *node) Edges() []Edge { if len(n.edges) == 0 { return nil } return n.edges } // Degree returns the number of incident edges on a node. Looped edges are counted at both ends. func (n *node) Degree() int { l := 0 for _, e := range n.edges { if e.Head() == e.Tail() { l++ } } return l + len(n.edges) } // Neighbors returns a slice of nodes that share an edge with the node. Multiply connected nodes are // repeated in the slice. If the node is n-connected it will be included in the slice, potentially // repeatedly if there are multiple n-connecting edges. If ef is nil all edges are included. func (n *node) Neighbors(ef EdgeFilter) []Node { var nodes []Node for _, e := range n.edges { if ef == nil || ef(e) { if a := e.Tail(); a.ID() == n.ID() { nodes = append(nodes, e.Head()) } else { nodes = append(nodes, a) } } } return nodes } // Hops has essentially the same functionality as Neighbors with the exception that the connecting // edge is also returned. func (n *node) Hops(ef EdgeFilter) []*Hop { var h []*Hop for _, e := range n.edges { if ef == nil || ef(e) { if a := e.Tail(); a.ID() == n.ID() { h = append(h, &Hop{e, e.Head()}) } else { h = append(h, &Hop{e, a}) } } } return h } func (n *node) add(e Edge) { n.edges = append(n.edges, e) } func (n *node) dropAll() { for i := range n.edges { n.edges[i] = nil } n.edges = n.edges[:0] } func (n *node) drop(e Edge) { for i := 0; i < len(n.edges); { if n.edges[i] == e { n.edges = n.edges.delFromNode(i) break // assumes e has not been added more than once - this should not happen, but we don't check for it } else { i++ } } } func (n *node) setID(id int) { n.id = id } func (n *node) setIndex(i int) { n.i = i } func (n *node) index() int { return n.i } func (n *node) String() string { return fmt.Sprintf("%d:%v", n.id, n.edges) } // Nodes is a collection of nodes. type Nodes []Node // BuildUndirected creates a new Undirected graph using nodes and edges specified by the // set of nodes in the receiver. If edges of nodes in the receiver connect to nodes that are not, these extra nodes // will be included in the resulting graph. If compact is set to true, edge IDs are chosen to minimize // space consumption, but breaking edge ID consistency between the new graph and the original. func (ns Nodes) BuildUndirected(compact bool) (*Undirected, error) { seen := make(map[Edge]struct{}) g := NewUndirected() for _, n := range ns { g.AddID(n.ID()) for _, e := range n.Edges() { if _, ok := seen[e]; ok { continue } seen[e] = struct{}{} u, v := e.Nodes() uid, vid := u.ID(), v.ID() if uid < 0 || vid < 0 { return nil, NodeIDOutOfRange } g.AddID(uid) g.AddID(vid) var ne Edge if compact { ne = g.newEdge(g.nodes[uid], g.nodes[vid]) } else { ne = g.newEdgeKeepID(e.ID(), g.nodes[uid], g.nodes[vid]) } g.nodes[uid].add(ne) if vid != uid { g.nodes[vid].add(ne) } } } return g, nil } func (ns Nodes) delFromGraph(i int) Nodes { ns[i], ns[len(ns)-1] = ns[len(ns)-1], ns[i] ns[i].setIndex(i) ns[len(ns)-1].setIndex(-1) return ns[:len(ns)-1] }
{ "content_hash": "e232dbe25ebf68667ffc41793beb3d00", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 115, "avg_line_length": 23.352272727272727, "alnum_prop": 0.6253041362530414, "repo_name": "biogo/graph", "id": "1a829441aee9515300f03ec3c9b8685b6130e646", "size": "4276", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Go", "bytes": "43869" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_inner_course_detail" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/title_inner_course_post" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/selectableItemBackground" android:clickable="true" android:drawableLeft="@drawable/ic_chevron_right_black_24dp" android:drawablePadding="4dip" android:paddingBottom="10dp" android:paddingLeft="20dp" android:paddingRight="20dp" android:paddingTop="6dp" android:textColor="@color/color_accent" android:textSize="15sp" android:textStyle="italic" android:visibility="gone" /> <LinearLayout android:id="@+id/layout_comment_inner_course_post" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingLeft="20dp" android:paddingRight="20dp" android:visibility="gone"> <org.sufficientlysecure.htmltextview.HtmlTextView android:id="@+id/comment_inner_course_post" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none" /> </LinearLayout> </LinearLayout>
{ "content_hash": "0cc6efebbaf5d8459e973ef66c16c8c5", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 72, "avg_line_length": 37.19512195121951, "alnum_prop": 0.659016393442623, "repo_name": "mgilangjanuar/GoSCELE", "id": "3c494b2669064f19ca89fa3e03ec599cabaa75ba", "size": "1525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/layout_inner_course_detail.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "221121" } ], "symlink_target": "" }
import os from headref import Head from git.util import ( join, join_path ) __all__ = ["RemoteReference"] class RemoteReference(Head): """Represents a reference pointing to a remote head.""" __slots__ = tuple() _common_path_default = Head._remote_common_path_default @classmethod def iter_items(cls, repo, common_path = None, remote=None): """Iterate remote references, and if given, constrain them to the given remote""" common_path = common_path or cls._common_path_default if remote is not None: common_path = join_path(common_path, str(remote)) # END handle remote constraint return super(RemoteReference, cls).iter_items(repo, common_path) @classmethod def create(cls, *args, **kwargs): """Used to disable this method""" raise TypeError("Cannot explicitly create remote references") @classmethod def delete(cls, repo, *refs, **kwargs): """Delete the given remote references. :note: kwargs are given for compatability with the base class method as we should not narrow the signature.""" repo.git.branch("-d", "-r", *refs) # the official deletion method will ignore remote symbolic refs - these # are generally ignored in the refs/ folder. We don't though # and delete remainders manually for ref in refs: try: os.remove(join(repo.git_dir, ref.path)) except OSError: pass # END for each ref
{ "content_hash": "64b35e16a9f1b4fb77d81bd85827c1e1", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 83, "avg_line_length": 29.617021276595743, "alnum_prop": 0.6968390804597702, "repo_name": "Conjuro/GitPython", "id": "d7bfc3e0f0ff71883584488ec16aa126e3df5a43", "size": "1392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "refs/remote.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "76908" }, { "name": "Python", "bytes": "785718" }, { "name": "Ruby", "bytes": "46005" } ], "symlink_target": "" }
@interface OrderViewController : UIViewController @property(nonatomic,assign)NSInteger index; @end
{ "content_hash": "d1522e86b612cd7d6d5612dc81636abf", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 49, "avg_line_length": 14.714285714285714, "alnum_prop": 0.8155339805825242, "repo_name": "18703212007/pjYiPinTongHang", "id": "c7a3284d516a371abb343d10a9bc678980cd01ea", "size": "274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "YiPinTongHang /YiPinTongXing/PersonalCenter/Controller/OrderViewController.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "30543" }, { "name": "DTrace", "bytes": "412" }, { "name": "HTML", "bytes": "4556" }, { "name": "Objective-C", "bytes": "2922831" }, { "name": "Shell", "bytes": "8924" } ], "symlink_target": "" }
package com.amazonaws.services.serverlessapplicationrepository.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.serverlessapplicationrepository.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ParameterDefinition JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ParameterDefinitionJsonUnmarshaller implements Unmarshaller<ParameterDefinition, JsonUnmarshallerContext> { public ParameterDefinition unmarshall(JsonUnmarshallerContext context) throws Exception { ParameterDefinition parameterDefinition = new ParameterDefinition(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("allowedPattern", targetDepth)) { context.nextToken(); parameterDefinition.setAllowedPattern(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("allowedValues", targetDepth)) { context.nextToken(); parameterDefinition.setAllowedValues(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)) .unmarshall(context)); } if (context.testExpression("constraintDescription", targetDepth)) { context.nextToken(); parameterDefinition.setConstraintDescription(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("defaultValue", targetDepth)) { context.nextToken(); parameterDefinition.setDefaultValue(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("description", targetDepth)) { context.nextToken(); parameterDefinition.setDescription(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("maxLength", targetDepth)) { context.nextToken(); parameterDefinition.setMaxLength(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("maxValue", targetDepth)) { context.nextToken(); parameterDefinition.setMaxValue(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("minLength", targetDepth)) { context.nextToken(); parameterDefinition.setMinLength(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("minValue", targetDepth)) { context.nextToken(); parameterDefinition.setMinValue(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("name", targetDepth)) { context.nextToken(); parameterDefinition.setName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("noEcho", targetDepth)) { context.nextToken(); parameterDefinition.setNoEcho(context.getUnmarshaller(Boolean.class).unmarshall(context)); } if (context.testExpression("referencedByResources", targetDepth)) { context.nextToken(); parameterDefinition.setReferencedByResources(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)) .unmarshall(context)); } if (context.testExpression("type", targetDepth)) { context.nextToken(); parameterDefinition.setType(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return parameterDefinition; } private static ParameterDefinitionJsonUnmarshaller instance; public static ParameterDefinitionJsonUnmarshaller getInstance() { if (instance == null) instance = new ParameterDefinitionJsonUnmarshaller(); return instance; } }
{ "content_hash": "2537dd1694cb69404d2e4a578c1524e9", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 136, "avg_line_length": 46.40869565217391, "alnum_prop": 0.6128911373430767, "repo_name": "aws/aws-sdk-java", "id": "511d4e6d82111b1c018f1c5288fbd9a754794bc8", "size": "5917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-serverlessapplicationrepository/src/main/java/com/amazonaws/services/serverlessapplicationrepository/model/transform/ParameterDefinitionJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// DOMContentLoaded is fired once the document has been loaded and parsed, // but without waiting for other external resources to load (css/images/etc) // That makes the app more responsive and perceived as faster. // https://developer.mozilla.org/Web/Reference/Events/DOMContentLoaded window.addEventListener('DOMContentLoaded', function() { // We'll ask the browser to use strict code to help us catch errors earlier. // https://developer.mozilla.org/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode 'use strict'; var translate = navigator.mozL10n.get; // We want to wait until the localisations library has loaded all the strings. // So we'll tell it to let us know once it's ready. navigator.mozL10n.once(start); // --- function start() { /*var message = document.getElementById('message'); message.textContent = translate('message');*/ } //////////////// https://github.com/mozilla-b2g/gaia/blob/5709345df31c5fab5cc5c051d591d4e76ca4f706/apps/settings/js/panels/app_permissions_list/app_permissions_list.js#L247 var _getBestIconURL = function pl__get_best_icon_URL(app, icons) { if (!icons || !Object.keys(icons).length) { return '../style/images/default.png'; } // The preferred size is 30 by the default. If we use HDPI device, we may // use the image larger than 30 * 1.5 = 45 pixels. var preferredIconSize = 30 * (window.devicePixelRatio || 1); var preferredSize = Number.MAX_VALUE; var max = 0; for (var size in icons) { size = parseInt(size, 10); if (size > max) { max = size; } if (size >= preferredIconSize && size < preferredSize) { preferredSize = size; } } // If there is an icon matching the preferred size, we return the result, // if there isn't, we will return the maximum available size. if (preferredSize === Number.MAX_VALUE) { preferredSize = max; } var url = icons[preferredSize]; if (url) { return !(/^(http|https|data):/.test(url)) ? app.origin + url : url; } else { return '../style/images/default.png'; } } /////////////////// var setPermission = function (appName, permName, value) { var apps_request = navigator.mozApps.mgmt.getAll(); var permission = navigator.mozPermissionSettings; console.log("Setting permission...", permName, appName, value); apps_request.onsuccess = function (evt) { var appsArr = evt.target.result; for (var app of appsArr) { if (app.manifest.name === appName) { console.log("Found the app!", app.manifest.name, "==", appName, app); if (permission.isExplicit(permName, app.manifestURL, app.origin, false)) { // Let's ask the user for all permissions requested by the application try { //XXX still throws sometimes :-( // we can't return because onsuccess event... permission.set(permName, value, app.manifestURL, app.origin, false); } catch(e) { console.warn("Uh, could not set the permission...", e); }; } else { console.warn("This is an implicit permission. We can't change it!"); console.warn(permName, app.manifestURL, app.origin); } } } } }; var listPermissions = (function listPermissions() { // via https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API // Let's check all installed apps var apps_request = navigator.mozApps.mgmt.getAll(); var applist = document.getElementById("applist"); apps_request.onsuccess = function (evt) { var appsArr = evt.target.result; var permission = navigator.mozPermissionSettings; // Let's check the permission of each app appsArr.forEach(function (app) { var permName, appName = app.manifest.name; var app_entry = document.createElement("li"); var app_link = document.createElement("a"); var app_icon_container = document.createElement("aside"); var app_icon = document.createElement("img"); app_icon.src = _getBestIconURL(app, app.manifest.icons) app_icon_container.appendChild(app_icon); var app_title = document.createElement("p"); app_link.appendChild(app_icon_container); app_link.appendChild(app_title); app_entry.appendChild(app_link); app_title.textContent = appName; app_link.addEventListener("click", (function() { var app_view = document.getElementById("app-view-name"); app_view.textContent = this.manifest.name; var perm_list = document.getElementById("permlist"); for (permName in this.manifest.permissions) { // Let's get the current permission for each permission request by the application var p = permission.get(permName, this.manifestURL, this.origin, false); var perm_entry = document.createElement("li"); var perm_link = document.createElement("button"); var perm_icon_container = document.createElement("aside"); var perm_icon = document.createElement("img"); if (["allow", "prompt", "deny", "unknown"].indexOf(p) != -1) { perm_icon.src = "/img/" + p + ".png" } perm_icon_container.appendChild(perm_icon) perm_link.appendChild(perm_icon_container); perm_entry.dataset.p = p; if (p !== "unknown") { perm_link.addEventListener("click", function () { // invoke select var select = document.getElementById("change-perms"); select.dataset.permName = permName; select.dataset.appName = appName; var current = select.querySelector('[value="' + this.parentNode.dataset.p + '"]'); current.setAttribute("selected", true); select.focus(); select.onchange = function() { setPermission(this.dataset.appName, this.dataset.permName, this.value); // change image var entries = perm_list.querySelectorAll("p"); for (var item of entries) { if (item.textContent == this.dataset.permName) { item.previousSibling.querySelector("img").src = "/img/" + this.value + ".png"; break; } } } }) } else { perm_link.addEventListener("click", function() { alert("This permission is currently set to 'unknown'. For safety reasons, we prevent you from changing it :("); }) } /*var attributeSafeName = app.manifest.name.replace(/\W+/g, '_'); var perm_label = document.createElement('label'); perm_label.setAttribute("class", "pack-checkbox danger"); var perm_checkbox = document.createElement('input'); perm_checkbox.setAttribute("id", "checkbox-"+attributeSafeName); perm_checkbox.setAttribute("type", "checkbox"); perm_checkbox.setAttribute("checked", "false"); //perm_checkbox.checked = false; if (p == "allow") { perm_checkbox.checked = true; } else if (p == "deny") { perm_checkbox.checked = false; } else if (p == "prompt") { perm_checkbox.indeterminate = true; } perm_label.appendChild(perm_checkbox); var perm_span = document.createElement('span'); perm_label.appendChild(perm_span); perm_entry.appendChild(perm_label);*/ perm_entry.appendChild(perm_link); var perm_value = document.createElement("p"); perm_value.textContent = permName; perm_link.appendChild(perm_value); perm_list.appendChild(perm_entry); } scrolled = window.scrollY; scrollTo(0,0); // Show app view document.getElementById("app-view").classList.add("move-in"); document.getElementById("app-view").classList.remove("move-out"); document.getElementById("list-view").style.display = "none"; }).bind(app)) applist.appendChild(app_entry); }); } }); listPermissions(); //document.getElementById("btnreload").addEventListener("click", function() { listPermissions() }); }); /* app settings view show/hide */ // Close app view var scrolled; var appViewClose = document.getElementById("close-app"); appViewClose.addEventListener("click", function () { document.getElementById("permlist").innerHTML = ""; document.getElementById("app-view").classList.remove("move-in"); document.getElementById("app-view").classList.add("move-out"); document.getElementById("list-view").style.display = "block"; scrollTo(0, scrolled); })
{ "content_hash": "0240323bb6531b630f0f7a8508bf0237", "timestamp": "", "source": "github", "line_count": 220, "max_line_length": 174, "avg_line_length": 41.03636363636364, "alnum_prop": 0.601019051838724, "repo_name": "mozfreddyb/permissions-app", "id": "bd2ade419a65f2522241a5316916d0a815a733c0", "size": "9028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/app.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "15876" }, { "name": "JavaScript", "bytes": "46198" } ], "symlink_target": "" }
require 'spec_helper' describe command('ruby --version') do its(:exit_status) { should eq 0 } end describe command('gem --version') do its(:exit_status) { should eq 0 } end
{ "content_hash": "470753c3cdfc1837cdbf3aca100785e4", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 37, "avg_line_length": 19.88888888888889, "alnum_prop": 0.6815642458100558, "repo_name": "njam/vagrant-boxes", "id": "90b95720b6d004de17d2e019baedab377de6e37d", "size": "179", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/ruby.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Puppet", "bytes": "301" }, { "name": "Ruby", "bytes": "13302" }, { "name": "Shell", "bytes": "4013" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; public class LifeController : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
{ "content_hash": "363cca5f2a58149b05a78dfa0db587bf", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 45, "avg_line_length": 14.066666666666666, "alnum_prop": 0.6872037914691943, "repo_name": "unstablesun/LifeX", "id": "434111c74233b437638099e3d3d3dbef6bb3775c", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/LifeController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "7610" } ], "symlink_target": "" }
module IndexOrderHelper def sortable_field(name, field, options = {}, html_options = {}) options.merge!({ :action => :index, :index_order_field => field.to_s, :index_order_direction => get_sortable_field_order(field.to_s)[:index_order_direction], :filter => @filter }) link_to(name, options, html_options) end private def get_sortable_field_order(field_name) order_hash = {:index_order_field => field_name} if @index_order_field == field_name order_hash[:index_order_direction] = (@index_order_direction == 'ASC' ? 'DESC' : 'ASC') else order_hash[:index_order_direction] = 'ASC' end order_hash end end
{ "content_hash": "70818a91b5a1411e407c1ae260fc3317", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 94, "avg_line_length": 29.04, "alnum_prop": 0.5922865013774105, "repo_name": "eLafo/sortable_index_filters", "id": "61b20111e8eb42d2b2b9d005f72d8d762889b0c9", "size": "726", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/index_order_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3426" } ], "symlink_target": "" }
{-# LANGUAGE DataKinds, ScopedTypeVariables, TypeFamilies, FlexibleContexts #-} module FRP.Basket.Signals.Switches where import Data.HList hiding ((#)) import FRP.Basket.Signals data Event e = Event e | NoEvent deriving (Show, Eq) {- | Whenever the signal e occurs the handler function is called for the return value. The handler and the signal have differing states and the switch keeps track of both. -} hSwitch :: forall s s' ss a b e n. (HSplitAt n ss s s', ss ~ HAppendListR s (HAppendListR s' '[]), HAppendFD s' '[] s', HAppendFD s s' ss) => Signal s a (b, Event e) -> Signal s' e b -> Signal ss a b hSwitch sf handler = Signal $ \t totalState a -> let splitIndex = Proxy :: Proxy n (sfst, handlerst) = hSplitAt splitIndex totalState ((b, ev), sfst') = runSignal sf t sfst a in case ev of NoEvent -> (b, hConcat $ hBuild sfst' handlerst) Event e -> let (b, handlerst') = runSignal handler t handlerst e in (b, hConcat $ hBuild sfst' handlerst') {- | Similar to a regular switch, but instead of having a signal function and a handler signal with differing state types, these are equivalent. In this case the state that the handler uses is the returned state of the original function call (sf) -} switch :: Signal s a (b, Event e) -> Signal s e b -> Signal s a b switch sf handler = Signal $ \t s a -> let ((b, ev), s') = runSignal sf t s a in case ev of NoEvent -> (b, s') Event e -> runSignal handler t s' e {- | This function allows a 'regulator' to see the output of a signal along with it's internal state to perform some time of regulatory transformation on its output. -} hRegulator :: forall s s' ss a b c n. (HSplitAt n ss s s', ss ~ HAppendListR s (HAppendListR s' '[]), HAppendFD s' '[] s', HAppendFD s s' ss) => Signal s a b -> Signal s' (b, HList s) c -> Signal ss a c hRegulator sf regulator = Signal $ \t totalState a -> let splitIndex = Proxy :: Proxy n (sfState, rState) = hSplitAt splitIndex totalState (b, sfState') = runSignal sf t sfState a (c, rState') = runSignal regulator t rState (b, sfState') in (c, hConcat $ hBuild sfState' rState') {- | A regulator that compares the initial state of the Signal sf it regulates to sf's output -} regulator :: Signal s a b -> Signal s (b, HList s) c -> Signal s a c regulator sf regulator = Signal $ \t s a -> let (b, s') = runSignal sf t s a in runSignal regulator t s (b, s') parSwitch :: Signal s a (Either b c) -> Signal s b d -> Signal s c d -> Signal s a d parSwitch main left right = Signal $ \t s a -> let (r, s') = runSignal main t s a in case r of Left b -> runSignal left t s' b Right c -> runSignal right t s' c
{ "content_hash": "7d9a26a73303cd15076b6788272b03f1", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 100, "avg_line_length": 48.5, "alnum_prop": 0.5293078055964654, "repo_name": "jhstanton/Basket", "id": "cbb43d7a20e782bfbefe7610ff11e1001f186057", "size": "3395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/FRP/Basket/Signals/Switches.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "11433" } ], "symlink_target": "" }
VPRJCONV ;V4W/DLW,KRM/CJE -- Conversion routine to make conversions to JDS data that has changed ; QUIT ; Should not be called from the top ; ; This routine should be run at every site that was running JDS before the conversion to the new metastamp ; This routine makes extensive use of ^TMP. This is used as a temprory work place for conversions to happen ; If this process needs to be re-ran (due to a crash, etc). The data stored in ^TMP is important to keep around. ; This cannot be moved to process private globals. ; SYNCSTS ; Entry point for sync status metastamp conversion ; Convert the old sync status metastamp to the new one N STARTOD,STARTPAT,ENDTIME,TOTALTIME,ODTIME,ODAVG,PATTIME,PATAVG,I,J,PID,SITE,SOURCESTAMP,DOMAIN ; I $D(^VPRJSAVD) W "^VPRJSAVD is not empty, aborting!",! QUIT I $D(^VPRJSAVP) W "^VPRJSAVP is not empty, aborting!",! QUIT I $D(^VPRJSTMP) W "^VPRJSTMP is not empty, aborting!",! QUIT I '$D(^VPRSTATUSOD) W "^VPRSTATUSOD appears to be empty, aborting!",! QUIT I '$D(^VPRSTATUS) W "^VPRSTATUS appears to be empty, aborting!",! QUIT ; S STARTOD=$$SEC^XLFDT($H) ; Start conversion for operational data L +^VPRSTATUSOD:$G(^VPRCONFIG("timeout","odconvert"),5) E W "Could not obtain lock on ^VPRSTATUSOD, aborting!",! QUIT ; M ^VPRJSAVD=^VPRSTATUSOD W "Saved ^VPRSTATUSOD as ^VPRJSAVD",! ; S I=0 S (SITE,SOURCESTAMP,DOMAIN)="" ; F S SITE=$O(^VPRSTATUSOD(SITE)) Q:SITE="" D . S (SOURCESTAMP,DOMAIN)="" . W "Converting Site: "_SITE,! . TS (DOMAIN,SOURCESTAMP) . ; . S SOURCESTAMP=$O(^VPRSTATUSOD(SITE,SOURCESTAMP),-1) ; Get the newest source stamp . ; Check to make sure the source stamp is a 14 digit integer, otherwise quit this iteration . I SOURCESTAMP?14N S I=I+1 . E TRO D Q . . W "Site: "_SITE_" Invalid Sourcestamp found: ",SOURCESTAMP,! . . S ^VPRJCONV(SITE,"operational")="Invalid Sourcestamp found: "_SOURCESTAMP . ; . F S DOMAIN=$O(^VPRSTATUSOD(SITE,SOURCESTAMP,DOMAIN)) Q:DOMAIN="" D . . ; Delete the domain stored node . . K:$D(^VPRSTATUSOD(SITE,SOURCESTAMP,DOMAIN,SOURCESTAMP,"stored")) ^VPRSTATUSOD(SITE,SOURCESTAMP,DOMAIN,SOURCESTAMP,"stored") . ; . ZK:$D(^VPRSTATUSOD(SITE,SOURCESTAMP))#10 ^VPRSTATUSOD(SITE,SOURCESTAMP) ; Delete the data, but not the descendants . ; Save off newest metastamp to a temp global . M ^VPRJSTMP("VPRSTATUSOD",SITE)=^VPRSTATUSOD(SITE,SOURCESTAMP) . S ^VPRJSTMP("VPRSTATUSOD",SITE,"stampTime")=SOURCESTAMP . K:$D(^VPRSTATUSOD(SITE)) ^VPRSTATUSOD(SITE) . M ^VPRSTATUSOD(SITE)=^VPRJSTMP("VPRSTATUSOD",SITE) . ; . TC ; K:$D(^VPRJSTMP("VPRSTATUSOD")) ^VPRJSTMP("VPRSTATUSOD") ; L -^VPRSTATUSOD ; S STARTPAT=$$SEC^XLFDT($H) ; Start conversion for patient data L +^VPRSTATUS:$G(^VPRCONFIG("timeout","ptconvert"),5) E W "Could not obtain lock on ^VPRSTATUS, aborting!",! QUIT ; M ^VPRJSAVP=^VPRSTATUS W "Saved ^VPRSTATUS as ^VPRJSAVP",! ; S J=0 S (PID,SITE,SOURCESTAMP,DOMAIN)="" ; F S PID=$O(^VPRSTATUS(PID)) Q:PID="" D . S SITE=$P(PID,";") . S (SOURCESTAMP,DOMAIN)="" . ; . TS (DOMAIN,SOURCESTAMP) . ; . S SOURCESTAMP=$O(^VPRSTATUS(PID,SITE,SOURCESTAMP),-1) ; Get the newest source stamp . I SOURCESTAMP?14N S J=J+1 . E TRO D Q . . W "Site: "_SITE_" PID: "_PID_" Invalid Sourcestamp found: ",SOURCESTAMP,! . . S ^VPRJCONV(SITE,"patient",PID)="Invalid Sourcestamp found: "_SOURCESTAMP . ; . F S DOMAIN=$O(^VPRSTATUS(PID,SITE,SOURCESTAMP,DOMAIN)) Q:DOMAIN="" D . . ; Delete the domain stored node . . K:$D(^VPRSTATUS(PID,SITE,SOURCESTAMP,DOMAIN,SOURCESTAMP,"stored")) ^VPRSTATUS(PID,SITE,SOURCESTAMP,DOMAIN,SOURCESTAMP,"stored") . ; . ZK:$D(^VPRSTATUS(PID,SITE,SOURCESTAMP))#10 ^VPRSTATUS(PID,SITE,SOURCESTAMP) ; Delete the data, but not the descendants . ; Save off newest metastamp to a temp global . M ^VPRJSTMP("VPRSTATUS",PID,SITE)=^VPRSTATUS(PID,SITE,SOURCESTAMP) . S ^VPRJSTMP("VPRSTATUS",PID,SITE,"stampTime")=SOURCESTAMP . K:$D(^VPRSTATUS(PID,SITE)) ^VPRSTATUS(PID,SITE) . M ^VPRSTATUS(PID,SITE)=^VPRJSTMP("VPRSTATUS",PID,SITE) . ; . TC ; K:$D(^VPRJSTMP("VPRSTATUS")) ^VPRJSTMP("VPRSTATUS") ; L -^VPRSTATUS ; S ENDTIME=$$SEC^XLFDT($H) ; ; Calculate elapsed time for operational and patient sync metastamp conversions S TOTALTIME=ENDTIME-STARTOD D DISPTIME(TOTALTIME,"Total time:") ; W !,"Total sites: "_I,! ; S ODTIME=STARTPAT-STARTOD D DISPTIME(ODTIME,"Total time for operational data:") ; I I>1 D ; Only need an average if there is more than one site . S ODAVG=STARTPAT-STARTOD/I ; Calculate average time per site . D DISPTIME(ODAVG,"Average time per site:") ; ; W !,"Total patients: "_J,! ; S PATTIME=ENDTIME-STARTPAT D DISPTIME(PATTIME,"Total time for patient data:") ; I J>1 D ; Only need an average if there is more than one patient . S PATAVG=ENDTIME-STARTPAT/J ; Calculate average time per patient . D DISPTIME(PATAVG,"Average time per patient:") ; W !,"Check ^VPRSTATUSOD and ^VPRSTATUS, original versions in ^VPRJSAVD and ^VPRJSAVP",! ; QUIT ; JPIDSHRD(SAVE) ; Entry point for JPID restructure for sharding conversion ; SAVE specifies whether to save the original global trees before conversion ; Pass a 1 to save to disk explicitly, or pass a 2, to save to a global ; mapped to memory, or pass a 0 to NOT save N STARTARY,STARTJSN,STARTIDX,STARTTPL,STARTSTS,ENDTIME,TOTALTIME,ARYTIME,ARYAVG N JSNTIME,JSNAVG,IDXTIME,IDXAVG,TPLTIME,TPLAVG,STSTIME,STSAVG,I,J,K,L,M,JPID,PID ; ; Default to saving all original data to disk be able to rollback conversion S SAVE=$G(SAVE,1) ; I SAVE=1,$D(^VPRJSAVA) W "^VPRJSAVA is not empty, aborting!",! QUIT I SAVE=1,$D(^VPRJSAVJ) W "^VPRJSAVJ is not empty, aborting!",! QUIT I SAVE=1,$D(^VPRJSAVI) W "^VPRJSAVI is not empty, aborting!",! QUIT I SAVE=1,$D(^VPRJSAVT) W "^VPRJSAVT is not empty, aborting!",! QUIT I SAVE=1,$D(^VPRJSAVS) W "^VPRJSAVS is not empty, aborting!",! QUIT ; I SAVE=2,$D(^TMP("VPRJSAVA")) W "^TMP(""VPRJSAVA"") is not empty, aborting!",! QUIT I SAVE=2,$D(^TMP("VPRJSAVJ")) W "^TMP(""VPRJSAVJ"") is not empty, aborting!",! QUIT I SAVE=2,$D(^TMP("VPRJSAVI")) W "^TMP(""VPRJSAVI"") is not empty, aborting!",! QUIT I SAVE=2,$D(^TMP("VPRJSAVT")) W "^TMP(""VPRJSAVT"") is not empty, aborting!",! QUIT I SAVE=2,$D(^TMP("VPRJSAVS")) W "^TMP(""VPRJSAVS"") is not empty, aborting!",! QUIT ; I $D(^TMP("VPRJSVPT")) W "^TMP(""VPRJSVPT"") is not empty, aborting!",! QUIT I '$D(^VPRPT) W "^VPRPT appears to be empty, aborting!",! QUIT I '$D(^VPRPTJ("JSON")) W "^VPRPTJ appears to be empty, aborting!",! QUIT I '$D(^VPRPTI) W "^VPRPTI appears to be empty, aborting!",! QUIT I '$D(^VPRPTJ("TEMPLATE")) W "^VPRPTJ appears to be empty, aborting!",! QUIT I '$D(^VPRSTATUS) W "^VPRSTATUS appears to be empty, aborting!",! QUIT ; S STARTARY=$$SEC^XLFDT($H) ; ; Start conversion for patient data array L +^VPRPT:$G(^VPRCONFIG("timeout","arrayconvert"),5) E W "Could not obtain lock on ^VPRPT, aborting!",! QUIT ; W:SAVE "All original data will be saved during conversion",!! ; S I=0 S (PID,JPID)="" ; F S PID=$O(^VPRPT(PID)) Q:PID="" D . I '$$ISPID^VPRJPR(PID) W PID_" is not a PID, skipping",! Q . ; . W "Converting patient data array for PID: "_PID,! . ; . TS JPID . S JPID=$$JPID4PID^VPRJPR(PID) . ; . I $$ISJPID^VPRJPR(JPID) S I=I+1 . E TRO D Q . . W "No JPID found for patient: "_PID,! . . S ^VPRJCONV("ARRAY",PID)="No JPID found for patient" . ; . ; Save off patient to a temp global . ; Merge patient under its JPID . M ^TMP("VPRJSVPT","ARRAY",JPID,PID)=^VPRPT(PID) . ; Save to disk mode, back up the original node to a disk-backed global . I SAVE=1 M ^VPRJSAVA(PID)=^VPRPT(PID) . ; Save to cache mode, back up the original node to a memory-backed global . E I SAVE=2 M ^TMP("VPRJSAVA",PID)=^VPRPT(PID) . ; Kill original patient array node . K:$D(^VPRPT(PID)) ^VPRPT(PID) . ; . TC ; Merge all patients back in to ^VPRPT W "Merging ^TMP(""VPRJSVPT"",""ARRAY"") back in to ^VPRPT",! M ^VPRPT=^TMP("VPRJSVPT","ARRAY") K:$D(^TMP("VPRJSVPT","ARRAY")) ^TMP("VPRJSVPT","ARRAY") W "Merged ^TMP(""VPRJSVPT"",""ARRAY"") back in to ^VPRPT",! ; L -^VPRPT ; W ! ; S STARTJSN=$$SEC^XLFDT($H) ; ; Start conversion for patient data JSON L +^VPRPTJ("JSON"):$G(^VPRCONFIG("timeout","jsonconvert"),5) E W "Could not obtain lock on ^VPRPTJ(""JSON""), aborting!",! QUIT ; S J=0 S (PID,JPID)="" ; F S PID=$O(^VPRPTJ("JSON",PID)) Q:PID="" D . I '$$ISPID^VPRJPR(PID) W PID_" is not a PID, skipping",! Q . ; . W "Converting patient data JSON for PID: "_PID,! . ; . TS JPID . S JPID=$$JPID4PID^VPRJPR(PID) . ; . I $$ISJPID^VPRJPR(JPID) S J=J+1 . E TRO D Q . . W "No JPID found for patient: "_PID,! . . S ^VPRJCONV("JSON",PID)="No JPID found for patient" . ; . ; Save off patient to a temp global . ; Merge patient under its JPID . M ^TMP("VPRJSVPT","JSON",JPID,PID)=^VPRPTJ("JSON",PID) . ; Save to disk mode, back up the original node to a disk-backed global . I SAVE=1 M ^VPRJSAVJ(PID)=^VPRPTJ("JSON",PID) . ; Save to cache mode, back up the original node to a memory-backed global . E I SAVE=2 M ^TMP("VPRJSAVJ",PID)=^VPRPTJ("JSON",PID) . ; Kill original patient JSON node . K:$D(^VPRPTJ("JSON",PID)) ^VPRPTJ("JSON",PID) . ; . TC ; Merge all patients back in to ^VPRPTJ("JSON") W "Merging ^TMP(""VPRJSVPT"",""JSON"") back in to ^VPRPTJ(""JSON"")",! M ^VPRPTJ("JSON")=^TMP("VPRJSVPT","JSON") K:$D(^TMP("VPRJSVPT","JSON")) ^TMP("VPRJSVPT","JSON") W "Merged ^TMP(""VPRJSVPT"",""JSON"") back in to ^VPRPTJ(""JSON"")",! ; L -^VPRPTJ("JSON") ; W ! ; S STARTIDX=$$SEC^XLFDT($H) ; ; Start conversion for patient data INDEX L +^VPRPTI:$G(^VPRCONFIG("timeout","indexconvert"),5) E W "Could not obtain lock on ^VPRPTI, aborting!",! QUIT ; S K=0 S (PID,JPID)="" ; F S PID=$O(^VPRPTI(PID)) Q:PID="" D . I '$$ISPID^VPRJPR(PID) W PID_" is not a PID, skipping",! Q . ; . W "Converting patient data index for PID: "_PID,! . ; . TS JPID . S JPID=$$JPID4PID^VPRJPR(PID) . ; . I $$ISJPID^VPRJPR(JPID) S K=K+1 . E TRO D Q . . W "No JPID found for patient: "_PID,! . . S ^VPRJCONV("INDEX",PID)="No JPID found for patient" . ; . ; Save off patient to a temp global . ; Merge patient under its JPID . M ^TMP("VPRJSVPT","INDEX",JPID,PID)=^VPRPTI(PID) . ; Save to disk mode, back up the original node to a disk-backed global . I SAVE=1 M ^VPRJSAVI(PID)=^VPRPTI(PID) . ; Save to cache mode, back up the original node to a memory-backed global . E I SAVE=2 M ^TMP("VPRJSAVI",PID)=^VPRPTI(PID) . ; Kill original patient index node . K:$D(^VPRPTI(PID)) ^VPRPTI(PID) . ; . TC ; Merge all patients back in to ^VPRPTI W "Merging ^TMP(""VPRJSVPT"",""INDEX"") back in to ^VPRPTI",! M ^VPRPTI=^TMP("VPRJSVPT","INDEX") K:$D(^TMP("VPRJSVPT","INDEX")) ^TMP("VPRJSVPT","INDEX") W "Merged ^TMP(""VPRJSVPT"",""INDEX"") back in to ^VPRPTI",! ; L -^VPRPTI ; W ! ; S STARTTPL=$$SEC^XLFDT($H) ; ; Start conversion for patient data TEMPLATE L +^VPRPTJ("TEMPLATE"):$G(^VPRCONFIG("timeout","templateconvert"),5) E W "Could not obtain lock on ^VPRPTJ(""TEMPLATE""), aborting!",! QUIT ; S L=0 S (PID,JPID)="" ; F S PID=$O(^VPRPTJ("TEMPLATE",PID)) Q:PID="" D . I '$$ISPID^VPRJPR(PID) W PID_" is not a PID, skipping",! Q . ; . W "Converting patient data template for PID: "_PID,! . ; . TS JPID . S JPID=$$JPID4PID^VPRJPR(PID) . ; . I $$ISJPID^VPRJPR(JPID) S L=L+1 . E TRO D Q . . W "No JPID found for patient: "_PID,! . . S ^VPRJCONV("TEMPLATE",PID)="No JPID found for patient" . ; . ; Save off patient to a temp global . ; Merge patient under its JPID . M ^TMP("VPRJSVPT","TEMPLATE",JPID,PID)=^VPRPTJ("TEMPLATE",PID) . ; If in save mode, back up the original node . M:SAVE ^VPRJSAVT(PID)=^VPRPTJ("TEMPLATE",PID) . ; Save to disk mode, back up the original node to a disk-backed global . I SAVE=1 M ^VPRJSAVT(PID)=^VPRPTJ("TEMPLATE",PID) . ; Save to cache mode, back up the original node to a memory-backed global . E I SAVE=2 M ^TMP("VPRJSAVT",PID)=^VPRPTJ("TEMPLATE",PID) . ; Kill original patient template node . K:$D(^VPRPTJ("TEMPLATE",PID)) ^VPRPTJ("TEMPLATE",PID) . ; . TC ; Merge all patients back in to ^VPRPTJ("TEMPLATE") W "Merging ^TMP(""VPRJSVPT"",""TEMPLATE"") back in to ^VPRPTJ(""TEMPLATE"")",! M ^VPRPTJ("TEMPLATE")=^TMP("VPRJSVPT","TEMPLATE") K:$D(^TMP("VPRJSVPT","TEMPLATE")) ^TMP("VPRJSVPT","TEMPLATE") W "Merged ^TMP(""VPRJSVPT"",""TEMPLATE"") back in to ^VPRPTJ(""TEMPLATE"")",! ; L -^VPRPTJ("TEMPLATE") ; W ! ; S STARTSTS=$$SEC^XLFDT($H) ; ; Start conversion for patient data sync status L +^VPRSTATUS:$G(^VPRCONFIG("timeout","statusconvert"),5) E W "Could not obtain lock on ^VPRSTATUS, aborting!",! QUIT ; S M=0 S (PID,JPID)="" ; F S PID=$O(^VPRSTATUS(PID)) Q:PID="" D . I '$$ISPID^VPRJPR(PID) W PID_" is not a PID, skipping",! Q . ; . W "Converting patient sync status for PID: "_PID,! . ; . TS JPID . S JPID=$$JPID4PID^VPRJPR(PID) . ; . I $$ISJPID^VPRJPR(JPID) S M=M+1 . E TRO D Q . . W "No JPID found for patient: "_PID,! . . S ^VPRJCONV("STATUS",PID)="No JPID found for patient" . ; . ; Save off patient to a temp global . ; Merge patient under its JPID . M ^TMP("VPRJSVPT","STATUS",JPID,PID)=^VPRSTATUS(PID) . ; Save to disk mode, back up the original node to a disk-backed global . I SAVE=1 M ^VPRJSAVS(PID)=^VPRSTATUS(PID) . ; Save to cache mode, back up the original node to a memory-backed global . E I SAVE=2 M ^TMP("VPRJSAVS",PID)=^VPRSTATUS(PID) . ; Kill original patient sync status node . K:$D(^VPRSTATUS(PID)) ^VPRSTATUS(PID) . ; . TC ; Merge all patients back in to ^VPRSTATUS W "Merging ^TMP(""VPRJSVPT"",""STATUS"") back in to ^VPRSTATUS",! M ^VPRSTATUS=^TMP("VPRJSVPT","STATUS") K:$D(^TMP("VPRJSVPT","STATUS")) ^TMP("VPRJSVPT","STATUS") W "Merged ^TMP(""VPRJSVPT"",""STATUS"") back in to ^VPRSTATUS",! ; L -^VPRSTATUS ; W ! ; S ENDTIME=$$SEC^XLFDT($H) ; ; Calculate elapsed time for patient array, json, index, and template conversions S TOTALTIME=ENDTIME-STARTARY D DISPTIME(TOTALTIME,"Total time:") ; W !,"Total PIDs in ^VPRPT: "_I,! ; S ARYTIME=STARTJSN-STARTARY D DISPTIME(ARYTIME,"Total time for patient array data:") ; I I>1 D ; Only need an average if there is more than one PID . S ARYAVG=STARTJSN-STARTARY/I ; Calculate average time per PID . D DISPTIME(ARYAVG,"Average time per PID:") ; W !,"Total PIDs in ^VPRPTJ(""JSON""): "_J,! ; S JSNTIME=STARTIDX-STARTJSN D DISPTIME(JSNTIME,"Total time for patient JSON data:") ; I J>1 D ; Only need an average if there is more than one PID . S JSNAVG=STARTIDX-STARTJSN/J ; Calculate average time per PID . D DISPTIME(JSNAVG,"Average time per PID:") ; W !,"Total PIDs in ^VPRPTI: "_K,! ; S IDXTIME=STARTTPL-STARTIDX D DISPTIME(IDXTIME,"Total time for patient index data:") ; I K>1 D ; Only need an average if there is more than one PID . S IDXAVG=STARTTPL-STARTIDX/K ; Calculate average time per PID . D DISPTIME(IDXAVG,"Average time per PID:") ; W !,"Total PIDs in ^VPRPTJ(""TEMPLATE""): "_L,! ; S TPLTIME=STARTSTS-STARTTPL D DISPTIME(TPLTIME,"Total time for patient template data:") ; I L>1 D ; Only need an average if there is more than one PID . S TPLAVG=STARTSTS-STARTTPL/L ; Calculate average time per PID . D DISPTIME(TPLAVG,"Average time per PID:") ; W !,"Total PIDs in ^VPRSTATUS: "_M,! ; S STSTIME=ENDTIME-STARTSTS D DISPTIME(STSTIME,"Total time for patient sync status data:") ; I M>1 D ; Only need an average if there is more than one PID . S STSAVG=ENDTIME-STARTSTS/M ; Calculate average time per PID . D DISPTIME(STSAVG,"Average time per PID:") ; W !,"Check ^VPRPT, ^VPRPTJ(""JSON""), ^VPRPTI, ^VPRPTJ(""TEMPLATE""), and ^VPRSTATUS",! W !,"Errors can be found in ^VPRJCONV",! I SAVE=1 D . W !,"Original versions in ^VPRJSAVA, ^VPRJSAVJ, ^VPRJSAVI, ^VPRJSAVT, and ^VPRJSAVS" . W !!,"You can recover the old structure by running these five commands:" . W !,?4,"K ^VPRPT M ^VPRPT=^VPRJSAVA" . W !,?4,"K ^VPRPTJ(""JSON"") M ^VPRPTJ(""JSON"")=^VPRJSAVJ" . W !,?4,"K ^VPRPTI M ^VPRPTI=^VPRJSAVI" . W !,?4,"K ^VPRPTJ(""TEMPLATE"") M ^VPRPTJ(""TEMPLATE"")=^VPRJSAVT" . W !,?4,"K ^VPRSTATUS M ^VPRSTATUS=^VPRJSAVS" . W !!,"You will have to remove them if you need to run the conversion again:" . W !,?4,"K ^VPRJSAVA,^VPRJSAVJ,^VPRJSAVI,^VPRJSAVT,^VPRJSAVS" E I SAVE=2 D . W !,"Original versions in ^TMP(""VPRJSAVA""), ^TMP(""VPRJSAVJ"")," . W !,"^TMP(""VPRJSAVI""), ^TMP(""VPRJSAVT""), and ^TMP(""VPRJSAVS"")" . W !!,"You can recover the old structure by running these five commands:" . W !,?4,"K ^VPRPT M ^VPRPT=^TMP(""VPRJSAVA"")" . W !,?4,"K ^VPRPTJ(""JSON"") M ^VPRPTJ(""JSON"")=^TMP(""VPRJSAVJ"")" . W !,?4,"K ^VPRPTI M ^VPRPTI=^TMP(""VPRJSAVI"")" . W !,?4,"K ^VPRPTJ(""TEMPLATE"") M ^VPRPTJ(""TEMPLATE"")=^TMP(""VPRJSAVT"")" . W !,?4,"K ^VPRSTATUS M ^VPRSTATUS=^TMP(""VPRJSAVS"")" . W !!,"You will have to remove them if you need to run the conversion again:" . W !,?4,"K ^TMP(""VPRJSAVA""),^TMP(""VPRJSAVJ""),^TMP(""VPRJSAVI"")" . W !,?4,"K ^TMP(""VPRJSAVT""),^TMP(""VPRJSAVS"")" ; QUIT ; DISPTIME(TIME,MSG) ; Display the elapsed time the conversion routine took to run ; Parameters: ; TIME = elapsed time in seconds ; MSG = message to display before human readable time is displayed ; I TIME'?.N1(1"."1.N,.N) W "First argument must be number of seconds elapsed",! QUIT ; N DAYS,HOURS,MINUTES,SECONDS ; Convert elapsed seconds to a more human readable format I TIME["." S TIME=$J(TIME,"",3) S DAYS=TIME\86400 S HOURS=TIME-(DAYS*86400)\3600 S MINUTES=TIME-(DAYS*86400)-(HOURS*3600)\60 S SECONDS=TIME-(DAYS*86400)-(HOURS*3600)#60 ; I $E($RE($G(MSG)))'=" " S MSG=$G(MSG)_" " ; Add a space for nicer formatting ; W !,MSG_DAYS_" Day"_$S(DAYS'=1:"s",1:"")_", "_HOURS_" Hour"_$S(HOURS'=1:"s",1:"") W ", "_MINUTES_" Minute"_$S(MINUTES'=1:"s",1:"")_", "_SECONDS_" Second"_$S(SECONDS'=1:"s",1:"") W !,?$L(MSG),"("_TIME_" Total Seconds)",! ; QUIT ; DELERROR ; Delete the old JDS error store data and URL mappings N URL,NUM ; F URL="error/set/this","error/get/{id}","error/get","error/length/this","error/destroy/{id}","error/clear/this" D . S NUM=0 . F S NUM=$O(^VPRCONFIG("urlmap","url-index",URL,NUM)) Q:NUM="" D . . K:$D(^VPRCONFIG("urlmap",NUM)) ^VPRCONFIG("urlmap",NUM) . K:$D(^VPRCONFIG("urlmap","url-index",URL)) ^VPRCONFIG("urlmap","url-index",URL) K:$D(^VPRJERR) ^VPRJERR ; I ($D(^VPRJERR))!($O(^VPRCONFIG("urlmap","url-index","err"))["error") W "Old JDS error store was not completely deleted..",! E W "Old JDS error store is successfully deleted..",! ; QUIT
{ "content_hash": "50353ce06ecd9070c53580717509c1ac", "timestamp": "", "source": "github", "line_count": 484, "max_line_length": 141, "avg_line_length": 38.336776859504134, "alnum_prop": 0.6561573699811372, "repo_name": "KRMAssociatesInc/JDS-GTM", "id": "e7aafa1ca5d9dcdca00a86bc1121c45b39eaa5cb", "size": "18555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VPRJCONV.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "M", "bytes": "1773055" } ], "symlink_target": "" }
package im.actor.server.session import java.util.concurrent.TimeUnit import akka.actor.{ ActorLogging, ActorRef, Cancellable, Props } import akka.stream.actor._ import com.typesafe.config.Config import im.actor.api.rpc.{ RpcOk, UpdateBox, RpcResult ⇒ ApiRpcResult } import im.actor.api.rpc.codecs.UpdateBoxCodec import im.actor.api.rpc.sequence._ import im.actor.server.api.rpc.RpcResultCodec import im.actor.server.mtproto.protocol._ import scodec.bits.BitVector import scala.annotation.tailrec import scala.collection.{ immutable, mutable } import scala.concurrent.duration._ import scala.util.control.NoStackTrace private[session] sealed trait ReSenderMessage private[session] object ReSenderMessage { final case class NewClient(client: ActorRef) extends ReSenderMessage final case class IncomingAck(messageIds: Seq[Long]) extends ReSenderMessage final case class IncomingRequestResend(messageId: Long) extends ReSenderMessage // final case class OutgoingMessage(msg: ProtoMessage) extends ReSenderMessage final case class OutgoingAck(messageIds: Seq[Long]) extends ReSenderMessage final case class Push(ub: UpdateBox, reduceKey: Option[String]) extends ReSenderMessage final case class RpcResult(rsp: ApiRpcResult, requestMessageId: Long) extends ReSenderMessage final case class SetUpdateOptimizations(updateOptimizations: Set[ApiUpdateOptimization.Value]) extends ReSenderMessage } private[session] case class ReSenderConfig(ackTimeout: FiniteDuration, maxResendSize: Long, maxBufferSize: Long, maxPushBufferSize: Long) private[session] object ReSenderConfig { def fromConfig(config: Config): ReSenderConfig = { ReSenderConfig( ackTimeout = config.getDuration("ack-timeout", TimeUnit.SECONDS).seconds, maxResendSize = config.getBytes("max-resend-size"), maxBufferSize = config.getBytes("max-buffer-size"), maxPushBufferSize = config.getBytes("max-push-buffer-size") ) } } private[session] object ReSender { private case class ScheduledResend(messageId: Long, item: ResendableItem) private sealed trait ResendableItem { val bitsSize: Long val size = bitsSize / 8 val priority: Priority } private object RpcItem { def apply(result: ApiRpcResult, requestMessageId: Long): RpcItem = RpcItem(RpcResultCodec.encode(result).require, requestMessageId) } private final case class RpcItem(body: BitVector, requestMessageId: Long) extends ResendableItem { override lazy val bitsSize = body.size override val priority = Priority.RPC } private object PushItem { def apply(ub: UpdateBox, reduceKeyOpt: Option[String]): PushItem = { val priority = ub match { case _: SeqUpdate | _: FatSeqUpdate ⇒ Priority.SeqPush case _: WeakUpdate ⇒ Priority.WeakPush } PushItem(UpdateBoxCodec.encode(ub).require, reduceKeyOpt, priority) } } private final case class PushItem(body: BitVector, reduceKeyOpt: Option[String], priority: Priority) extends ResendableItem { override lazy val bitsSize = body.size } private final case class NewSessionItem(newSession: NewSession) extends ResendableItem { override val bitsSize = 0L override val priority = Priority.NewSession } sealed trait Priority { val id: Int } object Priority { object NewSession extends Priority { override val id = 2 } object Ack extends Priority { override val id = 1 } object RPC extends Priority { override val id = 0 } object SeqPush extends Priority { override val id = -1 } object WeakPush extends Priority { override val id = -2 } } private case object BufferOverflow def props(authId: Long, sessionId: Long, firstMessageId: Long)(implicit config: ReSenderConfig) = Props(classOf[ReSender], authId, sessionId, firstMessageId, config) } private[session] class ReSender(authId: Long, sessionId: Long, firstMessageId: Long)(implicit config: ReSenderConfig) extends ActorSubscriber with ActorPublisher[MessageBox] with ActorLogging with MessageIdHelper { import ActorPublisherMessage._ import ActorSubscriberMessage._ import ReSender._ import ReSenderMessage._ import context.dispatcher // TODO: configurable private val AckTimeout = config.ackTimeout private val MaxBufferSize = config.maxBufferSize private val MaxResendSize = config.maxResendSize def receive = resendingToNewClients def resendingToNewClients: Receive = subscriber.orElse(publisher).orElse { case NewClient(_) ⇒ log.debug("New client, sending all scheduled for resend") this.mbQueue.clear() this.resendBufferSize = 0 this.resendPushBufferSize = 0 this.newSessionBuffer foreach { case (messageId, ni, scheduled) ⇒ scheduled.cancel() enqueueNewSession(ni) } this.responseBuffer foreach { case (messageId, (pi, scheduled)) ⇒ scheduled.cancel() enqueueRpc(pi, nextMessageId()) } this.pushBuffer foreach { case (messageId, (pi, scheduled)) ⇒ scheduled.cancel() enqueuePush(pi, nextMessageId()) } } private[this] var resendBufferSize = 0L private[this] var resendPushBufferSize = 0L private[this] var updateOptimizations = Set.empty[ApiUpdateOptimization.Value] private[this] var newSessionBuffer: Option[(Long, NewSessionItem, Cancellable)] = None private[this] var responseBuffer = immutable.SortedMap.empty[Long, (RpcItem, Cancellable)] private[this] var pushBuffer = immutable.SortedMap.empty[Long, (PushItem, Cancellable)] // Provides mapping from reduceKey to the last message with the reduceKey private[this] var pushReduceMap = immutable.Map.empty[String, Long] // Provides mapping from request messageId to a responseMessageId // to prevent response duplicates when client re-requests with same messageId type RequestMessageId = Long type ResponseMessageId = Long private[this] var rpcMap = immutable.Map.empty[RequestMessageId, ResponseMessageId] // Used to prevent scheduling multiple updates at the same millisecond and result out of order private[this] var lastScheduledResend = System.currentTimeMillis - 1 override def preStart(): Unit = { super.preStart() enqueueNewSession(NewSessionItem(NewSession(sessionId, firstMessageId))) } override def preRestart(reason: Throwable, message: Option[Any]): Unit = { log.error(reason, "An error occured while processing message: {}", message) super.preRestart(reason, message) } // Subscriber-related def subscriber: Receive = { case OnNext(IncomingAck(messageIds)) ⇒ log.debug("Received Acks {}", messageIds) messageIds foreach { messageId ⇒ getResendableItem(messageId) foreach { case (item, scheduledResend) ⇒ decreaseBufferSize(item) scheduledResend.cancel() item match { case PushItem(_, reduceKeyOpt, _) ⇒ reduceKeyOpt foreach { reduceKey ⇒ if (pushReduceMap.get(reduceKey).contains(messageId)) pushReduceMap -= reduceKey } pushBuffer -= messageId case _: RpcItem ⇒ responseBuffer -= messageId rpcMap -= messageId case item: NewSessionItem ⇒ this.newSessionBuffer = None } } } case OnNext(OutgoingAck(messageIds)) ⇒ enqueueAcks(messageIds) case OnNext(IncomingRequestResend(messageId)) ⇒ getResendableItem(messageId) foreach { case (item, scheduled) ⇒ scheduled.cancel() item match { case pi: PushItem ⇒ enqueuePush(pi, nextMessageId()) case ri: RpcItem ⇒ enqueueRpc(ri, nextMessageId()) case ni: NewSessionItem ⇒ enqueueNewSession(ni) } } case OnNext(RpcResult(rsp, requestMessageId)) ⇒ val item = RpcItem(rsp, requestMessageId) this.rpcMap get requestMessageId match { // we are trying to deliver this response already, // so we cancel previous scheduled resend as client already requested a resend by doubling RPC request case Some(responseMessageId) ⇒ responseBuffer.get(responseMessageId) map (_._2.cancel()) match { case Some(false) ⇒ case _ ⇒ enqueueRpc(item, responseMessageId) } // it's a new rpc response case None ⇒ val responseMessageId = nextMessageId() this.rpcMap += (requestMessageId → responseMessageId) enqueueRpc(item, responseMessageId) } case OnNext(p @ Push(_, reduceKey)) ⇒ enqueuePush(PushItem(p.ub, reduceKey), nextMessageId()) case OnNext(SetUpdateOptimizations(opts)) ⇒ this.updateOptimizations = opts case OnComplete ⇒ log.debug("Stopping due to stream completion") // TODO: cleanup scheduled resends context.stop(self) case OnError(cause) ⇒ log.error(cause, "Stopping due to stream error") // TODO: cleanup scheduled resends context.stop(self) case ScheduledResend(messageId, item) ⇒ if (getResendableItem(messageId).isDefined) { log.debug("Scheduled resend for messageId: {}, item: {}, resending", messageId, item) decreaseBufferSize(item) item match { case ni: NewSessionItem ⇒ enqueueNewSession(ni) case pi: PushItem ⇒ if (pi.size > MaxResendSize) enqueueUnsentPush(pi, messageId) else enqueuePush(pi, messageId) case ri: RpcItem ⇒ if (ri.size > MaxResendSize) enqueueUnsentRpc(ri, messageId) else enqueueRpc(ri, messageId) } } else log.debug("ScheduledResend for messageId: {}, item: {}, ignoring (absent in buffer)", messageId, item) case BufferOverflow ⇒ if (this.resendBufferSize > config.maxBufferSize) { log.warning("Buffer overflow, stopping session") this.onCompleteThenStop() } } private def increaseBufferSize(item: ResendableItem): Unit = { this.resendBufferSize += item.size item match { case p: PushItem ⇒ if (this.resendPushBufferSize > config.maxPushBufferSize) clearPushBuffer() else this.resendPushBufferSize += item.size case _ ⇒ } } private def decreaseBufferSize(item: ResendableItem): Unit = { this.resendBufferSize -= item.size item match { case _: PushItem ⇒ this.resendPushBufferSize -= item.size case _ ⇒ } } private def clearPushBuffer(): Unit = { log.debug("Push buffer exceeded, clearing and sending SeqUpdateTooLong") pushBuffer foreach { case (messageId, (pi: PushItem, resend)) ⇒ pushBuffer -= messageId decreaseBufferSize(pi) resend.cancel() case _ ⇒ } enqueueSeqUpdateTooLong() } // Publisher-related override val requestStrategy = WatermarkRequestStrategy(100) // TODO: configurable // Publisher-related private[this] val mbQueue = mutable.PriorityQueue.empty[(MessageBox, Priority)](Ordering.by { case (mb, p) ⇒ (p.id, mb.messageId) }) def publisher: Receive = { case Request(n) ⇒ deliverBuf() case Cancel ⇒ context.stop(self) } @tailrec final def deliverBuf(): Unit = { if (isActive && totalDemand > 0 && mbQueue.nonEmpty) mbQueue.dequeue() match { case (mb, _) ⇒ onNext(mb) deliverBuf() } } override def unhandled(message: Any): Unit = { super.unhandled(message) log.error("Unhandled {}", message) } private def getResendableItem(messageId: Long): Option[(ResendableItem, Cancellable)] = { responseBuffer .get(messageId) .orElse(pushBuffer.get(messageId)) .orElse { this.newSessionBuffer match { case Some((`messageId`, item, scheduled)) ⇒ Some((item, scheduled)) case _ ⇒ None } } } private def calcScheduleDelay(): FiniteDuration = { val currentTime = System.currentTimeMillis() if (currentTime > this.lastScheduledResend) { this.lastScheduledResend = currentTime AckTimeout } else { val delta = this.lastScheduledResend - currentTime + 1 this.lastScheduledResend = currentTime + delta AckTimeout + delta.milli } } private def scheduleResend(item: ResendableItem, messageId: Long) = { log.debug("Scheduling resend of messageId: {}, timeout: {}", messageId, AckTimeout) // FIXME: increase resendBufferSize by real Unsent if (resendBufferSize <= MaxBufferSize) { val delay = calcScheduleDelay() val scheduled = context.system.scheduler.scheduleOnce(delay, self, ScheduledResend(messageId, item)) item match { case pi @ PushItem(_, reduceKeyOpt, _) ⇒ reduceKeyOpt foreach { reduceKey ⇒ for { msgId ← pushReduceMap.get(reduceKey) (ritem, resend) ← pushBuffer.get(msgId) } yield { this.pushBuffer -= msgId decreaseBufferSize(ritem) resend.cancel() } this.pushReduceMap += (reduceKey → messageId) } this.pushBuffer = this.pushBuffer.updated(messageId, (pi, scheduled)) case ni: NewSessionItem ⇒ this.newSessionBuffer = Some((messageId, ni, scheduled)) case ri: RpcItem ⇒ this.responseBuffer = this.responseBuffer.updated(messageId, (ri, scheduled)) } } else bufferOverflow() increaseBufferSize(item) } private def enqueueAcks(messageIds: Seq[Long]): Unit = enqueue(MessageBox(nextMessageId(), MessageAck(messageIds.toVector)), Priority.Ack) private def enqueueNewSession(item: NewSessionItem): Unit = { val messageId = nextMessageId() scheduleResend(item, messageId) enqueue(MessageBox(messageId, item.newSession), Priority.NewSession) } private def enqueueSeqUpdateTooLong(): Unit = enqueue(MessageBox(nextMessageId(), ProtoPush(UpdateBoxCodec.encode(SeqUpdateTooLong).require)), Priority.SeqPush) private def enqueueRpc(item: RpcItem, messageId: Long): Unit = { scheduleResend(item, messageId) val mb = MessageBox(messageId, ProtoRpcResponse(item.requestMessageId, item.body)) enqueue(mb, Priority.RPC) } private def enqueueUnsentRpc(item: RpcItem, unsentMessageId: Long): Unit = { scheduleResend(item, unsentMessageId) val mb = MessageBox(nextMessageId(), UnsentResponse(unsentMessageId, item.requestMessageId, item.size.toInt)) enqueue(mb, Priority.RPC) } private def enqueuePush(item: PushItem, messageId: Long): Unit = { scheduleResend(item, messageId) val mb = MessageBox(messageId, ProtoPush(item.body)) enqueue(mb, item.priority) } private def enqueueUnsentPush(item: PushItem, unsentMessageId: Long): Unit = { scheduleResend(item, unsentMessageId) val mb = MessageBox(nextMessageId(), UnsentMessage(unsentMessageId, item.size.toInt)) enqueue(mb, item.priority) } private def enqueue(mb: MessageBox, priority: Priority): Unit = { log.debug("Queue size: {}, bufferSize: {}, pushBufferSize: {}", mbQueue.size, resendBufferSize, resendPushBufferSize) if (isActive && totalDemand > 0 && mbQueue.isEmpty) { onNext(mb) } else { this.mbQueue.enqueue(mb → priority) deliverBuf() } } private def bufferOverflow(): Unit = { self ! BufferOverflow } private def pushBufferSize = responseBuffer.size + pushBuffer.size + newSessionBuffer.map(_ ⇒ 1).getOrElse(0) override def postStop(): Unit = { super.postStop() log.debug("Clearing resend buffers ({} items)", pushBufferSize) responseBuffer.values foreach (_._2.cancel()) pushBuffer.values foreach (_._2.cancel()) newSessionBuffer foreach (_._3.cancel()) } }
{ "content_hash": "42f6019a4ab906a6b9004aea58a5bf15", "timestamp": "", "source": "github", "line_count": 472, "max_line_length": 137, "avg_line_length": 33.985169491525426, "alnum_prop": 0.6760177046318808, "repo_name": "ljshj/actor-platform", "id": "3278c18193306b11167e5d0ec6cb0aa8a29d543d", "size": "16153", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "actor-server/actor-session/src/main/scala/im/actor/server/session/Resender.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2575" }, { "name": "CSS", "bytes": "84420" }, { "name": "HTML", "bytes": "2562" }, { "name": "Java", "bytes": "3685846" }, { "name": "JavaScript", "bytes": "310291" }, { "name": "Makefile", "bytes": "3630" }, { "name": "Objective-C", "bytes": "239045" }, { "name": "PLSQL", "bytes": "66" }, { "name": "Protocol Buffer", "bytes": "29116" }, { "name": "Python", "bytes": "5803" }, { "name": "Ruby", "bytes": "2728" }, { "name": "SQLPL", "bytes": "99" }, { "name": "Scala", "bytes": "1241984" }, { "name": "Shell", "bytes": "12028" }, { "name": "Swift", "bytes": "638635" } ], "symlink_target": "" }
Settings ======== The following settings are Scrapy Cluster specific. For all other Scrapy settings please refer to the official Scrapy documentation `here <http://doc.scrapy.org/en/latest/topics/settings.html>`_. Redis ----- **REDIS_HOST** Default: ``'localhost'`` The Redis host. **REDIS_PORT** Default: ``6379`` The port to use when connecting to the ``REDIS_HOST``. Kafka ----- **KAFKA_HOSTS** Default: ``'localhost:9092'`` The Kafka host. May have multiple hosts separated by commas within the single string like ``'h1:9092,h2:9092'``. **KAFKA_TOPIC_PREFIX** Default: ``'demo'`` The Kafka Topic prefix to use when generating the outbound Kafka topics. .. _c_kafka_appid_topics: **KAFKA_APPID_TOPICS** Default: ``False`` Flag to send data to both the firehose and Application ID specific Kafka topics. If set to ``True``, results will be sent to both the ``demo.outbound_firehose`` **and** ``demo.outbound_<appid>`` Kafka topics, where ``<appid>`` is the Application ID used to submit the request. This is useful if you have many applications utilizing your cluster but only would like to listen to results for your specific application. .. _c_base64: **KAFKA_BASE_64_ENCODE** Default: ``False`` `Base64 <https://en.wikipedia.org/wiki/Base64>`_ encode the raw crawl body from the crawlers. This is useful when crawling malformed utf8 encoded pages, where json encoding throws an error. If an error occurs when encoding the crawl object in the item pipeline, there will be an error thrown and the result will be dropped. Zookeeper --------- **ZOOKEEPER_ASSIGN_PATH** Default: ``/scrapy-cluster/crawler/`` The location to store Scrapy Cluster domain specific configuration within Zookeeper **ZOOKEEPER_ID** Default: ``all`` The file identifier to read crawler specific configuration from. This file is located within the ``ZOOKEEPER_ASSIGN_PATH`` folder above. **ZOOKEEPER_HOSTS** Default: ``localhost:2181`` The zookeeper host to connect to. Scheduler --------- **SCHEDULER_PERSIST** Default: ``True`` Determines whether to clear all Redis Queues when the Scrapy Scheduler is shut down. This will wipe all domain queues for a particular spider type. **SCHEDULER_QUEUE_REFRESH** Default: ``10`` How many seconds to wait before checking for new domain queues. This is also dictated by internal Scrapy processes, so setting this any lower does not guarantee a quicker refresh time. .. _c_throttle: Throttle -------- **QUEUE_HITS** Default: ``10`` When encountering an unknown domain, throttle the domain to X number of hits within the ``QUEUE_WINDOW`` **QUEUE_WINDOW** Default: ``60`` The number of seconds to count and retain cluster hits for a particular domain. **QUEUE_MODERATED** Default: ``True`` Moderates the outbound domain request flow to evenly spread the ``QUEUE_HITS`` throughout the ``QUEUE_WINDOW``. .. _dupe_timeout: **DUPEFILTER_TIMEOUT** Default: ``600`` Number of seconds to keep **crawlid** specific duplication filters around after the latest crawl with that id has been conducted. Putting this setting too low may allow crawl jobs to crawl the same page due to the duplication filter being wiped out. **SCHEDULER_IP_REFRESH** Default: ``60`` The number of seconds to wait between refreshing the Scrapy process's public IP address. Used when doing :ref:`IP <throttle_mechanism>` based throttling. **PUBLIC_IP_URL** Default: ``'http://ip.42.pl/raw'`` The default URL to grab the Crawler's public IP Address from. **IP_ADDR_REGEX** Default: ``(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`` The regular expression used to find the Crawler's public IP Address from the ``PUBLIC_IP_URL`` response. The first element from the results of this regex will be used as the ip address. **SCHEDULER_TYPE_ENABLED** Default: ``True`` If set to true, the crawling process's spider type is taken into consideration when throttling the crawling cluster. **SCHEDULER_IP_ENABLED** Default: ``True`` If set to true, the crawling process's public IP Address is taken into consideration when throttling the crawling cluster. .. note:: For more information about Type and IP throttling, please see the :ref:`throttle <throttle_mechanism>` documentation. **SCHEUDLER_ITEM_RETRIES** Default: ``2`` Number of cycles through all known domain queues the Scheduler will take before the Spider is considered idle and waits for Scrapy to retry processing a request. Logging ------- **SC_LOGGER_NAME** Default: ``'sc-crawler'`` The Scrapy Cluster logger name. **SC_LOG_DIR** Default: ``'logs'`` The directory to write logs into. Only applicable when ``SC_LOG_STDOUT`` is set to ``False``. **SC_LOG_FILE** Default: ``'sc_crawler.log'`` The file to write the logs into. When this file rolls it will have ``.1`` or ``.2`` appended to the file name. Only applicable when ``SC_LOG_STDOUT`` is set to ``False``. **SC_LOG_MAX_BYTES** Default: ``10 * 1024 * 1024`` The maximum number of bytes to keep in the file based log before it is rolled. **SC_LOG_BACKUPS** Default: ``5`` The number of rolled file logs to keep before data is discarded. A setting of ``5`` here means that there will be one main log and five rolled logs on the system, totaling six log files. **SC_LOG_STDOUT** Default: ``True`` Log to standard out. If set to ``False``, will write logs to the file given by the ``LOG_DIR/LOG_FILE`` **SC_LOG_JSON** Default: ``False`` Log messages will be written in JSON instead of standard text messages. **SC_LOG_LEVEL** Default: ``'INFO'`` The log level designated to the logger. Will write all logs of a certain level and higher. .. note:: More information about logging can be found in the utilities :ref:`Log Factory <log_factory>` documentation. .. _c_stats: Stats ----- **STATS_STATUS_CODES** Default: ``True`` Collect Response status code metrics **STATUS_RESPONSE_CODES** Default: :: [ 200, 404, 403, 504, ] Determines the different Response status codes to collect metrics against if metrics collection is turned on. **STATS_CYCLE** Default: ``5`` How often to check for expired keys and to roll the time window when doing stats collection. **STATS_TIMES** Default: :: [ 'SECONDS_15_MINUTE', 'SECONDS_1_HOUR', 'SECONDS_6_HOUR', 'SECONDS_12_HOUR', 'SECONDS_1_DAY', 'SECONDS_1_WEEK', ] Rolling time window settings for statistics collection, the above settings indicate stats will be collected for the past 15 minutes, the past hour, the past 6 hours, etc. .. note:: For more information about stats collection, please see the :ref:`stats_collector` documentation.
{ "content_hash": "e100f8edc5293a9f2ca6366f3440eff7", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 416, "avg_line_length": 25.74131274131274, "alnum_prop": 0.7183140842957852, "repo_name": "quixey/scrapy-cluster", "id": "b379cd0996b2f81ff37f88f3dabe49bbd5e73e10", "size": "6667", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "docs/topics/crawler/settings.rst", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "46003" }, { "name": "Makefile", "bytes": "165" }, { "name": "Python", "bytes": "292759" }, { "name": "Shell", "bytes": "8082" } ], "symlink_target": "" }
// Copyright (c) 2014-2020, Justin Crawford <Justin@stacksmash.net> // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Just don't even bother formatting this file... It's format is too specific and non-standard to the rest // of the codebase that formatting it with clang-format would be incredibly unreadable. // clang-format off #pragma once #include <string> #include <cstring> #include <vector> #include <map> #include <algorithm> //For std::transform for Flux::string.tolower() and toupper() #include <sstream> #include <iomanip> // For std::setprecision #include <bitset> #include <cmath> // Required for nlohmann's JSON.hpp #include <ios> #include <string_view> #include <experimental/filesystem> // For conversion from std::experimental::filesystem::path to our str. // workaround for now until the filesystem lib has moved out of experimental. namespace std { namespace filesystem = std::experimental::filesystem; } // Include the fmt library via spdlog. #include "spdlog/fmt/fmt.h" #include "spdlog/fmt/ostr.h" #include "sysconf.h" /* we include the config header from ./configure */ #include "nlohmann/json.hpp" /* Include json.hpp */ using json = nlohmann::json; #ifdef __GNUC__ # define DEPRECATED(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) # define DEPRECATED(func) __declspec(deprecated) func #else # define DEPRECATED(func) func #endif typedef std::basic_string<char, std::char_traits<char>, std::allocator<char> > base_string; namespace Flux { class string; } // Make sure we can use fmtlib's udl's. using namespace fmt::literals; // a pseudonym for bit-wise flags. typedef unsigned long flags_t; /** Percent-encoding map for HTML output **/ static const char* url_escape_table[256] = { "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", "%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f", "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", 0, 0, "%2a", "%2b", "%2c", "%2d", 0, "%2f", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "%3a", "%3b", "%3c", "%3d", "%3e", "%3f", "%40", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "%5b", "%5c", "%5d", "%5e", 0, "%60", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "%7b", "%7c", "%7d", 0, "%7f", "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87", "%88", "%89", "%8a", "%8b", "%8c", "%8d", "%8e", "%8f","%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97", "%98", "%99","%9a", "%9b", "%9c", "%9d", "%9e", "%9f", "%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7", "%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af", "%b0", "%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7", "%b8", "%b9", "%ba", "%bb", "%bc", "%bd", "%be", "%bf", "%c0", "%c1", "%c2", "%c3", "%c4", "%c5", "%c6", "%c7", "%c8", "%c9", "%ca", "%cb", "%cc", "%cd", "%ce", "%cf", "%d0", "%d1", "%d2", "%d3", "%d4", "%d5", "%d6", "%d7", "%d8", "%d9", "%da", "%db", "%dc", "%dd", "%de", "%df", "%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6", "%e7", "%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef", "%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7", "%f8", "%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff" }; /** The ci namespace contains a number of helper classes. */ namespace ci { /** The ci_char_traits class is used for ASCII-style comparison of strings. * This class is used to implement ci::string, a case-insensitive, ASCII- * comparing string class. */ struct ci_char_traits : std::char_traits<char> { /** Check if two chars match. * @param c1st First character * @param c2nd Second character * @return true if the characters are equal */ static bool eq(char c1st, char c2nd); /** Check if two chars do NOT match. * @param c1st First character * @param c2nd Second character * @return true if the characters are unequal */ static bool ne(char c1st, char c2nd); /** Check if one char is less than another. * @param c1st First character * @param c2nd Second character * @return true if c1st is less than c2nd */ static bool lt(char c1st, char c2nd); /** Compare two strings of size n. * @param str1 First string * @param str2 Second string * @param n Length to compare to * @return similar to strcmp, zero for equal, less than zero for str1 * being less and greater than zero for str1 being greater than str2. */ static int compare(const char *str1, const char *str2, size_t n); /** Find a char within a string up to position n. * @param s1 String to find in * @param n Position to search up to * @param c Character to search for * @return Pointer to the first occurance of c in s1 */ static const char *find(const char *s1, int n, char c); }; /** This typedef declares ci::string based upon ci_char_traits. */ typedef std::basic_string<char, ci_char_traits, std::allocator<char> > string; struct less { /** Compare two Flux::strings as ci::strings and find which one is less * @param s1 The first string * @param s2 The second string * @return true if s1 < s2, else false */ bool operator()(const Flux::string &s1, const Flux::string &s2) const; }; } /** Operator >> for ci::string */ inline std::istream &operator>>(std::istream &is, ci::string &str) { base_string tmp; is >> tmp; str = tmp.c_str(); return is; } /** Define operators for + and == with ci::string to base_string for easy assignment * and comparison * * Operator + */ inline base_string operator+(base_string &leftval, ci::string &rightval) { return leftval + base_string(rightval.c_str()); } /** Define operators for + and == with ci::string to base_string for easy assignment * and comparison * * Operator + */ inline ci::string operator+(ci::string &leftval, base_string &rightval) { return leftval + ci::string(rightval.c_str()); } /** Define operators for + and == with ci::string to base_string for easy assignment * and comparison * * Operator == */ inline bool operator==(const base_string &leftval, const ci::string &rightval) { return leftval.c_str() == rightval; } /** Define operators for + and == with ci::string to base_string for easy assignment * and comparison * * Operator == */ inline bool operator==(const ci::string &leftval, const base_string &rightval) { return leftval == rightval.c_str(); } /** Define operators != for ci::string to base_string for easy comparison */ inline bool operator!=(const ci::string &leftval, const base_string &rightval) { return !(leftval == rightval.c_str()); } /** Define operators != for ci::string to irc::string for easy comparison */ inline bool operator!=(const base_string &leftval, const ci::string &rightval) { return !(leftval.c_str() == rightval); } namespace Flux { class string { private: base_string _string; public: typedef base_string::iterator iterator; typedef base_string::const_iterator const_iterator; typedef base_string::reverse_iterator reverse_iterator; typedef base_string::const_reverse_iterator const_reverse_iterator; typedef base_string::size_type size_type; static const size_type npos = static_cast<size_type>(-1); string() : _string("") { } // number conversions. explicit string(int i) { this->_string = std::to_string(i); } explicit string(long i) { this->_string = std::to_string(i); } explicit string(long long i) { this->_string = std::to_string(i); } explicit string(unsigned i) { this->_string = std::to_string(i); } explicit string(unsigned long i) { this->_string = std::to_string(i); } explicit string(unsigned long long i) { this->_string = std::to_string(i); } explicit string(float i) { this->_string = std::to_string(i); } explicit string(double i) { this->_string = std::to_string(i); } explicit string(long double i) { this->_string = std::to_string(i); } // Other conversions string(char chr) : _string(1, chr) { } string(size_type n, char chr) : _string(n, chr) { } string(const json &j) : _string(j.dump()) { } string(std::string_view &s) : _string(s) { } string(const std::filesystem::path &p) : _string(p.native()) { } string(const char *_str) : _string(_str) { } string(const char *_str, size_type len) : _string(_str, len) { } string(const base_string &_str) : _string(_str) { } string(const ci::string &_str) : _string(_str.c_str()) { } string(const string &_str, size_type pos = 0, size_type n = npos) : _string(_str._string, pos, n) { } string(const std::vector<string> &_vec, const std::string &delim) { this->join(_vec, delim); } string(const std::vector<string> &_vec) { this->join(_vec, " "); } template <class InputIterator> string(InputIterator first, InputIterator last) : _string(first, last) { } // Wide-character functions. string(wchar_t chr) : string(&chr, 1) { } string(const wchar_t *_str) : string(_str, std::wcslen(_str)) { } // Call the constructor below string(const wchar_t *_str, size_type sz) : _string() { char *str = new char[sz]; std::wcstombs(str, _str, sz); this->_string = str; delete[] str; } // Used for formatting strings using the user-defined literal below. template<typename... Args> string operator ()(const Args&... args) { return fmt::format(this->_string, args...); } inline string &operator=(char chr) { this->_string = chr; return *this; } inline string &operator=(const char *_str) { this->_string = _str; return *this; } inline string &operator=(const base_string &_str) { this->_string = _str; return *this; } inline string &operator=(const ci::string &_str) { this->_string = _str.c_str(); return *this; } inline string &operator=(const string &_str) { if (this != &_str) this->_string = _str._string; return *this; } inline string &operator=(const json &j) { this->_string = j.dump(); return *this; } inline bool operator==(const char *_str) const { return this->_string == _str; } inline bool operator==(const base_string &_str) const { return this->_string == _str; } inline bool operator==(const ci::string &_str) const { return ci::string(this->_string.c_str()) == _str; } inline bool operator==(const string &_str) const { return this->_string == _str._string; } inline bool equals_cs(const char *_str) const { return this->_string == _str; } inline bool equals_cs(const base_string &_str) const { return this->_string == _str; } inline bool equals_cs(const ci::string &_str) const { return this->_string == _str.c_str(); } inline bool equals_cs(const string &_str) const { return this->_string == _str._string; } inline bool equals_ci(const char *_str) const { return ci::string(this->_string.c_str()) == _str; } inline bool equals_ci(const base_string &_str) const { return ci::string(this->_string.c_str()) == _str.c_str(); } inline bool equals_ci(const ci::string &_str) const { return _str == this->_string.c_str(); } inline bool equals_ci(const string &_str) const { return ci::string(this->_string.c_str()) == _str._string.c_str(); } inline bool operator!=(const char *_str) const { return !operator==(_str); } inline bool operator!=(const base_string &_str) const { return !operator==(_str); } inline bool operator!=(const ci::string &_str) const { return !operator==(_str); } inline bool operator!=(const string &_str) const { return !operator==(_str); } inline string &operator+=(char chr) { this->_string += chr; return *this; } inline string &operator+=(const char *_str) { this->_string += _str; return *this; } inline string &operator+=(const base_string &_str) { this->_string += _str; return *this; } inline string &operator+=(const ci::string &_str) { this->_string += _str.c_str(); return *this; } inline string &operator+=(const string &_str) { if (this != &_str) this->_string += _str._string; return *this; } inline const string operator+(char chr) const { return string(*this) += chr; } inline const string operator+(const char *_str) const { return string(*this) += _str; } inline const string operator+(const base_string &_str) const { return string(*this) += _str; } inline const string operator+(const ci::string &_str) const { return string(*this) += _str; } inline const string operator+(const string &_str) const { return string(*this) += _str; } friend const string operator+(char chr, const string &str); friend const string operator+(const char *_str, const string &str); friend const string operator+(const base_string &_str, const string &str); friend const string operator+(const ci::string &_str, const string &str); friend const string operator+(const string &str, const base_string &_str); inline bool operator<(const string &_str) const { return this->_string < _str._string; } inline const char *c_str() const { return this->_string.c_str(); } // NOTE: this is only used for idiot libraries which accept char* instead of const char* inline char *cc_str() const { return const_cast<char*>(this->_string.c_str()); } inline const char *data() const { return this->_string.data(); } inline ci::string ci_str() const { return ci::string(this->_string.c_str()); } inline const base_string &std_str() const { return this->_string; } inline base_string &std_str() { return this->_string; } inline string url_str() const { string ret; const char *t = this->_string.c_str(); while(t && *t) { int c = *t; const char *e = url_escape_table[c]; if(e) ret += e; else ret += c; t++; } return ret; } inline std::vector<string> split(const string &delim) const { size_t start = 0, end = 0; std::vector<string> ret; while (end != string::npos) { end = this->_string.find(delim._string, start); // If at end, use length=maxLength. Else use length=end-start. ret.push_back(this->_string.substr(start, (end == string::npos) ? string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ((end > (string::npos - delim.size())) ? string::npos : end + delim.size()); } return ret; } inline string join(const std::vector<string> &_vec, const string &delim) { for (auto it = _vec.begin(), it_end = _vec.end(); it != it_end; ++it) { if (it + 1 == it_end) this->_string += (*it)._string; else this->_string += (*it)._string + delim._string; } return *this; } inline bool empty() const { return this->_string.empty(); } inline size_type length() const { return this->_string.length(); } inline size_type size() const { return this->_string.size(); } inline size_type capacity() const { return this->_string.capacity(); } inline size_type max_size() const { return this->_string.max_size(); } inline void swap(string &_str) { this->_string.swap(_str._string); } inline void push_back(char c) { return this->_string.push_back(c); } inline void push_back(const string &_str) { if (this != &_str) this->_string += _str._string; } inline void resize(size_type n) { return this->_string.resize(n); } inline string erase(size_t pos = 0, size_t n = base_string::npos) { return this->_string.erase(pos, n); } inline iterator erase(const iterator &i) { return this->_string.erase(i); } inline iterator erase(const iterator &first, const iterator &last) { return this->_string.erase(first, last); } //inline void erase(size_type pos = 0, size_type n = base_string::npos) { this->_string.erase(pos, n); } inline string trim() { while(!this->_string.empty() && isspace(this->_string[0])) this->_string.erase(this->_string.begin()); while(!this->_string.empty() && isspace(this->_string[this->_string.length() - 1])) this->_string.erase(this->_string.length() - 1); return *this; } inline string tolower() { std::transform(_string.begin(), _string.end(), _string.begin(), ::tolower); return *this; } inline string toupper() { std::transform(_string.begin(), _string.end(), _string.begin(), ::toupper); return *this; } inline string tolower() const { base_string tmp = this->_string; std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); return tmp; } inline string toupper() const { base_string tmp = this->_string; std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper); return tmp; } inline void clear() { this->_string.clear(); } inline bool search(const string &_str) { if(_string.find(_str._string) != base_string::npos) return true; return false; } inline bool search(const string &_str) const { if(_string.find(_str._string) != base_string::npos) return true; return false; } inline bool search_ci(const string &_str) { if(ci::string(this->_string.c_str()).find(ci::string(_str.c_str())) != ci::string::npos) return true; return false; } inline bool search_ci(const string &_str) const { if(ci::string(this->_string.c_str()).find(ci::string(_str.c_str())) != ci::string::npos) return true; return false; } inline size_type find(const string &_str, size_type pos = 0) const { return this->_string.find(_str._string, pos); } inline size_type find(char chr, size_type pos = 0) const { return this->_string.find(chr, pos); } inline size_type find_ci(const string &_str, size_type pos = 0) const { return ci::string(this->_string.c_str()).find(ci::string(_str._string.c_str()), pos); } inline size_type find_ci(char chr, size_type pos = 0) const { return ci::string(this->_string.c_str()).find(chr, pos); } inline size_type rfind(const string &_str, size_type pos = npos) const { return this->_string.rfind(_str._string, pos); } inline size_type rfind(char chr, size_type pos = npos) const { return this->_string.rfind(chr, pos); } inline size_type rfind_ci(const string &_str, size_type pos = npos) const { return ci::string(this->_string.c_str()).rfind(ci::string(_str._string.c_str()), pos); } inline size_type rfind_ci(char chr, size_type pos = npos) const { return ci::string(this->_string.c_str()).rfind(chr, pos); } inline size_type find_first_of(const string &_str, size_type pos = 0) const { return this->_string.find_first_of(_str._string, pos); } inline size_type find_first_of_ci(const string &_str, size_type pos = 0) const { return ci::string(this->_string.c_str()).find_first_of(ci::string(_str._string.c_str()), pos); } inline size_type find_first_not_of(const string &_str, size_type pos = 0) const { return this->_string.find_first_not_of(_str._string, pos); } inline size_type find_first_not_of_ci(const string &_str, size_type pos = 0) const { return ci::string(this->_string.c_str()).find_first_not_of(ci::string(_str._string.c_str()), pos); } inline size_type find_last_of(const string &_str, size_type pos = npos) const { return this->_string.find_last_of(_str._string, pos); } inline size_type find_last_of_ci(const string &_str, size_type pos = npos) const { return ci::string(this->_string.c_str()).find_last_of(ci::string(_str._string.c_str()), pos); } inline size_type find_last_not_of(const string &_str, size_type pos = npos) const { return this->_string.find_last_not_of(_str._string, pos); } inline size_type find_last_not_of_ci(const string &_str, size_type pos = npos) const { return ci::string(this->_string.c_str()).find_last_not_of(ci::string(_str._string.c_str()), pos); } inline bool is_number_only() const { return this->find_first_not_of("0123456789.-") == npos; } inline bool is_pos_number_only() const { return this->find_first_not_of("0123456789.") == npos; } inline string replace(size_type pos, size_type n, const string &_str) { return string(this->_string.replace(pos, n, _str._string)); } inline string replace(size_type pos, size_type n, const string &_str, size_type pos1, size_type n1) { return string(this->_string.replace(pos, n, _str._string, pos1, n1)); } inline string replace(size_type pos, size_type n, size_type n1, char chr) { return string(this->_string.replace(pos, n, n1, chr)); } inline string replace(iterator first, iterator last, const string &_str) { return string(this->_string.replace(first, last, _str._string)); } inline string append(const string &_str) { return this->_string.append(_str._string); } inline string append(const string &_str, size_t pos, size_t n) { return this->_string.append(_str._string, pos, n); } inline string append(const char* s, size_t n) { return this->_string.append(s, n); } inline string append(const char* s) { return this->_string.append(s); } inline string append(size_t n, char c) { return this->_string.append(n, c); } inline int compare(const string &_str) const { return this->_string.compare(_str._string); } inline int compare(const char *s) const { return this->_string.compare(s); } inline int compare(size_t pos1, size_t n1, const string &_str) const { return this->_string.compare(pos1, n1, _str._string); } inline int compare(size_t pos1, size_t n1, const char *s) const { return this->_string.compare(pos1, n1, s); } inline int compare(size_t pos1, size_t n1, const string &_str, size_t pos2, size_t n2) const { return this->_string.compare(pos1, n1, _str._string, pos2, n2); } inline int compare(size_t pos1, size_t n1, const char *s, size_t n2) const { return this->_string.compare(pos1, n1, s, n2); } inline string insert(size_t pos1, const string &_str) { return this->_string.insert(pos1, _str._string); } inline string insert(size_t pos1, const string &_str, size_t pos2, size_t n) { return this->_string.insert(pos1, _str._string, pos2, n); } inline string insert(size_t pos1, const char* s, size_t n) { return this->_string.insert(pos1, s, n); } inline string insert(size_t pos1, const char* s) { return this->_string.insert(pos1, s); } inline string insert(size_t pos1, size_t n, char c) { return this->_string.insert(pos1, n, c); } inline iterator insert(iterator p, char c) { return this->_string.insert(p, c); } inline void insert(iterator p, size_t n, char c) { this->_string.insert(p, n, c); } template<class InputIterator> inline void insert(iterator p, InputIterator first, InputIterator last) { return this->_string.insert(p, first, last); } inline string assign(const string &str) { return this->_string.assign(str._string); } inline string assign(const string &str, size_t pos, size_t n) { return this->_string.assign(str._string, pos, n); } inline string assign(const char* s, size_t n) { return this->_string.assign(s, n); } inline string assign(const char* s) { return this->_string.assign(s); } inline string assign(size_t n, char c) { return this->_string.assign(n, c); } template <class InputIterator> inline string assign(InputIterator first, InputIterator last) { return this->_string.assign(first, last); } inline string replace(iterator first, iterator last, size_type n, char chr) { return string(this->_string.replace(first, last, n, chr)); } template <class InputIterator> inline string replace(iterator first, iterator last, InputIterator f, InputIterator l) { return string(this->_string.replace(first, last, f, l)); } inline string replace_all_cs(const string &_orig, const string &_repl) const { Flux::string new_string = *this; size_type pos = new_string.find(_orig), orig_length = _orig.length(), repl_length = _repl.length(); while (pos != npos) { new_string = new_string.substr(0, pos) + _repl + new_string.substr(pos + orig_length); pos = new_string.find(_orig, pos + repl_length); } return new_string; } inline string replace_all_ci(const string &_orig, const string &_repl) const { Flux::string new_string = *this; size_type pos = new_string.find_ci(_orig), orig_length = _orig.length(), repl_length = _repl.length(); while (pos != npos) { new_string = new_string.substr(0, pos) + _repl + new_string.substr(pos + orig_length); pos = new_string.find_ci(_orig, pos + repl_length); } return new_string; } inline string substr(size_type pos = 0, size_type n = npos) const { return this->_string.substr(pos, n).c_str(); } inline iterator begin() { return this->_string.begin(); } inline const_iterator begin() const { return this->_string.begin(); } inline iterator end() { return this->_string.end(); } inline const_iterator end() const { return this->_string.end(); } inline reverse_iterator rbegin() { return this->_string.rbegin(); } inline const_reverse_iterator rbegin() const { return this->_string.rbegin(); } inline reverse_iterator rend() { return this->_string.rend(); } inline const_reverse_iterator rend() const { return this->_string.rend(); } inline const char &at(size_t pos) const { return this->_string.at(pos); } inline char &at(size_t pos) { return this->_string.at(pos); } inline std::allocator<char> get_allocator() const { return this->_string.get_allocator(); } inline char &operator[](size_type n) { return this->_string[n]; } inline const char &operator[](size_type n) const { return this->_string[n]; } inline string isolate(char b, char e) const { string to_find; size_t pos = _string.find(b); pos += 1; for (unsigned i = pos; i < _string.length(); i++) { if (_string[i] == e) break; else to_find = to_find+_string[i]; } return to_find; } // Short Format intended to be used with string literals // Eg: "the %s fox jumps %d times over the fence!"_F.format("quick brown", 10); template<typename... Args> string format(const Args&... args) { return fmt::format(this->_string, args...); } /* Strip Return chars */ inline string strip() { string new_buf = *this; new_buf = new_buf.replace_all_cs("\n", ""); new_buf = new_buf.replace_all_cs("\r", ""); return new_buf; } inline string strip() const { string new_buf = *this; new_buf = new_buf.replace_all_cs("\n", ""); new_buf = new_buf.replace_all_cs("\r", ""); return new_buf; } /* Strip specific chars */ inline string strip(const char &_delim) { string new_buf = *this; new_buf = new_buf.replace_all_cs(_delim, ""); return new_buf; } inline string strip(const char &_delim) const { string new_buf = *this; new_buf = new_buf.replace_all_cs(_delim, ""); return new_buf; } /* Cast into an integer */ inline operator int() { return std::stoi(this->_string); } /* Cast into a long integer */ inline operator long() { return std::stol(this->_string); } /* Cast to long long integer */ inline operator long long() { return std::stoll(this->_string); } /* Cast to unsigned long integer */ inline operator unsigned long() { return std::stoul(this->_string); } /* Cast to unsigned long long integer */ inline operator unsigned long long() { return std::stoull(this->_string); } /* Cast into a float */ inline operator float() { return std::stof(this->_string); } /* Cast into a double */ inline operator double() { return std::stod(this->_string); } /* Cast to long double */ inline operator long double() { return std::stold(this->_string); } friend std::ostream &operator<<(std::ostream &os, const string &_str); friend std::istream &operator>>(std::istream &os, string &_str); }; //end of string class template<typename T> class map : public std::map<string, T> { }; template<typename T> class insensitive_map : public std::map<string, T, ci::less> { }; typedef std::vector<string> vector; inline std::ostream &operator<<(std::ostream &os, const string &_str) { return os << _str._string; } inline std::istream &operator>>(std::istream &os, string &_str) { return os >> _str._string; } inline const string operator+(char chr, const string &str) { string tmp(chr); tmp += str; return tmp; } inline const string operator+(const char *_str, const string &str) { string tmp(_str); tmp += str; return tmp; } inline const string operator+(const base_string &_str, const string &str) { string tmp(_str); tmp += str; return tmp; } inline const string operator+(const ci::string &_str, const string &str) { string tmp(_str); tmp += str; return tmp; } // For json.hpp compatibility for Flux::string inline void to_json(json &j, const string &str) { j = json(str.std_str()); } inline void from_json(const json &j, string &str) { str = j.dump(); } template<typename... Args> Flux::string format(const Flux::string &str, const Args&... args) { return fmt::format(str.std_str(), args...); } }//end of namespace // User-defined literal for Flux::string. inline Flux::string operator "" _F(const char *str, size_t sz) { return Flux::string(str, sz); } // Formatter for {fmt} library inline void format_arg(fmt::BasicFormatter<char> &f, const char *&format_str, const Flux::string &s) { f.writer().write(s.c_str()); }
{ "content_hash": "8717ce693e4414a87cba182fc0583f15", "timestamp": "", "source": "github", "line_count": 618, "max_line_length": 188, "avg_line_length": 48.81391585760518, "alnum_prop": 0.6469320780985846, "repo_name": "Justasic/libjustasic", "id": "2665b319a250156927317a9911468bbfd6ccc550", "size": "30167", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/Flux.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "64034" } ], "symlink_target": "" }
package com.arm.carp.pencil import scala.collection.mutable.HashMap import scala.collection.mutable.HashSet /** * Represents the call graph of the PENCIL program. * * Currently it support the following: * - Check for recursion. */ class CallGraph { private val graph = new HashMap[Function, HashSet[Function]] /** Record new call. */ def addCall(callee: Function, called: Function) = { graph.get(callee) match { case None => graph.put(callee, HashSet(called)) case Some(calls) => calls.add(called) } } private def getCalls(in: Function) = { graph.get(in) match { case Some(calls) => calls case None => HashSet[Function]() } } private def DFS(curr: Function, visited: Set[Function]): Option[Function] = { if (visited.contains(curr)) { Some(curr) } else { getCalls(curr).find(f => DFS(f, visited + curr).isDefined) } } /** * Return all functions called directly or indirectly by the given function. */ def getAllCallees(in: Function): HashSet[Function] = { val calls = getCalls(in) calls.foreach(i => calls ++= getAllCallees(i)) calls } /** * Check for recursion. * * @return Function, which is recursively calling itself (directly or indirectly). */ def getRecursion():Option[Function] = { if(graph.isEmpty) { None } else { DFS(graph.head._1, Set()) } } def clear = graph.clear }
{ "content_hash": "a411729bd9a39f66e3a727ab79fa3116", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 85, "avg_line_length": 22.703125, "alnum_prop": 0.629043358568479, "repo_name": "Meinersbur/pencil", "id": "9682e77b199e7bb57126f2cb573003ba14ab6b1a", "size": "2574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scala/com/arm/carp/pencil/CallGraph.scala", "mode": "33188", "license": "mit", "language": [ { "name": "GAP", "bytes": "13234" }, { "name": "Makefile", "bytes": "1261" }, { "name": "Scala", "bytes": "259916" }, { "name": "Shell", "bytes": "8804" } ], "symlink_target": "" }
function QuestionProgramWeightsModel( id, surveyQuestionId, programId) { var _self = this; _self.Id = ko.observable(id); _self.SurveyQuestionId = ko.observable(surveyQuestionId); _self.ProgramId = ko.observable(programId); } function QuestionProgramWeights_ViewModel() { //#region member vars testVariable_QuestionProgramWeights = 'QuestionProgramWeights viewmodel bound'; var _self = this; var dummyQuestionProgramWeightsModel = new QuestionProgramWeightsModel(0,0,0); var obsModels = new Array(); var data; _self.addedQuestionProgramWeightsModel = new ko.observable(dummyQuestionProgramWeightsModel); _self.editedQuestionProgramWeightsModel = ko.observable(dummyQuestionProgramWeightsModel); _self.removedQuestionProgramWeightsModel = ko.observable(dummyQuestionProgramWeightsModel); _self.selectedQuestionProgramWeightsModel = ko.observable(dummyQuestionProgramWeightsModel); _self.candidateQuestionProgramWeightsModel = ko.observable(dummyQuestionProgramWeightsModel); _self.questionProgramWeightsModels = ko.observableArray([]); //#endregion //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ // fill models _self.initAllQuestionProgramWeightsModels = function(callbackSuccess, callbackFail){ $.ajax({ url: '/api/Liveo.Platform/QuestionProgramWeightsApi', dataType: 'json', success: function (data) { for (var i = 0; i < data.length; i++) { obsModels.push(new QuestionProgramWeightsModel(data[i].Id, data[i].SurveyQuestionId, data[i].ProgramId)); } _self.questionProgramWeightsModels(obsModels); if(callbackSuccess){ callbackSuccess(obsModels.length); } }, error: function (xhr, textStatus, errorThrown) { if(callbackFail){ callbackFail('Failed to get QuestionProgramWeights items '); } } }); } _self.beginEditedQuestionProgramWeightsModel = function (model, formlink) { _self.editedQuestionProgramWeightsModel(model); if (formlink) { $('[link="' + formlink + '"]').click(); } } _self.beginCandidateQuestionProgramWeightsModel = function (formlink) { _self.candidateQuestionProgramWeightsModel(dummyQuestionProgramWeightsModel); if (formlink) { $('[link="' + formlink + '"]').click(); } } _self.beginRemoveQuestionProgramWeightsModel = function (model, formlink) { _self.removedQuestionProgramWeightsModel(model); if (formlink) { $('[link="' + formlink + '"]').click(); } } _self.commitEditedQuestionProgramWeightsModel = function (callbackSuccess, callbackFail) { $.ajax('/api/Liveo.Platform/QuestionProgramWeightsApi?Id=' + _self.editedQuestionProgramWeightsModel().Id(), { data: ko.toJSON(_self.editedQuestionProgramWeightsModel()), type: 'put', contentType: 'application/json', dataType: 'json', success: function () { //update the observable for (var i = 0; i < _self.questionProgramWeightsModels().length; i++) { if (_self.questionProgramWeightsModels()[i].Id() == _self.editedQuestionProgramWeightsModel().Id()) { _self.questionProgramWeightsModels.replace(_self.questionProgramWeightsModels()[i], _self.editedQuestionProgramWeightsModel()); break; } } if (callbackSuccess) { callbackSuccess(_self.editedQuestionProgramWeightsModel().Id()); } console.log('Success edited QuestionProgramWeights item ' + _self.editedQuestionProgramWeightsModel().Id() + '.'); }, error: function (xhr, textStatus, errorThrown) { if (callbackFail) { callbackFail(errorThrown); } console.log('Failed to edit item ' + _self.editedQuestionProgramWeightsModel().Id() + '.'); } }); } _self.commitCandidateQuestionProgramWeightsModel = function (callbackSuccess, callbackFail) { var addedModel; var result = $.ajax('/api/Liveo.Platform/QuestionProgramWeightsApi', { data: ko.toJSON(_self.candidateQuestionProgramWeightsModel()), type: 'post', contentType: 'application/json', dataType: 'json', success: function () { console.log('success add new QuestionProgramWeights model'); addedModel = JSON.parse(result.responseText); _self.addedQuestionProgramWeightsModel().Id(addedModel.Id); _self.addedQuestionProgramWeightsModel().SurveyQuestionId(addedModel.SurveyQuestionId); _self.addedQuestionProgramWeightsModel().ProgramId(addedModel.ProgramId); if (callbackSuccess) { callbackSuccess(addedModel.Id); } console.log('Success added QuestionProgramWeights item ' + addedModel.Id + '.'); }, error: function (xhr, textStatus, errorThrown) { if (callbackFail) { callbackFail(errorThrown); } console.log('Failed to add new QuestionProgramWeights model.'); } }); } _self.commitRemovedQuestionProgramWeightsModel = function (callbackSuccess, callbackFail) { var id; if (ko.isObservable(_self.removedQuestionProgramWeightsModel().Id)) { id = _self.removedQuestionProgramWeightsModel().Id(); } else { id = _self.removedQuestionProgramWeightsModel().Id; } $.ajax('/api/Liveo.Platform/QuestionProgramWeightsApi' + '?Id=' + id, { type: 'delete', contentType: 'application/json', dataType: 'json', success: function () { _self.questionProgramWeightsModels.remove(_self.removedQuestionProgramWeightsModel()); if (callbackSuccess) { callbackSuccess(id); } console.log('Success removed QuestionProgramWeights item ' + id + '.'); }, error: function (xhr, textStatus, errorThrown) { if (callbackFail) { callbackFail(errorThrown); } console.log('Failed to remove QuestionProgramWeights item ' + id + '.'); } }); } _self.saveQuestionProgramWeightsAll = function () { var jsonData = ko.toJSON(_self.questionProgramWeightsModels); console.log('Save whole viewmodel ' + '\r\n' + jsonData); } }
{ "content_hash": "45ad401da2e2f6b30bb88a96c9b7dc93", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 216, "avg_line_length": 40.62130177514793, "alnum_prop": 0.5992716678805535, "repo_name": "CloudMetal/Liveo.Deployment", "id": "4235a0257b9871cb1b3e6fe9afd4a1e3b6071e0f", "size": "6866", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Modules/Liveo.Platform/Scripts/Generated/viewModel_QuestionProgramWeights.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "3185825" }, { "name": "JavaScript", "bytes": "7744960" } ], "symlink_target": "" }
<html><head> <title></title> </head><body> <div class="definition"> <h1>clip()</h1> <h2>Syntax</h2> <div class="row"> <pre>with clip(stencil, channel="alpha"): </pre> </div> <h2>Description</h2> <div class="row"> <p>Sets the clipping region for a block of drawing commands. </p><p>All drawing operations within the block will be constrained by a <a href="Drawing.html#Bezier">Bezier</a>, <a href="Drawing.html#Image">Image</a>, or <a href="Typography.html#Text">Text</a> object passed as the <code>stencil</code> argument. If clipping to a path, only content <em>within</em> the filled bounds of the stencil path will be rendered (strokes will be ignored). When clipping to an image, drawing operations will have high opacity in places where the mask value is also high. </p><p>The optional <code>channel</code> arg applies only to image-based stencils and specifies which component of the stencil's pixels should be used for this calculation. If omitted it defaults to <code class="str">"alpha"</code> (if available) or <code class="str">"black"</code> level (if the image is opaque). </p><p>When an object is used as a <code>stencil</code> arg, it is ‘consumed’ by the operation and will not be directly visible on the canvas. As a result, it's perfectly safe to include calls to <a href="Primitives.html">Primitives</a> or the <a href="Primitives.html#image()">image()</a> command in the arguments list for <i>clip()</i>. </p></div> <h2>See Also</h2> <div class="row"> <p>The <a href="#mask()">mask()</a> command uses the same syntax as <i>clip()</i> but has an opposite effect. </p></div> <h2>Example</h2> <div class="row"> <div class="example"> <span><img height="125" src="../etc/ref/clip.png" width="125"/></span> <pre>with clip(poly(64,64, 50, sides=5)): image('plaid.png') </pre> </div> <div class="example"> <span><img height="125" src="../etc/ref/clip-image.png" width="125"/></span> <pre>with clip(image('logo-stencil.png')): image('plaid.png') </pre>using the <a href="../etc/ref/logo-stencil.png">logo-stencil.png</a> image </div> <div class="example"> <span><img height="125" src="../etc/ref/clip-text.png" width="125"/></span> <pre>font("Avenir", "bold", 112) with clip(text('Hi', 5, 100)): image('plaid.png') </pre> </div> </div> </div> </body></html>
{ "content_hash": "b99d1a29aaf4520ca7d015ca4462a8be", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 502, "avg_line_length": 42.08620689655172, "alnum_prop": 0.6431790249897583, "repo_name": "plotdevice/plotdevice-manual", "id": "5d5b17f31ef16ef49a6a223ed8de5411e4e01eeb", "size": "2445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ref/Compositing/commands/clip().html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "28538" }, { "name": "HTML", "bytes": "968653" }, { "name": "Python", "bytes": "27005" } ], "symlink_target": "" }
:orphan: .. Auto-generated by help-rst from "mirtk average-dofs -h" output average-dofs ============ .. program:: average-dofs Synopsis -------- :: average-dofs <dofout> <dofin>... [options] average-dofs <dofout> -dofnames <file> [options] Description ----------- .. include:: _descriptions/average-dofs.rst Input options ------------- .. option:: -target <file> Common reference image space of input transformations. If not specified and local transformations are to be averaged, the attributes of the first local transformation are used. .. option:: -dofnames <file> Text file listing input transformations and associated values. .. option:: -dofdir <dir> Directory used to make relative paths in :option:`-dofnames` text file absolute. (default: cwd) .. option:: -prefix <string> Prefix for transformation name entries in :option:`-dofnames` text file. (default: none) .. option:: -suffix <string> Suffix for transformation name entries in :option:`-dofnames` text file. (default: none) .. option:: -gaussian <mean> <sigma> Use Gaussian kernel weights. Requires :option:`-dofnames` to specify transformation values. By default, if :option:`-dofnames` is used or <sigma> is 0, the values specified in the text file are directly used as kernel weights for the averaging instead of using these values as arguments for the Gaussian kernel function. .. option:: -epsilon <value> Weight threshold. (default: 0.001) .. option:: -add-identity Assume additional identity transformation as part of input transformations. (default: none) .. option:: -add-identity-with-weight <value> Assume additional identity transformation with given value/weight. (default: none) .. option:: -add-identity-for-dofname <name> Assume identity transformation for named input transformation. Note that if this option is used, the named input transformation file which is listed in the :option:`-dofnames` list does not need to exist. (default: read input transformation from file) Average transformation options ------------------------------ .. option:: -rotation, -norotation Average rotation or assume none to be present. (default: off) .. option:: -translation, -notranslation Average translation or assume none to be present. (default: off) .. option:: -scaling, -noscaling Average scaling or assume none to be present. (default: on) .. option:: -shearing, -noshearing Average shearing or assume none to be present. (default: on) .. option:: -deformation, -nodeformation Average deformation or assume none to be present. (default: on) .. option:: -log, -nolog Whether to average local transformations in log-space. (default: yes, unless the :option:`-dofs` are averaged directly) .. option:: -log-euclidean Compute Log-Euclidean means. (default: off) .. option:: -bi-invariant Compute global bi-invariant mean, i.e., exponential barycenter. (default: on) .. option:: -dofs Average the local transformation parameters directly. (default: corresponding (dense) displacement fields are averaged) .. option:: -inverse-dofs Average inverse input transformations and invert the average again. (default: off) .. option:: -rigid Enables averaging of :option:`-translation` and :option:`-rotation` components, and disables averaging of :option:`-scaling`, :option:`-shearing`, and :option:`-deformation`. .. option:: -norigid Disables averaging of :option:`-translation` and :option:`-rotation` components. .. option:: -affine Enables averaging of :option:`-translation`, :option:`-rotation`, :option:`-scaling`, and :option:`-shearing`, components and disables output of average :option:`-deformation`. .. option:: -noaffine Disables averaging of :option:`-rotation`, :option:`-translation`, :option:`-scaling`, and :option:`-shearing` components. .. option:: -all Enables averaging of :option:`-rotation`, :option:`-translation`, :option:`-scaling`, :option:`-shearing`, and :option:`-deformation`. .. option:: -linear Force average output transformation to use linear interpolation. .. option:: -cubic Force average output transformation to use cubic B-spline interpolation. Standard options ---------------- .. option:: -v, -verbose [n] Increase/Set verbosity of output messages. (default: 0) .. option:: -debug [level] Increase/Set debug level for output of intermediate results. (default: 0) .. option:: -version [major.minor] Print version and exit or set version to emulate. .. option:: -revision Print revision (or version) number only and exit. .. option:: -h, -help Print help and exit.
{ "content_hash": "19bd400884b1882a1c95eb9029a253ef", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 98, "avg_line_length": 26.34078212290503, "alnum_prop": 0.7003181336161187, "repo_name": "stefanpsz/MIRTK", "id": "374c7b20e02580c009b8d20f183cbebf2da8e3a0", "size": "4715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Documentation/commands/average-dofs.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1226" }, { "name": "C", "bytes": "37821" }, { "name": "C++", "bytes": "13759150" }, { "name": "CMake", "bytes": "1254951" }, { "name": "Python", "bytes": "99498" }, { "name": "Shell", "bytes": "3673" } ], "symlink_target": "" }
import * as fs from 'fs'; import * as path from 'path'; import {AndroidSDK, Appium, Binary, BinaryMap, ChromeDriver, GeckoDriver, IEDriver, Standalone} from '../../lib/binaries'; import {Config} from '../../lib/config'; import {DownloadedBinary, FileManager} from '../../lib/files'; describe('file manager', () => { describe('setting up for windows', () => { let osType = 'Windows_NT'; it('should find correct binaries', () => { expect(FileManager.checkOS_(osType, ChromeDriver)).toBe(true); expect(FileManager.checkOS_(osType, IEDriver)).toBe(true); expect(FileManager.checkOS_(osType, Standalone)).toBe(true); expect(FileManager.checkOS_(osType, AndroidSDK)).toBe(true); expect(FileManager.checkOS_(osType, Appium)).toBe(true); }); it('should return the binary array', () => { let binaries = FileManager.compileBinaries_(osType); expect(binaries[Standalone.id].name).toBe((new Standalone()).name); expect(binaries[ChromeDriver.id].name).toBe((new ChromeDriver()).name); expect(binaries[IEDriver.id].name).toBe((new IEDriver()).name); expect(binaries[AndroidSDK.id].name).toBe((new AndroidSDK()).name); expect(binaries[Appium.id].name).toBe((new Appium()).name); }); }); describe('setting up for linux', () => { let osType = 'Linux'; it('should find correct binaries', () => { expect(FileManager.checkOS_(osType, ChromeDriver)).toBe(true); expect(FileManager.checkOS_(osType, IEDriver)).toBe(false); expect(FileManager.checkOS_(osType, Standalone)).toBe(true); expect(FileManager.checkOS_(osType, AndroidSDK)).toBe(true); expect(FileManager.checkOS_(osType, Appium)).toBe(true); }); it('should return the binary array', () => { let binaries = FileManager.compileBinaries_(osType); expect(binaries[Standalone.id].name).toBe((new Standalone()).name); expect(binaries[ChromeDriver.id].name).toBe((new ChromeDriver()).name); expect(binaries[AndroidSDK.id].name).toBe((new AndroidSDK()).name); expect(binaries[Appium.id].name).toBe((new Appium()).name); expect(binaries[IEDriver.id]).toBeUndefined(); }); }); describe('setting up for mac', () => { let osType = 'Darwin'; it('should find correct binaries', () => { expect(FileManager.checkOS_(osType, ChromeDriver)).toBe(true); expect(FileManager.checkOS_(osType, IEDriver)).toBe(false); expect(FileManager.checkOS_(osType, Standalone)).toBe(true); expect(FileManager.checkOS_(osType, AndroidSDK)).toBe(true); expect(FileManager.checkOS_(osType, Appium)).toBe(true); }); it('should return the binary array', () => { let binaries = FileManager.compileBinaries_(osType); expect(binaries[Standalone.id].name).toBe((new Standalone()).name); expect(binaries[ChromeDriver.id].name).toBe((new ChromeDriver()).name); expect(binaries[IEDriver.id]).toBeUndefined(); expect(binaries[AndroidSDK.id].name).toBe((new AndroidSDK()).name); expect(binaries[Appium.id].name).toBe((new Appium()).name); }); }); describe('downloaded version checks', () => { let existingFiles: string[]; let selenium = new Standalone(); let chrome = new ChromeDriver(); let android = new AndroidSDK(); let appium = new Appium(); let ie = new IEDriver(); let ostype: string; let arch: string; function setup(osType: string): void { ostype = osType; arch = 'x64'; existingFiles = [ selenium.prefix() + '2.51.0' + selenium.executableSuffix(), selenium.prefix() + '2.52.0' + selenium.executableSuffix() ]; chrome.ostype = ostype; chrome.osarch = arch; existingFiles.push(chrome.prefix() + '2.20' + chrome.suffix()); existingFiles.push(chrome.prefix() + '2.20' + chrome.executableSuffix()); existingFiles.push(chrome.prefix() + '2.21' + chrome.suffix()); existingFiles.push(chrome.prefix() + '2.21' + chrome.executableSuffix()); existingFiles.push(android.prefix() + '24.1.0' + android.suffix()); existingFiles.push(android.prefix() + '24.1.0' + android.executableSuffix()); existingFiles.push(android.prefix() + '24.1.1' + android.suffix()); existingFiles.push(android.prefix() + '24.1.1' + android.executableSuffix()); existingFiles.push(appium.prefix() + '1.6.0' + appium.suffix()); if (ostype == 'Windows_NT') { ie.ostype = ostype; ie.osarch = arch; existingFiles.push(ie.prefix() + '_Win32_2.51.0' + ie.suffix()); existingFiles.push(ie.prefix() + '_Win32_2.51.0' + ie.executableSuffix()); existingFiles.push(ie.prefix() + '_x64_2.51.0' + ie.suffix()); existingFiles.push(ie.prefix() + '_x64_2.51.0' + ie.executableSuffix()); existingFiles.push(ie.prefix() + '_Win32_2.52.0' + ie.suffix()); existingFiles.push(ie.prefix() + '_Win32_2.52.0' + ie.executableSuffix()); existingFiles.push(ie.prefix() + '_x64_2.52.0' + ie.suffix()); existingFiles.push(ie.prefix() + '_x64_2.52.0' + ie.executableSuffix()); } } describe('versions for selenium', () => { it('should find the correct version for windows', () => { setup('Windows_NT'); let downloaded = FileManager.downloadedVersions_(selenium, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('2.51.0'); expect(downloaded.versions[1]).toBe('2.52.0'); }); it('should find the correct version for mac', () => { setup('Darwin'); let downloaded = FileManager.downloadedVersions_(selenium, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('2.51.0'); expect(downloaded.versions[1]).toBe('2.52.0'); }); it('should find the correct version for mac', () => { setup('Linux'); let downloaded = FileManager.downloadedVersions_(selenium, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('2.51.0'); expect(downloaded.versions[1]).toBe('2.52.0'); }); }); describe('versions for chrome', () => { it('should find the correct version for windows', () => { setup('Windows_NT'); let downloaded = FileManager.downloadedVersions_(chrome, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('2.20'); expect(downloaded.versions[1]).toBe('2.21'); }); it('should find the correct version for mac', () => { setup('Darwin'); let downloaded = FileManager.downloadedVersions_(chrome, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('2.20'); expect(downloaded.versions[1]).toBe('2.21'); }); it('should find the correct version for linux', () => { setup('Linux'); let downloaded = FileManager.downloadedVersions_(chrome, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('2.20'); expect(downloaded.versions[1]).toBe('2.21'); }); }); describe('versions for android', () => { it('should find the correct version for windows', () => { setup('Windows_NT'); let downloaded = FileManager.downloadedVersions_(android, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('24.1.0'); expect(downloaded.versions[1]).toBe('24.1.1'); }); it('should find the correct version for mac', () => { setup('Darwin'); let downloaded = FileManager.downloadedVersions_(android, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('24.1.0'); expect(downloaded.versions[1]).toBe('24.1.1'); }); it('should find the correct version for linux', () => { setup('Linux'); let downloaded = FileManager.downloadedVersions_(android, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(2); expect(downloaded.versions[0]).toBe('24.1.0'); expect(downloaded.versions[1]).toBe('24.1.1'); }); }); describe('versions for appium', () => { it('should find the correct version for windows', () => { setup('Windows_NT'); let downloaded = FileManager.downloadedVersions_(appium, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(1); expect(downloaded.versions[0]).toBe('1.6.0'); }); it('should find the correct version for mac', () => { setup('Darwin'); let downloaded = FileManager.downloadedVersions_(appium, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(1); expect(downloaded.versions[0]).toBe('1.6.0'); }); it('should find the correct version for linux', () => { setup('Linux'); let downloaded = FileManager.downloadedVersions_(appium, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(1); expect(downloaded.versions[0]).toBe('1.6.0'); }); }); describe('versions for ie on windows', () => { it('should find the correct version for windows', () => { setup('Windows_NT'); let downloaded = FileManager.downloadedVersions_(ie, ostype, arch, existingFiles); expect(downloaded.versions.length).toBe(4); expect(downloaded.versions[0]).toBe('Win32_2.51.0'); expect(downloaded.versions[1]).toBe('x64_2.51.0'); expect(downloaded.versions[2]).toBe('Win32_2.52.0'); expect(downloaded.versions[3]).toBe('x64_2.52.0'); }); }); }); describe('configuring the CDN location', () => { describe('when no custom CDN is specified', () => { let defaults = Config.cdnUrls(); let binaries = FileManager.compileBinaries_('Windows_NT'); it('should use the default configuration for Android SDK', () => { expect(binaries[AndroidSDK.id].cdn).toEqual(defaults[AndroidSDK.id]); }); it('should use the default configuration for Appium', () => { expect(binaries[Appium.id].cdn).toEqual(defaults[Appium.id]); }); it('should use the default configuration for Chrome Driver', () => { expect(binaries[ChromeDriver.id].cdn).toEqual(defaults[ChromeDriver.id]); }); it('should use the default configuration for Gecko Driver', () => { expect(binaries[GeckoDriver.id].cdn).toEqual(defaults[GeckoDriver.id]); }); it('should use the default configuration for IE Driver', () => { expect(binaries[IEDriver.id].cdn).toEqual(defaults[IEDriver.id]); }); it('should use the default configuration for Selenium Standalone', () => { expect(binaries[Standalone.id].cdn).toEqual(defaults['selenium']); }); }); describe('when custom CDN is specified', () => { it('should configure the CDN for each binary', () => { let customCDN = 'https://my.corporate.cdn/'; let binaries = FileManager.compileBinaries_('Windows_NT', customCDN); forEachOf(binaries, binary => expect(binary.cdn).toEqual(customCDN, binary.name)); }); }); function forEachOf<T extends Binary>(binaries: BinaryMap<T>, fn: (binary: T) => void) { for (var key in binaries) { fn(binaries[key]); } } }); // TODO(cnishina): download binaries for each os type / arch combination });
{ "content_hash": "bcf97deb75c39cabd5e99a87b6233876", "timestamp": "", "source": "github", "line_count": 272, "max_line_length": 122, "avg_line_length": 43.349264705882355, "alnum_prop": 0.62674921550335, "repo_name": "chrisgedrim/webdriver-manager", "id": "97f3b437e068f3ffde2269a2cf75f7690a38715a", "size": "11791", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/files/file_manager_spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2745" }, { "name": "TypeScript", "bytes": "181578" } ], "symlink_target": "" }
<?php include($_SERVER['DOCUMENT_ROOT'].'\Includes\simple_html_dom.php'); $dir = $_SERVER['DOCUMENT_ROOT'].'\News\\'; foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $filename) { $parts = pathinfo($filename); if(is_file($filename) && $parts['extension'] == 'php' && $parts['basename'] != 'index.php'){ $filename = preg_replace("{/}", "\\", $filename); $files[] = $filename; } } arsort($files); $newJson = array(); foreach($files as $file) { $html = file_get_html($file); //break into parts foreach($html->find('.news') as $e) { // Get time and convert $time = str_replace('-', "",$e->find('.time', 0)->innertext); $time = date('Y-m-d',strtotime($time)); // Get URL and title $urlObj = $e->find('a',0); if(isset($urlObj)) { $linkText = $urlObj->innertext; $url = $urlObj->href; $urlObj->outertext = ''; }else{ $url = false; $linkText = false; } $title = $e->find('dt',0)->innertext; // Description $desc = $e->find('.description',0)->innertext; if(array_key_exists($time, $newJson)) { $newJson[$time][] = array("url" => $url, "title" => $title, "desc" => $desc, "linkText" => $linkText); }else{ $newJson[$time][] = array("url" => $url, "title" => $title, "desc" => $desc, "linkText" => $linkText); } } } print('<pre>'.json_encode($newJson, JSON_PRETTY_PRINT).'</pre>'); ?>
{ "content_hash": "fdb120978eba26ed0b2bf24508db4fce", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 114, "avg_line_length": 31.176470588235293, "alnum_prop": 0.5056603773584906, "repo_name": "stewarjs/code-bin", "id": "69cf4a1b9adb9b535eb19ae3dd894ec44d725426", "size": "1590", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "updates/processing/news.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "339" }, { "name": "JavaScript", "bytes": "284" }, { "name": "PHP", "bytes": "6211" } ], "symlink_target": "" }
<?php namespace Symfony\Cmf\Component\Routing\NestedMatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Matcher\RequestMatcherInterface; use Symfony\Cmf\Component\Routing\RouteProviderInterface; /** * A more flexible approach to matching. The route collection to match against * can be dynamically determined based on the request and users can inject * their own filters or use a custom final matching strategy. * * The nested matcher splits matching into three configurable steps: * * 1) Get potential matches from a RouteProviderInterface * 2) Apply any RouteFilterInterface to reduce the route collection * 3) Have FinalMatcherInterface select the best match of the remaining routes * * @author Larry Garfield * @author David Buchmann */ class NestedMatcher implements RequestMatcherInterface { /** * The route provider responsible for the first-pass match. * * @var RouteProviderInterface */ protected $routeProvider; /** * The final matcher. * * @var FinalMatcherInterface */ protected $finalMatcher; /** * An array of RouteFilterInterface objects. * * @var RouteFilterInterface[] */ protected $filters = array(); /** * Array of RouteFilterInterface objects, sorted. * * @var RouteFilterInterface[] */ protected $sortedFilters = array(); /** * Constructs a new NestedMatcher * * @param RouteProviderInterface $provider The route provider this matcher * should use * @param FinalMatcherInterface $final The Final Matcher to match the * routes */ public function __construct( RouteProviderInterface $provider = null, FinalMatcherInterface $final = null ) { if (null !== $provider) { $this->setRouteProvider($provider); } if (null !== $final) { $this->setFinalMatcher($final); } } /** * Sets the route provider for the matching plan. * * @param RouteProviderInterface $provider A source of routes. * * @return NestedMatcher this object to have a fluent interface */ public function setRouteProvider(RouteProviderInterface $provider) { $this->routeProvider = $provider; return $this; } /** * Adds a partial matcher to the matching plan. * * Partial matchers will be run in the order in which they are added. * * @param RouteFilterInterface $filter * @param int $priority (optional) The priority of the * filter. Higher number filters will * be used first. Defaults to 0. * * @return NestedMatcher this object to have a fluent interface */ public function addRouteFilter(RouteFilterInterface $filter, $priority = 0) { if (empty($this->filters[$priority])) { $this->filters[$priority] = array(); } $this->filters[$priority][] = $filter; $this->sortedFilters = array(); return $this; } /** * Sets the final matcher for the matching plan. * * @param FinalMatcherInterface $final The final matcher that will have to * pick the route that will be used. * * @return NestedMatcher this object to have a fluent interface */ public function setFinalMatcher(FinalMatcherInterface $final) { $this->finalMatcher = $final; return $this; } /** * {@inheritdoc} */ public function matchRequest(Request $request) { $collection = $this->routeProvider->getRouteCollectionForRequest($request); if (!count($collection)) { throw new ResourceNotFoundException(); } // Route filters are expected to throw an exception themselves if they // end up filtering the list down to 0. foreach ($this->getRouteFilters() as $filter) { $collection = $filter->filter($collection, $request); } $attributes = $this->finalMatcher->finalMatch($collection, $request); return $attributes; } /** * Sorts the filters and flattens them. * * @return RouteFilterInterface[] the filters ordered by priority */ public function getRouteFilters() { if (empty($this->sortedFilters)) { $this->sortedFilters = $this->sortFilters(); } return $this->sortedFilters; } /** * Sort filters by priority. * * The highest priority number is the highest priority (reverse sorting). * * @return RouteFilterInterface[] the sorted filters */ protected function sortFilters() { $sortedFilters = array(); krsort($this->filters); foreach ($this->filters as $filters) { $sortedFilters = array_merge($sortedFilters, $filters); } return $sortedFilters; } }
{ "content_hash": "f68083bcca37b27e6f33650636798b53", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 83, "avg_line_length": 28.642857142857142, "alnum_prop": 0.6075196623825053, "repo_name": "timplunkett/Routing", "id": "ecc11f858c46335723ae3f3d1988fafaca5b2b73", "size": "5430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NestedMatcher/NestedMatcher.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "188043" } ], "symlink_target": "" }
package org.wso2.am.integration.tests.other; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONObject; import org.testng.annotations.*; import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest; import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants; import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; import org.wso2.am.integration.test.utils.bean.APILifeCycleState; import org.wso2.am.integration.test.utils.bean.APILifeCycleStateRequest; import org.wso2.am.integration.test.utils.bean.APIResourceBean; import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import javax.ws.rs.core.Response; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; //APIM2-720:Get all endpoint URLs of a API through the store rest api //APIM2-722:Add a comment on an API through the store api manager public class APIM720GetAllEndPointsTestCase extends APIMIntegrationBaseTest { private static final Log log = LogFactory.getLog(APIM720GetAllEndPointsTestCase.class); private APIPublisherRestClient apiPublisher; private APIStoreRestClient apiStore; private static final String apiName = "EndPointTestAPI"; private static final String apiVersion = "1.0.0"; private static final String apiContext = "endpointtestapi"; private final String tags = "document"; private String tier= APIMIntegrationConstants.API_TIER.UNLIMITED; private String resTier= APIMIntegrationConstants.RESOURCE_TIER.UNLIMITED; private final String description = "testApi"; private String apiProvider; private static final String webApp = "jaxrs_basic"; private String endpointUrl; private final String endPointType = "http"; private final String visibility = "public"; private String gatewayUrl; @Factory(dataProvider = "userModeDataProvider") public APIM720GetAllEndPointsTestCase(TestUserMode userMode) { this.userMode = userMode; } @DataProvider public static Object[][] userModeDataProvider() { return new Object[][]{ new Object[]{TestUserMode.SUPER_TENANT_ADMIN}, // new Object[]{TestUserMode.TENANT_ADMIN}, }; } @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { String fileFormat = ".war"; super.init(userMode); log.info("Test Starting user mode:" + userMode); String storeURLHttp = storeUrls.getWebAppURLHttp(); apiStore = new APIStoreRestClient(storeURLHttp); String publisherURLHttp = publisherUrls.getWebAppURLHttp(); apiPublisher = new APIPublisherRestClient(publisherURLHttp); apiProvider = publisherContext.getContextTenant().getContextUser().getUserName(); //publisher login HttpResponse publisherLogin = apiPublisher.login (publisherContext.getContextTenant().getContextUser().getUserName(), publisherContext.getContextTenant().getContextUser().getPassword()); assertEquals(publisherLogin.getResponseCode(), Response.Status.OK.getStatusCode(), "Publisher Login Response Code is Mismatched: "); //store login HttpResponse loginResponse = apiStore.login(storeContext.getContextTenant().getContextUser().getUserName(), storeContext.getContextTenant().getContextUser().getPassword()); assertEquals(loginResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response code is Mismatched in Login Response"); JSONObject loginJsonObject = new JSONObject(loginResponse.getData()); assertFalse(loginJsonObject.getBoolean("error"), "Response data error in Login Request"); String uri = "customers/{id}/"; List<APIResourceBean> resourceBeanList = new ArrayList<APIResourceBean>(); resourceBeanList.add(new APIResourceBean("GET", "Application & Application User", resTier, uri)); String endpointProduction = "/services/customers/customerservice"; String endpointSandbox = "/services/customers/customerservice"; List<String> prodEndpointList = new ArrayList<String>(); prodEndpointList.add(endpointProduction); List<String> sandboxEndpointList = new ArrayList<String>(); sandboxEndpointList.add(endpointSandbox); APICreationRequestBean apiCreationRequestBean = new APICreationRequestBean(apiName, apiContext, apiVersion, apiProvider, prodEndpointList, sandboxEndpointList); apiCreationRequestBean.setEndpointType(endPointType); apiCreationRequestBean.setTier(tier); apiCreationRequestBean.setTags(tags); apiCreationRequestBean.setResourceBeanList(resourceBeanList); apiCreationRequestBean.setDescription(description); apiCreationRequestBean.setVisibility(visibility); HttpResponse apiCreateResponse = apiPublisher.addAPI(apiCreationRequestBean); assertEquals(apiCreateResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Invalid Response Code"); //assert JSON object JSONObject createApiJsonObject = new JSONObject(apiCreateResponse.getData()); assertEquals(createApiJsonObject.getBoolean("error"), false, "Error in API Creation"); HttpResponse verifyApiResponse = apiPublisher.getApi(apiName, apiProvider, apiVersion); JSONObject verifyApiJsonObject = new JSONObject(verifyApiResponse.getData()); assertFalse(verifyApiJsonObject.getBoolean("error"), "Error in Verify API Response"); //publish API APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, apiProvider, APILifeCycleState.PUBLISHED); HttpResponse statusUpdateResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); assertEquals(statusUpdateResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response Code is Mismatched"); waitForAPIDeploymentSync(apiProvider, apiName, apiVersion, APIMIntegrationConstants.IS_API_EXISTS); JSONObject statusUpdateJsonObject = new JSONObject(statusUpdateResponse.getData()); assertFalse(statusUpdateJsonObject.getBoolean("error"), "API is not published"); if (gatewayContextWrk.getContextTenant().getDomain().equals(FrameworkConstants.SUPER_TENANT_DOMAIN_NAME)) { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp(); } else { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp() + "t/" + gatewayContextWrk.getContextTenant().getDomain() + "/"; } } @Test(description = "Get All Endpoints") public void getAllEndpointUrlsTest() throws Exception { HttpResponse getApiResponse = apiStore.getAllPublishedAPIs(); assertEquals(getApiResponse.getResponseCode(), Response.Status.OK.getStatusCode()); JSONObject getApiJsonObject = new JSONObject(getApiResponse.getData()); assertFalse(getApiJsonObject.getBoolean("error"), "Response code Mismatched in Get Api Response"); JSONArray getApiJsonArray = getApiJsonObject.getJSONArray("apis"); boolean isApiAvailable = false; boolean isEndpointUrlValid = false; boolean isHttpsUrlAvailable = false; boolean isHttpUrlAvailable = false; String environmentName = "Production and Sandbox"; String environmentType = "hybrid"; for (int apiIndex = 0; apiIndex < getApiJsonArray.length(); apiIndex++) { if (getApiJsonArray.getJSONObject(apiIndex).getString("name").equals(apiName)) { isApiAvailable = true; HttpResponse getEndpointApiResponse = apiStore.getApiEndpointUrls(apiName, apiVersion, apiProvider); assertEquals(getEndpointApiResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Error in get Endpoints Response Code"); JSONObject getEndpointJsonObject = new JSONObject(getEndpointApiResponse.getData()); assertFalse(getEndpointJsonObject.getBoolean("error"), "Error in End point Urls Response"); JSONArray getEndPointUrlsJsonArray = getEndpointJsonObject.getJSONArray("endpointURLs"); for (int index = 0; index < getEndPointUrlsJsonArray.length(); index++) { if (getEndPointUrlsJsonArray.getJSONObject(index).getString("environmentURLs").contains(apiContext)) { isEndpointUrlValid = true; assertTrue(getEndPointUrlsJsonArray.getJSONObject(index). getString("environmentName").equalsIgnoreCase(environmentName), "Error in environment Name"); assertTrue(getEndPointUrlsJsonArray.getJSONObject(index). getString("environmentType").equalsIgnoreCase(environmentType), "Error in environment Type"); JSONArray environmentUrlsArray = getEndPointUrlsJsonArray. getJSONObject(index).getJSONArray("environmentURLs"); Map<String, String> urlMap = new HashMap<String, String>(); for (int mapIndex = 0; mapIndex < environmentUrlsArray.length(); mapIndex++) { String jsonArrayElement = environmentUrlsArray.getString(mapIndex); String[] keyValue = jsonArrayElement.split("="); urlMap.put(keyValue[0], keyValue[1]); URL url = new URL(keyValue[1]); if (keyValue[0].equals("https")) { isHttpsUrlAvailable = true; assertEquals(url.getProtocol(), keyValue[0], "Error in URL Protocol"); assertEquals(url.getPath(), "/" + apiContext + "/" + apiVersion, "Error in URL Path"); } else if (keyValue[0].equals("http")) { isHttpUrlAvailable = true; assertEquals(url.getProtocol(), keyValue[0], "Error in URL Protocol"); assertEquals(url.getPath(), "/" + apiContext + "/" + apiVersion, "Error in URL Path"); } if (isHttpsUrlAvailable == true && isHttpUrlAvailable == true) { break; } } } } break; } } assertTrue(isHttpsUrlAvailable, "Error: Https Url is mismatched"); assertTrue(isHttpUrlAvailable, "Error: Http Url is mismatched"); assertTrue(isEndpointUrlValid, "Error: EndPoint Url is not found"); assertTrue(isApiAvailable, "Error: Api is not available in Store"); } @Test(description = "Add Comments", dependsOnMethods = "getAllEndpointUrlsTest") public void addCommentTest() throws Exception { apiProvider = storeContext.getContextTenant().getContextUser().getUserName(); String comment = "testComment"; HttpResponse addCommentResponse = apiStore.addComment(apiName, apiVersion, apiProvider, comment); assertEquals(addCommentResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Error in Add Comment Response"); JSONObject addCommentJsonObject = new JSONObject(addCommentResponse.getData()); assertFalse(addCommentJsonObject.getBoolean("error"), "Error in Add Comment Response"); } @AfterClass(alwaysRun = true) public void destroy() throws Exception { apiProvider = publisherContext.getContextTenant().getContextUser().getUserName(); HttpResponse deleteApiResponse = apiPublisher.deleteAPI(apiName, apiVersion, apiProvider); assertEquals(deleteApiResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Error in Delete API Response"); JSONObject deleteApiJsonObject = new JSONObject(deleteApiResponse.getData()); assertFalse(deleteApiJsonObject.getBoolean("error"), "Error in Delete API"); } }
{ "content_hash": "cd7d3f44e047d9cee5b0ca62cc21e375", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 135, "avg_line_length": 52.67338709677419, "alnum_prop": 0.6681466738115287, "repo_name": "dhanuka84/product-apim", "id": "dac8c1c85c437ed83e004d226183c55460f98c33", "size": "13761", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/APIM720GetAllEndPointsTestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "11261" }, { "name": "CSS", "bytes": "1461079" }, { "name": "HTML", "bytes": "266256" }, { "name": "Handlebars", "bytes": "2861" }, { "name": "Java", "bytes": "1742472" }, { "name": "JavaScript", "bytes": "4819241" }, { "name": "PLSQL", "bytes": "137925" }, { "name": "PLpgSQL", "bytes": "29276" }, { "name": "Shell", "bytes": "15420" }, { "name": "XSLT", "bytes": "94760" } ], "symlink_target": "" }
#include "bgfx_plugin_ui.h" #include "pd_ui.h" #include "pd_view.h" //#include "api/plugin_instance.h" //#include "core/plugin_handler.h" //#include "core/alloc.h" //#include "core/log.h" //#include "core/math.h" //#include "core/input_state.h" //#include "core/plugin_io.h" //#include "core/service.h" //#include "ui_dock.h" #include "ui_host.h" #include "imgui_setup.h" #include <imgui.h> #include <assert.h> #include "cursor.h" //#include <session/session.h> //#include <foundation/apple.h> //#include <foundation/string.h> #include <bgfx.h> //#include "core/input_state.h" //#include "ui/bgfx/cursor.h" //#include <foundation/string.h> //#include "i3wm_docking.h" #include "ui_render.h" #include <jansson.h> #ifdef _WIN32 #include <Windows.h> #endif #ifdef PRODBG_UNIX #include <X11/Xlib.h> #endif #include <bgfxplatform.h> struct ImGuiWindow; // TODO: Move to settings const int s_borderSize = 4; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct Context { int width; int height; //InputState inputState; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static Context s_context; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* void BgfxPluginUI::init(ViewPluginInstance* pluginInstance) { PrivateData* data = 0; PDUI* uiInstance = &pluginInstance->ui; *uiInstance = *s_uiFuncs; uiInstance->private_data = alloc_zero(sizeof(PrivateData)); data = (PrivateData*)uiInstance->private_data; data->name = buildName(pluginInstance->plugin->name, pluginInstance->count); data->window = 0; data->showWindow = true; data->title = 0; pluginInstance->name = data->name; } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Callback from the docking system /* void updateWindowSize(void* user_data, int x, int y, int width, int height) { ViewPluginInstance* instance = (ViewPluginInstance*)user_data; instance->rect.x = x; instance->rect.y = y; instance->rect.width = width; instance->rect.height = height; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void setCursorStyle(DockSysCursor cursor) { switch (cursor) { case DockSysCursor_SizeHorizontal: Cunsor_setType(CursorType_SizeHorizontal); break; case DockSysCursor_SizeVertical: Cunsor_setType(CursorType_SizeVertical); break; default: Cunsor_setType(CursorType_Default); break; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TODO: Move this code? static void saveUserData(struct json_t* item, void* user_data) { ViewPluginInstance* view = (ViewPluginInstance*)user_data; if (!view->plugin) return; PDSaveState saveFuncs; PluginIO_initSaveJson(&saveFuncs); PluginData* pluginData = PluginHandler_getPluginData(view->plugin); assert(pluginData); const char* pluginName = view->plugin->name; const char* filename = pluginData->filename; json_object_set_new(item, "plugin_name", json_string(pluginName)); json_object_set_new(item, "plugin_file", json_string(filename)); PDViewPlugin* viewPlugin = (PDViewPlugin*)pluginData->plugin; if (!viewPlugin->save_state) return; json_t* array = json_array(); saveFuncs.priv_data = array; viewPlugin->save_state(view->userData, &saveFuncs); json_object_set_new(item, "plugin_data", array); } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void* loadUserData(struct json_t* item) { ViewPluginInstance* view = 0; const char* pluginName = json_string_value(json_object_get(item, "plugin_name")); const char* filename = json_string_value(json_object_get(item, "plugin_file")); // if this is the case we have no plugin created (empty window) if (!strcmp(pluginName, "") && !strcmp(filename, "")) { view = (ViewPluginInstance*)alloc_zero(sizeof(ViewPluginInstance)); }else { PDLoadState loadFuncs; PluginIO_initLoadJson(&loadFuncs); PluginData* pluginData = PluginHandler_findPlugin(0, filename, pluginName, true); if (!pluginData) view = (ViewPluginInstance*)alloc_zero(sizeof(ViewPluginInstance)); else view = g_pluginUI->createViewPlugin(pluginData); PDViewPlugin* viewPlugin = (PDViewPlugin*)pluginData->plugin; json_t* pluginJsonData = json_object_get(item, "plugin_data"); if (pluginJsonData && viewPlugin && viewPlugin->load_state) { SessionLoadState load_state = { pluginJsonData, (int)json_array_size(pluginJsonData), 0 }; loadFuncs.priv_data = &load_state; viewPlugin->load_state(view->userData, &loadFuncs); } } // TODO: Fi this: assuming one session Session** sessions = Session_getSessions(); assert(sessions); assert(sessions[0]); Session_addViewPlugin(sessions[0], view); return view; } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static DockSysCallbacks s_dockSysCallbacks = { updateWindowSize, setCursorStyle, saveUserData, loadUserData, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PluginUI::State BgfxPluginUI::updateInstance(ViewPluginInstance* instance, PDReader* reader, PDWriter* writer) { PDUI* uiInstance = &instance->ui; PrivateData* data = (PrivateData*)uiInstance->private_data; float x = (float)instance->rect.x; float y = (float)instance->rect.y; float w = (float)instance->rect.width; float h = (float)instance->rect.height; ImGui::SetNextWindowPos(ImVec2(x, y)); ImGui::SetNextWindowSize(ImVec2(w - s_borderSize, h - s_borderSize)); // TODO: Cache this? char title[1024]; if (!data->title) strcpy(title, data->name); else{ sprintf(title, "%s %d - %s###%s%d", instance->plugin->name, instance->count, data->title, instance->plugin->name, instance->count); } ImGui::Begin(title, &data->showWindow, ImVec2(0, 0), true, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); instance->plugin->update(instance->userData, uiInstance, reader, writer); ImGui::End(); // Draw border if (!data->showWindow) return CloseView; return None; } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int BgfxPluginUI::getStatusBarSize() { return m_statusSize; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void renderStatusBar(const char* text, float statusSize) { const ImGuiIO& io = ImGui::GetIO(); ImVec2 size = io.DisplaySize; float yPos = size.y - statusSize; ImGui::SetNextWindowPos(ImVec2(0.0f, yPos)); ImGui::SetNextWindowSize(ImVec2(size.x, statusSize)); bool show = true; ImGui::PushStyleColor(ImGuiCol_WindowBg, ImColor(40, 40, 40)); ImGui::Begin("", &show, ImVec2(0, 0), true, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); ImGui::SetCursorPos(ImVec2(2.0f, 4.0f)); ImGui::Text("Status: %s", text); ImGui::End(); ImGui::PopStyleColor(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BgfxPluginUI::setStatusTextNoFormat(const char* text) { strcpy(m_statusText, text); } /* /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void updateDock(UIDockingGrid* grid) { switch (UIDock_getSizingState(grid)) { case UIDockSizerDir_None: { Cunsor_setType(CursorType_Default); break; } case UIDockSizerDir_Horz: { Cunsor_setType(CursorType_SizeHorizontal); break; } case UIDockSizerDir_Vert: { Cunsor_setType(CursorType_SizeVertical); break; } case UIDockSizerDir_Both: { Cunsor_setType(CursorType_SizeAll); break; } } UIDock_update(grid, InputState_getState()); UIDock_render(grid); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void updateDocking(Session* session) { InputState* state = InputState_getState(); int mx = (int)state->mousePos.x; int my = (int)state->mousePos.y; struct ViewPluginInstance* view = Session_getViewAt(session, mx, my, 0); docksys_set_mouse(view, mx, my, state->mouseDown[0]); } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BgfxPluginUI::preUpdate() { const float deltaTime = 1.0f / 60.f; // TODO: Calc correct dt bgfx::setViewRect(0, 0, 0, (uint16_t)s_context.width, (uint16_t)s_context.height); bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x000f0f0f, 1.0f, 0); bgfx::submit(0); IMGUI_preUpdate(deltaTime); //InputState_update(deltaTime); /* Session** sessions = Session_getSessions(); for (int i = 0; i < array_size(sessions); ++i) { Session* session = sessions[i]; updateDocking(session); } docksys_update(); */ } /* static PosColorVertex* fill_rectBorder(PosColorVertex* verts, IntRect* rect, uint32_t color) { const float x0 = (float)rect->x; const float y0 = (float)rect->y; const float x1 = (float)rect->width + x0; const float y1 = (float)rect->height + y0; // First triangle verts[0].x = x0; verts[0].y = y0; verts[0].color = color; verts[1].x = x1; verts[1].y = y0; verts[1].color = color; verts[2].x = x1; verts[2].y = y1; verts[2].color = color; // Second triangle verts[3].x = x0; verts[3].y = y0; verts[3].color = color; verts[4].x = x1; verts[4].y = y1; verts[4].color = color; verts[5].x = x0; verts[5].y = y1; verts[5].color = color; verts += 6; return verts; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void renderBorders(Session* session) { int count = 0; ViewPluginInstance** views = Session_getViewPlugins(session, &count); bgfx::TransientVertexBuffer tvb; const uint32_t vertexCount = (uint32_t)count * 2 * 6; UIRender_allocPosColorTb(&tvb, vertexCount); PosColorVertex* verts = (PosColorVertex*)tvb.data; // TODO: Use settings for colors const uint32_t colorDefalut = (0x40 << 16) | (0x40 << 8) | 0x40; const uint32_t colorHigh = (0x60 << 16) | (0x60 << 8) | 0x60; for (int i = 0; i < count; ++i) { IntRect t = views[i]->rect; IntRect t0 = {{{ t.x + t.width - s_borderSize, t.y, s_borderSize, t.height }}}; IntRect t1 = {{{ t.x, t.y + t.height - s_borderSize, t.width, s_borderSize }}}; verts = fill_rectBorder(verts, &t0, colorDefalut); verts = fill_rectBorder(verts, &t1, colorDefalut); } bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_MSAA); UIRender_posColor(&tvb, 0, vertexCount); } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BgfxPluginUI::postUpdate() { renderStatusBar(m_statusText, (float)m_statusSize); IMGUI_postUpdate(); /* Session** sessions = Session_getSessions(); for (int i = 0; i < array_size(sessions); ++i) { Session* session = sessions[i]; renderBorders(session); } */ bgfx::frame(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BgfxPluginUI::create(void* windowHandle, int width, int height) { //docksys_set_callbacks(&s_dockSysCallbacks); cursor_init(); #ifdef PRODBG_WIN bgfx::winSetHwnd((HWND)windowHandle); #elif PRODBG_MAC bgfx::osxSetNSWindow(windowHandle); #elif PRODBG_UNIX bgfx::x11SetDisplayWindow(XOpenDisplay(0), (uint32_t)(uintptr_t)windowHandle); #endif bgfx::init(); bgfx::reset((uint32_t)width, (uint32_t)height); bgfx::setViewSeq(0, true); IMGUI_setup(width, height); s_context.width = width; s_context.height = height; //Service_register(&g_serviceMessageFuncs, PDMESSAGEFUNCS_GLOBAL); //Service_register(&g_dialogFuncs, PDDIALOGS_GLOBAL); //Cursor_init(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BgfxPluginUI::destroy() { } // It's a bit weird to have the code like this here. To be cleaned up /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void prodbg_set_mouse_pos(float x, float y) { IMGUI_setMousePos(x, y); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void prodbg_set_mouse_state(int button, int state) { IMGUI_setMouseState(state); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void prodbg_set_scroll(float x, float y) { (void)x; IMGUI_setScroll(y); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void prodbg_key_down(int key, int modifier) { //InputState* state = InputState_getState(); //state->keysDown[key] = true; //state->modifiers = modifier; IMGUI_setKeyDown(key, modifier); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void ProDBG_keyDownMods(int modifier) { //InputState* state = InputState_getState(); //state->modifiers = modifier; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void prodbg_key_up(int key, int modifier) { /* InputState* state = InputState_getState(); state->keysDown[key] = false; state->modifiers = modifier; */ IMGUI_setKeyUp(key, modifier); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void prodbg_add_char(unsigned short c) { IMGUI_addInputCharacter(c); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void prodbg_set_window_size(int width, int height) { Context* context = &s_context; context->width = width; context->height = height; bgfx::reset((uint32_t)width, (uint32_t)height); IMGUI_updateSize(width, height); /* Session** sessions = Session_getSessions(); for (int i = 0; i < array_size(sessions); ++i) { Session* session = sessions[i]; docksys_update_size(width, height - (int)g_pluginUI->getStatusBarSize()); } */ } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_create() { g_pluginUI = new BgfxPluginUI; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_create_window(void* window, int width, int height) { g_pluginUI->create(window, width, height); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_pre_update() { g_pluginUI->preUpdate(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_post_update() { g_pluginUI->postUpdate(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_destroy() { g_pluginUI->destroy(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_imgui_set_window_pos(float x, float y) { ImGui::SetNextWindowPos(ImVec2(x, y)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_imgui_set_window_size(float w, float h) { ImGui::SetNextWindowSize(ImVec2(w - s_borderSize, h - s_borderSize)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void bgfx_test_menu(int show) { if (show) ImGui::OpenPopup("select"); if (ImGui::BeginPopup("select")) { ImGui::Text("Aquarium"); if (ImGui::BeginMenu("Sub-menu")) { ImGui::MenuItem("Click me"); ImGui::EndMenu(); } ImGui::EndPopup(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void* s_temp; extern "C" void bgfx_set_context(void* context) { s_temp = context; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" void* bgfx_get_context() { return s_temp; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" float bgfx_get_screen_width() { return (float)s_context.width; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" float bgfx_get_screen_height() { return (float)s_context.height; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ "content_hash": "489baac401b6c824e7e4ed5b3d896ca3", "timestamp": "", "source": "github", "line_count": 651, "max_line_length": 161, "avg_line_length": 28.781874039938558, "alnum_prop": 0.47558307092917756, "repo_name": "ashemedai/ProDBG", "id": "54cb6b440bcff2063b0c6b0bcdc59f77c9a25e96", "size": "18737", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/native/ui/bgfx/bgfx_plugin_ui.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7606" }, { "name": "C", "bytes": "728048" }, { "name": "C++", "bytes": "1548292" }, { "name": "HTML", "bytes": "16730" }, { "name": "Lua", "bytes": "623457" }, { "name": "Objective-C", "bytes": "4954" }, { "name": "Objective-C++", "bytes": "26672" }, { "name": "Python", "bytes": "12074" }, { "name": "Rust", "bytes": "222917" }, { "name": "Scala", "bytes": "86" }, { "name": "Shell", "bytes": "18624" }, { "name": "SuperCollider", "bytes": "1678" } ], "symlink_target": "" }
extern void mInstallLibrary_C(); extern void mInstallLibrary_ASM(); extern void mInstall_AMD_Math(); extern void mInstall_Library_SSE(); //-------------------------------------- ConsoleFunction( MathInit, void, 1, 10, "(detect|C|FPU|MMX|3DNOW|SSE|...)") { U32 properties = CPU_PROP_C; // C entensions are always used if (argc == 1) { Math::init(0); return; } for (argc--, argv++; argc; argc--, argv++) { if (dStricmp(*argv, "DETECT") == 0) { Math::init(0); return; } if (dStricmp(*argv, "C") == 0) { properties |= CPU_PROP_C; continue; } if (dStricmp(*argv, "FPU") == 0) { properties |= CPU_PROP_FPU; continue; } if (dStricmp(*argv, "MMX") == 0) { properties |= CPU_PROP_MMX; continue; } if (dStricmp(*argv, "3DNOW") == 0) { properties |= CPU_PROP_3DNOW; continue; } if (dStricmp(*argv, "SSE") == 0) { properties |= CPU_PROP_SSE; continue; } Con::printf("Error: MathInit(): ignoring unknown math extension '%s'", *argv); } Math::init(properties); } //------------------------------------------------------------------------------ void Math::init(U32 properties) { if (!properties) // detect what's available properties = Platform::SystemInfo.processor.properties; else // Make sure we're not asking for anything that's not supported properties &= Platform::SystemInfo.processor.properties; Con::printf("Math Init:"); Con::printf(" Installing Standard C extensions"); mInstallLibrary_C(); Con::printf(" Installing Assembly extensions"); mInstallLibrary_ASM(); if (properties & CPU_PROP_FPU) { Con::printf(" Installing FPU extensions"); } if (properties & CPU_PROP_MMX) { Con::printf(" Installing MMX extensions"); if (properties & CPU_PROP_3DNOW) { Con::printf(" Installing 3DNow extensions"); mInstall_AMD_Math(); } } #if !defined(__MWERKS__) || (__MWERKS__ >= 0x2400) if (properties & CPU_PROP_SSE) { Con::printf(" Installing SSE extensions"); mInstall_Library_SSE(); } #endif //mwerks>2.4 Con::printf(" "); } //------------------------------------------------------------------------------ static MRandomLCG sgPlatRandom; F32 Platform::getRandom() { return sgPlatRandom.randF(); } U32 Platform::getMathControlState() { return 0; } void Platform::setMathControlStateKnown() { } void Platform::setMathControlState(U32 state) { }
{ "content_hash": "f6e4aab5b0c44743f589c3e10a1d6ec2", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 84, "avg_line_length": 22.372881355932204, "alnum_prop": 0.531060606060606, "repo_name": "John3/T3D_GMK_BULLET", "id": "300515083ef2c3e9c31824317ddf7301e0f148ab", "size": "4043", "binary": false, "copies": "2", "ref": "refs/heads/development", "path": "Engine/source/platformX86UNIX/x86UNIXMath.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "32222" }, { "name": "Batchfile", "bytes": "12923" }, { "name": "C", "bytes": "11950387" }, { "name": "C#", "bytes": "5902839" }, { "name": "C++", "bytes": "33125127" }, { "name": "CMake", "bytes": "59253" }, { "name": "CSS", "bytes": "30290" }, { "name": "DIGITAL Command Language", "bytes": "9957" }, { "name": "GLSL", "bytes": "373616" }, { "name": "Groff", "bytes": "254284" }, { "name": "HLSL", "bytes": "753010" }, { "name": "HTML", "bytes": "1070573" }, { "name": "Lex", "bytes": "18736" }, { "name": "M4", "bytes": "151411" }, { "name": "Makefile", "bytes": "70241" }, { "name": "Module Management System", "bytes": "14415" }, { "name": "NSIS", "bytes": "1193756" }, { "name": "Objective-C", "bytes": "116279" }, { "name": "Objective-C++", "bytes": "137570" }, { "name": "OpenEdge ABL", "bytes": "4768" }, { "name": "PHP", "bytes": "586772" }, { "name": "Pascal", "bytes": "258402" }, { "name": "SAS", "bytes": "13756" }, { "name": "Shell", "bytes": "181035" }, { "name": "Smalltalk", "bytes": "1353" }, { "name": "Smarty", "bytes": "254142" }, { "name": "Yacc", "bytes": "19012" } ], "symlink_target": "" }
body { background: #333; } #page-wrap:after { content: "Smartphone Layout"; } h2 span, section h3 { display: none; } body { font-size: xx-large; } footer, input { font-size: large; } span.right{ float:right; }
{ "content_hash": "421a3ecfed6481b51ef3c3ed3644e9a6", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 50, "avg_line_length": 24.5, "alnum_prop": 0.5755102040816327, "repo_name": "armero1989/quiz-2016", "id": "1aea46d51baea733c53c4d3d2079e318814c6336", "size": "245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/stylesheets/smartphone.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1136" }, { "name": "HTML", "bytes": "4429" }, { "name": "JavaScript", "bytes": "12947" } ], "symlink_target": "" }
module.exports = Stream; var U = require('./utility.js'); var StreamTransform = require('./StreamTransform.js'); var Display = require('./display/Display.js'); function Stream(data, d3lib) { StreamTransform.call(this, data, d3lib); this.displays = []; } Stream.prototype = Object.create(StreamTransform.prototype); Stream.prototype.constructor = Stream; Stream.prototype.load = function(url, options) { var opt = options || {}; var self = this; (opt.loader || d3loader)(url, opt, this.d3).then(function(data) { self.update(data, opt); }); return this; function d3loader(url, options, d3) { if (options.format == 'csv') { return d3.csv(url, { credentials: 'same-origin' }); } else if (options.format == 'tsv') { return d3.tsv(url, { credentials: 'same-origin' }); } else if (options.format == 'xml') { return d3.xml(url, { credentials: 'same-origin' }); } return d3.json(url, { credentials: 'same-origin' }); } }; Stream.prototype.branch = function() { var b = new Stream(this.unstream()); this.displays.push(b); return b; }; Stream.prototype.display = function(element, options) { var d = new Display(this.d3, element, options, this.unstream()); this.displays.push(d); return d; }; Stream.prototype.update = function(data, options) { var opt = options || {}; if (data !== undefined) { if (opt.append) { this.data = this.data.concat(data); } else if (opt.prepend) { this.data = data.concat(this.data); } else { this.data = data; } } var transformedData = this.unstream(); for (var i = 0; i < this.displays.length; i++) { this.displays[i].update(transformedData); } return this; }; Stream.prototype.contains = function (item) { return this.data.includes(item); }; Stream.prototype.containedIn = function (list) { return list.includes(this.data); }; Stream.prototype.remove = function (item) { U.remove(this.data, item); this.update(); return this; }; Stream.prototype.empty = function (item) { this.data = []; this.update(); return this; }; Stream.prototype.add = function (item) { return this.update(item, { append: true }); }; Stream.prototype.timeInterval = function (name, sub) { if (name == 'hour' || (sub && name == 'day')) { return this.d3.timeHour; } else if (name == 'day' || (sub && name == 'week')) { return this.d3.timeDay; } else if (name == 'week' || (sub && name == 'month')) { return this.d3.timeWeek; } else if (name == 'month' || (sub && name == 'year')) { return this.d3.timeMonth; } else if (name == 'year') { return this.d3.timeYear; } return this.d3.timeDay; }; Stream.prototype.timeFormat = function (name, sub) { if (name == 'hour' || (sub && name == 'day')) { return this.d3.timeFormat('%H'); } else if (name == 'day' || (sub && name == 'week')) { return this.d3.timeFormat('%a'); } else if (name == 'week' || (sub && name == 'month')) { var f = this.d3.timeFormat('%U'); return function (t) { var n = 1 + parseInt(f(t)); return n > 52 ? n - 52 : n; }; } else if (name == 'month' || (sub && name == 'year')) { return this.d3.timeFormat('%m'); } else if (name == 'year') { return this.d3.timeFormat('%Y'); } return this.d3.timeFormat('%d.%m.'); } Stream.prototype.colorScale = function () { return this.d3.scaleOrdinal(this.d3.schemePaired); }
{ "content_hash": "fe4a5c6e50465a3bfc0869d7b4fe6b1e", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 67, "avg_line_length": 27.312, "alnum_prop": 0.6086701816051553, "repo_name": "debyte/desummary", "id": "833e0472ec742805c7d1b902f26ab588f66ed93d", "size": "3421", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Stream.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1259" }, { "name": "HTML", "bytes": "6321" }, { "name": "JavaScript", "bytes": "45774" }, { "name": "Makefile", "bytes": "557" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!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" xml:lang="en" lang="en"> <head> <title>ActiveRecord::TransactionIsolationError</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" /> <script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.0.0</span><br /> <h1> <span class="type">Class</span> ActiveRecord::TransactionIsolationError <span class="parent">&lt; <a href="ActiveRecordError.html">ActiveRecord::ActiveRecordError</a> </span> </h1> <ul class="files"> <li><a href="../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activerecord-4_0_0/lib/active_record/errors_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.0/lib/active_record/errors.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <!-- Methods --> </div> </div> </body> </html>
{ "content_hash": "459cc33404c7efd8ed384a889cc89d48", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 215, "avg_line_length": 24.756410256410255, "alnum_prop": 0.541170378042465, "repo_name": "alombardo4/Agendue", "id": "dfe55fe7adf4668304eaaea32e8a07a280cfb13a", "size": "1931", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AgendueWeb/doc/api/classes/ActiveRecord/TransactionIsolationError.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "138782" }, { "name": "CoffeeScript", "bytes": "3689" }, { "name": "HTML", "bytes": "13251982" }, { "name": "Java", "bytes": "308126" }, { "name": "JavaScript", "bytes": "15185870" }, { "name": "Objective-C", "bytes": "361506" }, { "name": "Perl", "bytes": "1361" }, { "name": "Ruby", "bytes": "150857" } ], "symlink_target": "" }
<div class="row"> <div class="span4"> <div class="panel-transparent inner"> <div class="page-header"> <h4>用户登录</h4> </div> <form class="form-horizontal form-min" name="login"> <div class="control-group"> <label class="control-label">用户名:</label> <div class="controls"> <input class="input-block-level" type="text" placeholder="name or Email or Uid" name="name" ng-model="logname" required/> <span class="text-error help-inline" ng-show="login.name.$error.required"> 请输入用户名、Email或Uid! </span> </div> </div> <div class="control-group"> <label class="control-label">密码:</label> <div class="controls"> <input class="input-block-level" type="password" placeholder="password" name="password" ng-model="logpwd" ng-minlength="6" ng-maxlength="20" required/> <span class="text-error help-inline" ng-show="login.password.$error.required"> 请输入密码! </span> </div> </div> <div class="control-group"> <div class="controls"> <button ng-click="submit()" class="btn btn-primary" ng-disabled="login.name.$error.required || login.password.$error.required">登 录</button> <a ng-show="userReset" ng-href="{{'/reset/'+userReset}}" class="btn btn-warning">{{resetName}}</a> </div> </div> </form> </div> </div> <div class="span8"> </div> </div>
{ "content_hash": "121f60c5d4385e1c73975c6b7bdded45", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 118, "avg_line_length": 46.825, "alnum_prop": 0.45381740523224773, "repo_name": "20012002er/jsgen", "id": "12e5461afc014c88c594d3a3492743fb286c1e8f", "size": "1925", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "static/tpl/login.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/** * <p> * <fullname>Amazon Managed Workflows for Apache Airflow</fullname> * <p> * This section contains the Amazon Managed Workflows for Apache Airflow (MWAA) API reference documentation. For more * information, see <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html">What Is Amazon * MWAA?</a>. * </p> * <p> * <b>Endpoints</b> * </p> * <ul> * <li> * <p> * <code>api.airflow.{region}.amazonaws.com</code> - This endpoint is used for environment management. * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_CreateEnvironment.html">CreateEnvironment</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_DeleteEnvironment.html">DeleteEnvironment</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_GetEnvironment.html">GetEnvironment</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_ListEnvironments.html">ListEnvironments</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_ListTagsForResource.html">ListTagsForResource</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_TagResource.html">TagResource</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_UntagResource.html">UntagResource</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_UpdateEnvironment.html">UpdateEnvironment</a> * </p> * </li> * </ul> * </li> * <li> * <p> * <code>env.airflow.{region}.amazonaws.com</code> - This endpoint is used to operate the Airflow environment. * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_CreateCliToken.html ">CreateCliToken</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_CreateWebLoginToken.html">CreateWebLoginToken</a> * </p> * </li> * </ul> * <br /> * </li> * <li> * <p> * <code>ops.airflow.{region}.amazonaws.com</code> - This endpoint is used to push environment metrics that track * environment health. * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/mwaa/latest/API/API_PublishMetrics.html ">PublishMetrics</a> * </p> * </li> * </ul> * </li> * </ul> * <p> * <b>Regions</b> * </p> * <p> * For a list of regions that Amazon MWAA supports, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html#regions-mwaa">Region availability</a> in * the <i>Amazon MWAA User Guide</i>. * </p> * </p> */ package com.amazonaws.services.mwaa;
{ "content_hash": "715dd662ae931080d932bc79fcd9a3f8", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 117, "avg_line_length": 25.733333333333334, "alnum_prop": 0.6236121391561806, "repo_name": "aws/aws-sdk-java", "id": "a717f677931fccebee20760ed251c9f062d761bf", "size": "3282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-mwaa/src/main/java/com/amazonaws/services/mwaa/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
This file is a complete documentation of the file `beam.json` that is used to configure `beam`. Beam cannot operate without a valid `beam.json` file in the working directory, so creating one is a good place to start if you want to use `beam`. If you are looking for an example configuration to get you started, look in [`README.md`](README.md) or run `beam init` to create a minimal config file in your working directory. ## Brief overview Beam has the following workflow assumptions: * You are using a version control system (Git is the only supported VCS at this time). * You want to sync the head of a branch or a specific commit to a server. * You want to be very sure about what is going to happen when you sync * You may want to exclude files and folders from the deployment * You may have multiple servers with different purposes (ie. testing and live) * You may want to run custom commands at different stages of deployment, locally and on the target server. * You want to do all of this with a command as simple as `beam up live` As well as 'beaming' up, `beam` can also 'beam' down; synchronising your working copy with what's on a server. You can also do a working copy `beam up`, send a specific branch, and do a dry-run to simulate a sync. For a full list of options run `beam up --help`. ### Order of operations To give a clear picture of what a `beam up my-target` does with no command line options, here's a high-level list: 1. Export the head of a branch from your repository to a temporary directory 1. Run commands defined as `phase: pre`, `location: local` in the temporary export location 1. Do a dry-run and display a breakdown of exactly what will happen if you sync 1. Prompt to continue (or exit when no changes to sync) 1. Prompt again if files will be deleted 1. Run commands defined as `phase: pre`, `location: target` in the deployment location on the target server 1. Perform the actual sync 1. Run commands defined as `phase: post`, `location: local` in the temporary export location 1. Run commands defined as `phase: post`, `location: target` in the deployment location on the target server 1. Clean up the temporary export location ## Servers "servers": { "test": { "user": "user", "host": "some.hostname", "webroot": "subdomains/staging" }, "live": { "user": "user", "host": "some.host.name", "webroot": "public_html", "branch": "remotes/origin/master" } } Servers are individual, named deployment targets. When using `beam up` or `beam down`, a server name referencing a server config is required. You can only work with one server per beam command, and at least one server must be defined to use Beam. **The following properties are required for each defined server:** * `user` - User to log into the server with * `host` - Host name or IP address of the server * `webroot` - Path to the deployment directory on the server. Relative paths are relative to the user's home directory. A trailing slash is optional. ### Optional properties * `type` *(string: rsync)* - Transfer method to use with the server. This must be one of `rsync`, `ftp`, and `sftp` (FTP over SSH). * `branch` *(string)* - Branch to lock this server to. When specified, a `beam up` to this server will always send this branch, regardless of the currently checked out branch and the `--ref` and `--working-copy` flags. This is useful for ensuring that only one branch can be deployed to, for example, your production server. Any git branch is valid here, including remote branches like `remotes/origin/master`. ### (S)FTP properties When `type` is set to 'ftp' or 'sftp', a number of FTP specific properties are available: **FTP & SFTP:** * `password` *(string)* - Password to connect with. Beam will prompt for a password where one is not specified in the config. **FTP only:** * `passive` *(boolean: false)* - Run the FTP session in passive mode. * `ssl` *(boolean: false)* - Make the FTP connection over SSL (FTPS) ### Rsync properties * `sshpass` *(boolean: false)* - Use the program [`sshpass`](http://sourceforge.net/projects/sshpass/) to enter your SSH password automatically when using password authentication. With this option enabled, Beam will prompt for an SSH password once instead of an SSH client prompting for each new connection. Key-based authentication is reccommeded, though this may not suit everyone. To use this option you will need to have the `sshpass` program accessible on your path. ## Exclude "exclude" : { "patterns" : [ "/cache/*", "/silverstripe-cache/*", "*.tmp" ] } The `exclude` section allows you to exclude files from all deployments. Pre-defined exclusion patterns for specific applications can also be specified. A built-in list of excludes is always applied, which excludes the 'beam.json' file amongst others (`*~`, `composer.json`, `.git`, `.gitignore`, etc). When using the `rsync` deployment method (default), patterns are passed directly to `rsync`'s `--exclude` option. Rsync has fairly extensive pattern support which will not be covered here, but can be found in the Rsync man page. When using (S)FTP, exclusion patterns are handled internally by beam (crudely relative to rsync) and follow the basic rules of rsync's path matching. Valid values for `applications` are: `gear`, `silverstripe`, `symfony`, `wordpress` and `zf` ## Commands "commands": [ { "command": "composer install --prefer-dist --no-dev", "location": "local", "phase": "pre", "required": true }, { "command": "composer dump-autoload -o", "location": "local", "phase": "pre" }, { "command": "clearcachetask", "location": "target", "phase": "post" } ] Beam allows arbitrary shell commands to be executed at certain points in the deployment process on both the local machine and the target. Commands are executed in order of location, phase, and defined order. Commands are always executed with the working directory set to the temporary git export for `local` commands, and in the defined `webroot` for `target` commands. Command output is suppressed unless beam is run with the verbose (`-v`) flag, a command's `tty` option is true, or if a command exits with a non-zero status. In the case a command fails, beam will prompt to continue unless the failed command is marked as required. Note that running commands on a target requires an SSH connection to the target. The SFTP and FTP deployment methods do not support running commands on the target due to this limitation. **Each command must define:** * `command` - Command to execute. This can be is anything you would normally type on a shell * `phase` - Phase of deployment to execute the command in: `pre` or `post` upload to the target * `location` - What machine to run the command on: `local` or `target` **Additionally, the following can be specified:** * `servers` *(array)* - A list of server configs by name that a command is limited to. When this option is defined, the command will only run on the specified servers. When not defined a command will run when deploying to any server. * `tag` *(string)* - A tag for use with the `--tags (-t)` option. Tagged commands are not run unless their tag is specified when `beam` is run. Multiple commands can have the same tag. * `required` *(boolean: false)* - Specifies that a command is required for the deployment to complete successfully. Required commands do not prompt when `--command-prompt` is used, are run regardless of tags, and beam will abort if a required command fails. * `tty` *(boolean: false)* - Whether the command should be run in a terminal (TTY) environment. Any command that requires user input/interaction will need this option enabled to work correctly. When set to true, the i/o streams (stdin, stderr, stdout) of the command process are connected to the current terminal instead of being managed internally by `beam`. ## Import "import": [ "~/configs/another-beam-config.json", "http://example.com/silverstripe-config.json" ] The `import` config option is an array of filenames that provides a way to merge multiple beam.json files together. Using imports, common settings can be used across multiple projects without duplication and managing shared options becomes easier. The values in `import` can be anything accepted by PHP's `file_get_contents`, including but not limited to HTTP URLs and local file paths. A tilde at the start of a path is replaced with the path to the current user's home directory. Imports are fetched recursively (ie. imported configs can import further configs) with each unique path being fetched only the first time it appears.
{ "content_hash": "a1ff73771eb7e470bb755e8638089d0b", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 472, "avg_line_length": 59.390728476821195, "alnum_prop": 0.7149866190900981, "repo_name": "unclecheese/beam", "id": "4602809f2778800bb8828084801085fbd703bb2c", "size": "8990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONFIG.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
module ActsAsReviewable # The named scopes are: # in_order: Returns reviews in the order they were created (created_at ASC). # recent: Returns reviews by how recently they were created (created_at DESC). module Review def self.included(review_model) review_model.extend Finders review_model.scope :in_order, -> { review_model.order('created_at ASC') } review_model.scope :recent, -> { review_model.order('created_at DESC') } end module Finders # All reviews assigned to a given user. def find_reviews_by_user(user_id) where(["reviewer_id = ?", user_id]).order("created_at DESC") end # All reviews assigned to a given drama. def find_reviews_for_drama(drama_id) where(["drama_id = ?", drama_id]).order("created_at DESC") end #Reviews with a rating def with_rating where('rating is not null') end end end end
{ "content_hash": "a6163d1201712127438fd6e294fd2ac8", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 80, "avg_line_length": 28.393939393939394, "alnum_prop": 0.6392742796157951, "repo_name": "ac-adekunle/ds", "id": "ea0f818e8c4a2c6ab1ac8995cf3a62570bb4a40c", "size": "937", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/acts_as_reviewable.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3155" }, { "name": "CoffeeScript", "bytes": "939" }, { "name": "HTML", "bytes": "17416" }, { "name": "JavaScript", "bytes": "47065" }, { "name": "Ruby", "bytes": "70759" } ], "symlink_target": "" }
package org.vrsl.jet.modeller.erd.editor.schema.view; import java.awt.Color; import java.awt.Font; import java.awt.font.TextAttribute; import java.util.Map; abstract public class SchemaText extends SchemaRectangleElement { private String text = null; private String fontName = null; private int fontSize = 0; private int fontType = 0; private Color theTextColor = null; protected Font boldFont; public void setText(String text) { this.text = text; } public String getText() { return text; } @SuppressWarnings({"unchecked", "rawtypes"}) public void setFont(String fName, int sz, int type) { fontName = fName; fontSize = sz; fontType = type; boldFont = new Font(fontName, fontType & 255, fontSize); if ((fontType & 256) != 0) { Map attributes = boldFont.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); boldFont = new Font(attributes); } } public String getFontName() { return fontName; } public int getFontSize() { return fontSize; } public int getFontType() { return fontType; } public void setColor(Color cl) { theTextColor = cl; } public Color getColor() { return theTextColor; } }
{ "content_hash": "3c3a5fe151e1bd83591368916e7f1723", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 80, "avg_line_length": 24.35593220338983, "alnum_prop": 0.5901183020180932, "repo_name": "vrsl/MDD-JPA", "id": "29bc764b84877b6ca11807b79e2ad8dd2c62c24c", "size": "2599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ErdModeller/src/org/vrsl/jet/modeller/erd/editor/schema/view/SchemaText.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "585273" } ], "symlink_target": "" }
/** * * Utilities and implementations of functional logic. * */ package com.ibm.streamsx.topology.logic;
{ "content_hash": "eb58ab38efac5e349d04cf491be889b2", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 53, "avg_line_length": 14, "alnum_prop": 0.6964285714285714, "repo_name": "dlaboss/streamsx.topology", "id": "2ad0f52f6556a8d3c659065dd6ce3df1aa06b87e", "size": "186", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "java/src/com/ibm/streamsx/topology/logic/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "11042" }, { "name": "Java", "bytes": "1049955" }, { "name": "Scala", "bytes": "11124" } ], "symlink_target": "" }
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/coordinator" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#dcdcdc"> <android.support.design.widget.AppBarLayout android:id="@+id/appBarLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways|snap" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:titleTextColor="#fff"> <EditText android:id="@+id/toolbar_edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="56dp" android:background="@android:color/transparent" android:enabled="false" android:hint="@string/toolbar_hint" android:inputType="text" android:maxLines="1" android:scrollHorizontally="true" android:textSize="13sp" /> <ImageButton android:id="@+id/toolbar_go" android:layout_width="?attr/actionBarSize" android:layout_height="?attr/actionBarSize" android:layout_gravity="end|center" android:background="?selectableItemBackgroundBorderless" android:contentDescription="@string/toolbar_cd_start_request" android:src="@drawable/ic_play" /> </android.support.v7.widget.Toolbar> </android.support.design.widget.AppBarLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="gone" /> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> </android.support.design.widget.CoordinatorLayout>
{ "content_hash": "e03555ee04a73ae0c484f623861585f3", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 107, "avg_line_length": 42.07462686567164, "alnum_prop": 0.621496984746364, "repo_name": "jaksab/EasyNetwork", "id": "7b6b3a518ba5f3363f0f6cbf0c147ade4367d835", "size": "2819", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_demo.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "151395" } ], "symlink_target": "" }
const { Class } = require('sdk/core/heritage'); const { EventTarget } = require("sdk/event/target"); const { emit } = require("sdk/event/core"); const { SSDP } = require("./ssdp"); //const { Device } = require("./device"); /** * A class that (asynchronously) scans for available devices and sends corresponding notifications * to its listener(s). This class is implicitly a singleton; since it does a network scan, it isn't * useful to have more than one instance of it in use. * * @ingroup Discovery */ const EVENT_DEVICE_DID_COME_ONLINE = 'deviceDidComeOnline'; const EVENT_DEVICE_DID_GO_OFFLINE = 'deviceDidGoOffline'; const DeviceScanner = Class({ extends: EventTarget, searchTarget: "urn:dial-multiscreen-org:service:dial:1", _devicesMap: new Map(), /** * Designated initializer. Constructs a new GCKDeviceScanner. */ initialize: function initialize(device_finding_callback) { let self = this; self.ssdpClient = SSDP(device_finding_callback); self.ssdpClient.on(SSDP.EVENT_SERVICE_FOUND, function (location) { let service = self.ssdpClient.findServiceForLocation(location); }); self.ssdpClient.on(SSDP.EVENT_SERVICE_LOST, function (location) { let service = self.ssdpClient.findServiceForLocation(location); let device = self._devicesMap.get(service.uuid); if (device) { emit(self, EVENT_DEVICE_DID_GO_OFFLINE, device); } }); self.ssdpClient.registerTarget(this.searchTarget, function (aService, aApp) { return undefined; // ignore }); }, /** * Starts a new device scan. The scan must eventually be stopped by calling * @link #stopScan @endlink. */ startScan: function startScan() { //let services = this.ssdpClient.services; //console.info("services::::::::::", services); this.ssdpClient.search(); }, /** * Stops any in-progress device scan. This method <b>must</b> be called at some point after * @link #startScan @endlink was called and before this object is released by its owner. */ stopScan: function stopScan() { this.ssdpClient.stopSearch(); } }); DeviceScanner.EVENT_DEVICE_DID_COME_ONLINE = EVENT_DEVICE_DID_COME_ONLINE; DeviceScanner.EVENT_DEVICE_DID_GO_OFFLINE = EVENT_DEVICE_DID_GO_OFFLINE; exports.DeviceScanner = DeviceScanner;
{ "content_hash": "4e5f20663a93a42bd6801583c3191c52", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 99, "avg_line_length": 32.521126760563384, "alnum_prop": 0.6929406669553919, "repo_name": "openflint/matchstick-settings-firefox", "id": "915c4fcf8cc18b76333b7b51d75e222f7fa978f3", "size": "2913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/utils/device_scanner.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5975" }, { "name": "JavaScript", "bytes": "48328" }, { "name": "Python", "bytes": "5494" } ], "symlink_target": "" }
html, body { height: 100%; width: 100%; } body { font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif; } hr { border-color: #009688; border-width: 3px; max-width: 300px; } .bg-primary hr { border-color: #FFFFFF; border-width: 3px; max-width: 300px; } header hr { border-color: #FFFFFF; border-width: 3px; max-width: 300px; } hr.light { border-color: white; } a { -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; color: white; } a:hover, a:focus { color: #eb3812; } h1, h2, h3, h4, h5, h6 { font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif; } p { font-size: 16px; line-height: 1.5; margin-bottom: 20px; } .bg-primary { background-color: #009688; } .bg-dark { background-color: #222222; color: white; } .text-faded { color: rgba(255, 255, 255, 0.7); } section { padding: 100px 0; } aside { padding: 50px 0; } .no-padding { padding: 0; } .navbar-default { background-color: white; border-color: rgba(34, 34, 34, 0.05); font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .navbar-default .navbar-header .navbar-brand { color: #009688; font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif; font-weight: 700; text-transform: uppercase; } .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus { color: #eb3812; } .navbar-default .navbar-header .navbar-toggle { font-weight: 700; font-size: 12px; color: #222222; text-transform: uppercase; } .navbar-default .nav > li > a, .navbar-default .nav > li > a:focus { text-transform: uppercase; font-weight: 700; font-size: 13px; color: #222222; } .navbar-default .nav > li > a:hover, .navbar-default .nav > li > a:focus:hover { color: #009688; } .navbar-default .nav > li.active > a, .navbar-default .nav > li.active > a:focus { color: #009688 !important; background-color: transparent; } .navbar-default .nav > li.active > a:hover, .navbar-default .nav > li.active > a:focus:hover { background-color: transparent; } @media (min-width: 768px) { .navbar-default { background-color: transparent; border-color: rgba(255, 255, 255, 0.3); } .navbar-default .navbar-header .navbar-brand { color: rgba(255, 255, 255, 0.7); } .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus { color: white; } .navbar-default .nav > li > a, .navbar-default .nav > li > a:focus { color: rgba(255, 255, 255, 0.7); } .navbar-default .nav > li > a:hover, .navbar-default .nav > li > a:focus:hover { color: white; } .navbar-default.affix { background-color: white; border-color: rgba(34, 34, 34, 0.05); } .navbar-default.affix .navbar-header .navbar-brand { color: #009688; font-size: 14px; } .navbar-default.affix .navbar-header .navbar-brand:hover, .navbar-default.affix .navbar-header .navbar-brand:focus { color: #eb3812; } .navbar-default.affix .nav > li > a, .navbar-default.affix .nav > li > a:focus { color: #222222; } .navbar-default.affix .nav > li > a:hover, .navbar-default.affix .nav > li > a:focus:hover { color: #009688; } } header { position: relative; width: 100%; min-height: auto; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; background-position: center; background-image: url('../img/header2.png'); text-align: center; color: white; } header .header-content { position: relative; text-align: center; padding: 100px 15px 100px; width: 100%; } header .header-content .header-content-inner h1 { font-weight: 700; text-transform: uppercase; margin-top: 0; margin-bottom: 0; font-size: 30px; } header .header-content .header-content-inner hr { margin: 30px auto; } header .header-content .header-content-inner p { font-weight: 300; color: rgba(255, 255, 255, 0.7); font-size: 16px; margin-bottom: 50px; } @media (min-width: 768px) { header { min-height: 100%; } header .header-content { position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); padding: 0 50px; } header .header-content .header-content-inner { max-width: 1000px; margin-left: auto; margin-right: auto; } header .header-content .header-content-inner h1 { font-size: 50px; } header .header-content .header-content-inner p { font-size: 18px; max-width: 80%; margin-left: auto; margin-right: auto; } } .section-heading { margin-top: 0; } .service-box { max-width: 400px; margin: 50px auto 0; } @media (min-width: 992px) { .service-box { margin: 20px auto 0; } } .service-box p { margin-bottom: 0; } .portfolio-box { position: relative; display: block; max-width: 650px; margin: 0 auto; } .portfolio-box .portfolio-box-caption { color: white; opacity: 0; display: block; background: rgba(0, 150, 136, 0.9); position: absolute; bottom: 0; text-align: center; width: 100%; height: 100%; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content { width: 100%; text-align: center; position: absolute; top: 50%; transform: translateY(-50%); } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category, .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif; padding: 0 15px; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category { text-transform: uppercase; font-weight: 600; font-size: 14px; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-size: 18px; } .portfolio-box:hover .portfolio-box-caption { opacity: 1; } .portfolio-box:focus { outline: none; } @media (min-width: 768px) { .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category { font-size: 16px; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-size: 22px; } } .call-to-action h2 { margin: 0 auto 20px; } .text-primary { color: #009688; } .no-gutter > [class*='col-'] { padding-right: 0; padding-left: 0; } .btn-default { color: #222222; background-color: white; border-color: white; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .btn-default:hover, .btn-default:focus, .btn-default.focus, .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { color: #222222; background-color: #f2f2f2; border-color: #ededed; } .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { background-image: none; } .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, .btn-default.disabled:hover, .btn-default[disabled]:hover, fieldset[disabled] .btn-default:hover, .btn-default.disabled:focus, .btn-default[disabled]:focus, fieldset[disabled] .btn-default:focus, .btn-default.disabled.focus, .btn-default[disabled].focus, fieldset[disabled] .btn-default.focus, .btn-default.disabled:active, .btn-default[disabled]:active, fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { background-color: white; border-color: white; } .btn-default .badge { color: white; background-color: #222222; } .btn-primary { color: white; background-color: #009688; border-color: #009688; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { color: white; background-color: #ee4b28; border-color: #ed431f; } .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { background-image: none; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled.focus, .btn-primary[disabled].focus, fieldset[disabled] .btn-primary.focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { background-color: #009688; border-color: #009688; } .btn-primary .badge { color: white; background-color: white; } .btn { font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif; border: none; border-radius: 300px; font-weight: 700; text-transform: uppercase; } .btn-xl { padding: 15px 30px; } ::-moz-selection { color: white; text-shadow: none; background: #222222; } ::selection { color: white; text-shadow: none; background: #222222; } img::selection { color: white; background: transparent; } img::-moz-selection { color: white; background: transparent; } body { webkit-tap-highlight-color: #222222; } h1, .navbar-brand { text-transform: initial !important; } .text-normal { color: black; } .bg-primary .tex-normal { color: white; } .container h2 { color: black; } .container h3 { color: black; } .container p { color: black; } .container a { color: black; } .container li { color: black; } .h1, .h2, .h3, .h4, body, h1, h2, h3, h4, h5, h6 { font-family: Roboto, Helvetica, Arial, sans-serif; font-weight: 300 } h5, h6 { font-weight: 400 } body .container .jumbotron p, body .container .well p, body .container-fluid .jumbotron p, body .container-fluid .well p { font-weight: 300 } .btn, .input-group-btn .btn { border: none; border-radius: 2px; position: relative; padding: 8px 30px; margin: 10px 1px; font-size: 14px; font-weight: 500; text-transform: uppercase; letter-spacing: 0; will-change: box-shadow, transform; -webkit-transition: -webkit-box-shadow .2s cubic-bezier(.4, 0, 1, 1), background-color .2s cubic-bezier(.4, 0, .2, 1), color .2s cubic-bezier(.4, 0, .2, 1); -o-transition: box-shadow .2s cubic-bezier(.4, 0, 1, 1), background-color .2s cubic-bezier(.4, 0, .2, 1), color .2s cubic-bezier(.4, 0, .2, 1); transition: box-shadow .2s cubic-bezier(.4, 0, 1, 1), background-color .2s cubic-bezier(.4, 0, .2, 1), color .2s cubic-bezier(.4, 0, .2, 1); outline: 0; cursor: pointer; text-decoration: none; background: 0 0 } .btn-group-lg .btn, .btn-group-lg .input-group-btn .btn, .btn.btn-lg, .input-group-btn .btn.btn-lg { font-size: 16px } .btn-group-sm .btn, .btn-group-sm .input-group-btn .btn, .btn.btn-sm, .input-group-btn .btn.btn-sm { padding: 5px 20px; font-size: 12px } .btn-group-xs .btn, .btn-group-xs .input-group-btn .btn, .btn.btn-xs, .input-group-btn .btn.btn-xs { padding: 4px 15px; font-size: 10px } .navbar .navbar-form .form-control, .navbar .navbar-form .form-group .form-control { border-color: inherit; color: inherit; padding: 0; margin: 0; height: 28px; font-size: 14px; line-height: 1.42857143 } .panel { border: 2pt solid black; } .panel-heading { background-color: #009F89 !important; color: white; } .btn.btn-primary.page-scroll:hover, .btn.btn-primary.page-scroll:focus { background-color: white !important; color: #009688 !important; }
{ "content_hash": "4e009d08bcdbd00628dfdce0f67586de", "timestamp": "", "source": "github", "line_count": 534, "max_line_length": 160, "avg_line_length": 22.06179775280899, "alnum_prop": 0.6743909685086156, "repo_name": "TechEducationPlusPlus/TechEducationPlusPlus.github.io", "id": "51aeecb84e2925b5ca0e37c9369f137a504bcb16", "size": "11781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "css/creative.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22216" }, { "name": "HTML", "bytes": "13437" }, { "name": "JavaScript", "bytes": "4918" } ], "symlink_target": "" }
from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils.translation import gettext_lazy as _ from .models import NewsItem from danceschool.core.constants import getConstant class LatestNewsFeed(Feed): def title(self): return _("%s Latest News" % getConstant('contact__businessName')) def description(self): return _("Updates and news items from %s" % getConstant('contact__businessName')) def link(self): return reverse('news_feed') def items(self): return NewsItem.objects.order_by('-publicationDate')[:10] def item_title(self, item): return item.title def item_pubDate(self, item): return item.publicationDate def item_description(self, item): return item.content # item_link is only needed if NewsItem has no get_absolute_url method. def item_link(self, item): return reverse('news_feed')
{ "content_hash": "362e144f4e32392646a3acd42ae6d501", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 89, "avg_line_length": 27.085714285714285, "alnum_prop": 0.6888185654008439, "repo_name": "django-danceschool/django-danceschool", "id": "957345873bf39ffa3837abb0edfa721ac0c1d0b3", "size": "948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "danceschool/news/feeds.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "55309" }, { "name": "HTML", "bytes": "334988" }, { "name": "JavaScript", "bytes": "2008559" }, { "name": "Less", "bytes": "21246" }, { "name": "Python", "bytes": "1856445" }, { "name": "SCSS", "bytes": "9564" } ], "symlink_target": "" }
package main import ( "context" "flag" "os" "os/signal" "syscall" "time" "go-common/app/service/main/coin/conf" "go-common/app/service/main/coin/server/gorpc" grpc "go-common/app/service/main/coin/server/grpc" "go-common/app/service/main/coin/server/http" "go-common/app/service/main/coin/service" ecode "go-common/library/ecode/tip" "go-common/library/log" "go-common/library/net/trace" "go-common/library/queue/databus/report" ) func main() { flag.Parse() if err := conf.Init(); err != nil { log.Error("conf.Init() error(%v)", err) panic(err) } log.Init(conf.Conf.Log) defer log.Close() trace.Init(conf.Conf.Tracer) defer trace.Close() ecode.Init(nil) log.Info("coin-service start") report.InitUser(conf.Conf.UserReport) // service init svr := service.New(conf.Conf) rpcSvr := rpc.New(conf.Conf, svr) grpcSvr := grpc.New(conf.Conf.GRPC, svr) http.Init(conf.Conf, svr) // init signal c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) for { s := <-c log.Info("coin-service get a signal %s", s.String()) switch s { case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT: grpcSvr.Shutdown(context.TODO()) rpcSvr.Close() svr.Close() time.Sleep(time.Second * 1) log.Info("coin-service exit") return case syscall.SIGHUP: // TODO reload default: return } } }
{ "content_hash": "432fabfafd952b9b9ad579ba12e572c6", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 83, "avg_line_length": 23.216666666666665, "alnum_prop": 0.6862885857860732, "repo_name": "LQJJ/demo", "id": "a0fed880bf9dc14bee7b7deefc6938dcc125beef", "size": "1393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "126-go-common-master/app/service/main/coin/cmd/main.go", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5910716" }, { "name": "C++", "bytes": "113072" }, { "name": "CSS", "bytes": "10791" }, { "name": "Dockerfile", "bytes": "934" }, { "name": "Go", "bytes": "40121403" }, { "name": "Groovy", "bytes": "347" }, { "name": "HTML", "bytes": "359263" }, { "name": "JavaScript", "bytes": "545384" }, { "name": "Makefile", "bytes": "6671" }, { "name": "Mathematica", "bytes": "14565" }, { "name": "Objective-C", "bytes": "14900720" }, { "name": "Objective-C++", "bytes": "20070" }, { "name": "PureBasic", "bytes": "4152" }, { "name": "Python", "bytes": "4490569" }, { "name": "Ruby", "bytes": "44850" }, { "name": "Shell", "bytes": "33251" }, { "name": "Swift", "bytes": "463286" }, { "name": "TSQL", "bytes": "108861" } ], "symlink_target": "" }
#import "RCTScrollView.h" #import <UIKit/UIKit.h> #import "RCTConvert.h" #import "RCTEventDispatcher.h" #import "RCTLog.h" #import "RCTUIManager.h" #import "RCTUtils.h" #import "UIView+Private.h" #import "UIView+React.h" #if !TARGET_OS_TV #import "RCTRefreshControl.h" #endif @interface RCTScrollEvent : NSObject <RCTEvent> - (instancetype)initWithEventName:(NSString *)eventName reactTag:(NSNumber *)reactTag scrollView:(UIScrollView *)scrollView userData:(NSDictionary *)userData coalescingKey:(uint16_t)coalescingKey NS_DESIGNATED_INITIALIZER; @end @implementation RCTScrollEvent { UIScrollView *_scrollView; NSDictionary *_userData; uint16_t _coalescingKey; } @synthesize viewTag = _viewTag; @synthesize eventName = _eventName; - (instancetype)initWithEventName:(NSString *)eventName reactTag:(NSNumber *)reactTag scrollView:(UIScrollView *)scrollView userData:(NSDictionary *)userData coalescingKey:(uint16_t)coalescingKey { RCTAssertParam(reactTag); if ((self = [super init])) { _eventName = [eventName copy]; _viewTag = reactTag; _scrollView = scrollView; _userData = userData; _coalescingKey = coalescingKey; } return self; } RCT_NOT_IMPLEMENTED(- (instancetype)init) - (uint16_t)coalescingKey { return _coalescingKey; } - (NSDictionary *)body { NSDictionary *body = @{ @"contentOffset": @{ @"x": @(_scrollView.contentOffset.x), @"y": @(_scrollView.contentOffset.y) }, @"contentInset": @{ @"top": @(_scrollView.contentInset.top), @"left": @(_scrollView.contentInset.left), @"bottom": @(_scrollView.contentInset.bottom), @"right": @(_scrollView.contentInset.right) }, @"contentSize": @{ @"width": @(_scrollView.contentSize.width), @"height": @(_scrollView.contentSize.height) }, @"layoutMeasurement": @{ @"width": @(_scrollView.frame.size.width), @"height": @(_scrollView.frame.size.height) }, @"zoomScale": @(_scrollView.zoomScale ?: 1), }; if (_userData) { NSMutableDictionary *mutableBody = [body mutableCopy]; [mutableBody addEntriesFromDictionary:_userData]; body = mutableBody; } return body; } - (BOOL)canCoalesce { return YES; } - (RCTScrollEvent *)coalesceWithEvent:(RCTScrollEvent *)newEvent { NSArray<NSDictionary *> *updatedChildFrames = [_userData[@"updatedChildFrames"] arrayByAddingObjectsFromArray:newEvent->_userData[@"updatedChildFrames"]]; if (updatedChildFrames) { NSMutableDictionary *userData = [newEvent->_userData mutableCopy]; userData[@"updatedChildFrames"] = updatedChildFrames; newEvent->_userData = userData; } return newEvent; } + (NSString *)moduleDotMethod { return @"RCTEventEmitter.receiveEvent"; } - (NSArray *)arguments { return @[self.viewTag, RCTNormalizeInputEventName(self.eventName), [self body]]; } @end /** * Include a custom scroll view subclass because we want to limit certain * default UIKit behaviors such as textFields automatically scrolling * scroll views that contain them. */ @interface RCTCustomScrollView : UIScrollView<UIGestureRecognizerDelegate> @property (nonatomic, assign) BOOL centerContent; #if !TARGET_OS_TV @property (nonatomic, strong) RCTRefreshControl *rctRefreshControl; #endif @end @implementation RCTCustomScrollView - (instancetype)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { [self.panGestureRecognizer addTarget:self action:@selector(handleCustomPan:)]; if ([self respondsToSelector:@selector(setSemanticContentAttribute:)]) { // We intentionaly force `UIScrollView`s `semanticContentAttribute` to `LTR` here // because this attribute affects a position of vertical scrollbar; we don't want this // scrollbar flip because we also flip it with whole `UIScrollView` flip. self.semanticContentAttribute = UISemanticContentAttributeForceLeftToRight; } } return self; } - (UIView *)contentView { return ((RCTScrollView *)self.superview).contentView; } /** * @return Whether or not the scroll view interaction should be blocked because * JS was found to be the responder. */ - (BOOL)_shouldDisableScrollInteraction { // Since this may be called on every pan, we need to make sure to only climb // the hierarchy on rare occasions. UIView *JSResponder = [RCTUIManager JSResponder]; if (JSResponder && JSResponder != self.superview) { BOOL superviewHasResponder = [self isDescendantOfView:JSResponder]; return superviewHasResponder; } return NO; } - (void)handleCustomPan:(__unused UIPanGestureRecognizer *)sender { if ([self _shouldDisableScrollInteraction] && ![[RCTUIManager JSResponder] isKindOfClass:[RCTScrollView class]]) { self.panGestureRecognizer.enabled = NO; self.panGestureRecognizer.enabled = YES; // TODO: If mid bounce, animate the scroll view to a non-bounced position // while disabling (but only if `stopScrollInteractionIfJSHasResponder` was // called *during* a `pan`). Currently, it will just snap into place which // is not so bad either. // Another approach: // self.scrollEnabled = NO; // self.scrollEnabled = YES; } } - (void)scrollRectToVisible:(__unused CGRect)rect animated:(__unused BOOL)animated { // noop } /** * Returning `YES` cancels touches for the "inner" `view` and causes a scroll. * Returning `NO` causes touches to be directed to that inner view and prevents * the scroll view from scrolling. * * `YES` -> Allows scrolling. * `NO` -> Doesn't allow scrolling. * * By default this returns NO for all views that are UIControls and YES for * everything else. What that does is allows scroll views to scroll even when a * touch started inside of a `UIControl` (`UIButton` etc). For React scroll * views, we want the default to be the same behavior as `UIControl`s so we * return `YES` by default. But there's one case where we want to block the * scrolling no matter what: When JS believes it has its own responder lock on * a view that is *above* the scroll view in the hierarchy. So we abuse this * `touchesShouldCancelInContentView` API in order to stop the scroll view from * scrolling in this case. * * We are not aware of *any* other solution to the problem because alternative * approaches require that we disable the scrollview *before* touches begin or * move. This approach (`touchesShouldCancelInContentView`) works even if the * JS responder is set after touches start/move because * `touchesShouldCancelInContentView` is called as soon as the scroll view has * been touched and dragged *just* far enough to decide to begin the "drag" * movement of the scroll interaction. Returning `NO`, will cause the drag * operation to fail. * * `touchesShouldCancelInContentView` will stop the *initialization* of a * scroll pan gesture and most of the time this is sufficient. On rare * occasion, the scroll gesture would have already initialized right before JS * notifies native of the JS responder being set. In order to recover from that * timing issue we have a fallback that kills any ongoing pan gesture that * occurs when native is notified of a JS responder. * * Note: Explicitly returning `YES`, instead of relying on the default fixes * (at least) one bug where if you have a UIControl inside a UIScrollView and * tap on the UIControl and then start dragging (to scroll), it won't scroll. * Chat with andras for more details. * * In order to have this called, you must have delaysContentTouches set to NO * (which is the not the `UIKit` default). */ - (BOOL)touchesShouldCancelInContentView:(__unused UIView *)view { //TODO: shouldn't this call super if _shouldDisableScrollInteraction returns NO? return ![self _shouldDisableScrollInteraction]; } /* * Automatically centers the content such that if the content is smaller than the * ScrollView, we force it to be centered, but when you zoom or the content otherwise * becomes larger than the ScrollView, there is no padding around the content but it * can still fill the whole view. */ - (void)setContentOffset:(CGPoint)contentOffset { UIView *contentView = [self contentView]; if (contentView && _centerContent) { CGSize subviewSize = contentView.frame.size; CGSize scrollViewSize = self.bounds.size; if (subviewSize.width <= scrollViewSize.width) { contentOffset.x = -(scrollViewSize.width - subviewSize.width) / 2.0; } if (subviewSize.height <= scrollViewSize.height) { contentOffset.y = -(scrollViewSize.height - subviewSize.height) / 2.0; } } super.contentOffset = contentOffset; } static inline BOOL isRectInvalid(CGRect rect) { return isnan(rect.origin.x) || isinf(rect.origin.x) || isnan(rect.origin.y) || isinf(rect.origin.y) || isnan(rect.size.width) || isinf(rect.size.width) || isnan(rect.size.height) || isinf(rect.size.height); } - (void)setBounds:(CGRect)bounds { if (isRectInvalid(bounds)) { RCTLogError(@"Attempted to set an invalid bounds to inner scrollview: %@", NSStringFromCGRect(bounds)); return; } [super setBounds:bounds]; } - (void)setFrame:(CGRect)frame { if (isRectInvalid(frame)) { RCTLogError(@"Attempted to set an invalid frame to inner scrollview: %@", NSStringFromCGRect(frame)); return; } [super setFrame:frame]; } #if !TARGET_OS_TV - (void)setRctRefreshControl:(RCTRefreshControl *)refreshControl { if (_rctRefreshControl) { [_rctRefreshControl removeFromSuperview]; } _rctRefreshControl = refreshControl; [self addSubview:_rctRefreshControl]; } #endif //TARGET_OS_TV @end @implementation RCTScrollView { RCTEventDispatcher *_eventDispatcher; RCTCustomScrollView *_scrollView; UIView *_contentView; NSTimeInterval _lastScrollDispatchTime; NSMutableArray<NSValue *> *_cachedChildFrames; BOOL _allowNextScrollNoMatterWhat; CGRect _lastClippedToRect; uint16_t _coalescingKey; NSString *_lastEmittedEventName; NSHashTable *_scrollListeners; } - (instancetype)initWithEventDispatcher:(RCTEventDispatcher *)eventDispatcher { RCTAssertParam(eventDispatcher); if ((self = [super initWithFrame:CGRectZero])) { _eventDispatcher = eventDispatcher; _scrollView = [[RCTCustomScrollView alloc] initWithFrame:CGRectZero]; _scrollView.delegate = self; _scrollView.delaysContentTouches = NO; _automaticallyAdjustContentInsets = YES; _DEPRECATED_sendUpdatedChildFrames = NO; _contentInset = UIEdgeInsetsZero; _contentSize = CGSizeZero; _lastClippedToRect = CGRectNull; _scrollEventThrottle = 0.0; _lastScrollDispatchTime = 0; _cachedChildFrames = [NSMutableArray new]; _scrollListeners = [NSHashTable weakObjectsHashTable]; [self addSubview:_scrollView]; } return self; } RCT_NOT_IMPLEMENTED(- (instancetype)initWithFrame:(CGRect)frame) RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder) static inline void RCTApplyTranformationAccordingLayoutDirection(UIView *view, UIUserInterfaceLayoutDirection layoutDirection) { view.transform = layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight ? CGAffineTransformIdentity : CGAffineTransformMakeScale(-1, 1); } - (void)setReactLayoutDirection:(UIUserInterfaceLayoutDirection)layoutDirection { [super setReactLayoutDirection:layoutDirection]; RCTApplyTranformationAccordingLayoutDirection(_scrollView, layoutDirection); RCTApplyTranformationAccordingLayoutDirection(_contentView, layoutDirection); } - (void)setRemoveClippedSubviews:(__unused BOOL)removeClippedSubviews { // Does nothing } - (void)insertReactSubview:(UIView *)view atIndex:(NSInteger)atIndex { [super insertReactSubview:view atIndex:atIndex]; #if !TARGET_OS_TV if ([view isKindOfClass:[RCTRefreshControl class]]) { [_scrollView setRctRefreshControl:(RCTRefreshControl *)view]; } else #endif { RCTAssert(_contentView == nil, @"RCTScrollView may only contain a single subview"); _contentView = view; RCTApplyTranformationAccordingLayoutDirection(_contentView, self.reactLayoutDirection); [_scrollView addSubview:view]; } } - (void)removeReactSubview:(UIView *)subview { [super removeReactSubview:subview]; #if !TARGET_OS_TV if ([subview isKindOfClass:[RCTRefreshControl class]]) { [_scrollView setRctRefreshControl:nil]; } else #endif { RCTAssert(_contentView == subview, @"Attempted to remove non-existent subview"); _contentView = nil; } } - (void)didUpdateReactSubviews { // Do nothing, as subviews are managed by `insertReactSubview:atIndex:` } - (BOOL)centerContent { return _scrollView.centerContent; } - (void)setCenterContent:(BOOL)centerContent { _scrollView.centerContent = centerContent; } - (void)setClipsToBounds:(BOOL)clipsToBounds { super.clipsToBounds = clipsToBounds; _scrollView.clipsToBounds = clipsToBounds; } - (void)dealloc { _scrollView.delegate = nil; } - (void)layoutSubviews { [super layoutSubviews]; RCTAssert(self.subviews.count == 1, @"we should only have exactly one subview"); RCTAssert([self.subviews lastObject] == _scrollView, @"our only subview should be a scrollview"); CGPoint originalOffset = _scrollView.contentOffset; _scrollView.frame = self.bounds; _scrollView.contentOffset = originalOffset; #if !TARGET_OS_TV // Adjust the refresh control frame if the scrollview layout changes. RCTRefreshControl *refreshControl = _scrollView.rctRefreshControl; if (refreshControl && refreshControl.refreshing) { refreshControl.frame = (CGRect){_scrollView.contentOffset, {_scrollView.frame.size.width, refreshControl.frame.size.height}}; } #endif [self updateClippedSubviews]; } - (void)updateClippedSubviews { // Find a suitable view to use for clipping UIView *clipView = [self react_findClipView]; if (!clipView) { return; } static const CGFloat leeway = 1.0; const CGSize contentSize = _scrollView.contentSize; const CGRect bounds = _scrollView.bounds; const BOOL scrollsHorizontally = contentSize.width > bounds.size.width; const BOOL scrollsVertically = contentSize.height > bounds.size.height; const BOOL shouldClipAgain = CGRectIsNull(_lastClippedToRect) || !CGRectEqualToRect(_lastClippedToRect, bounds) || (scrollsHorizontally && (bounds.size.width < leeway || fabs(_lastClippedToRect.origin.x - bounds.origin.x) >= leeway)) || (scrollsVertically && (bounds.size.height < leeway || fabs(_lastClippedToRect.origin.y - bounds.origin.y) >= leeway)); if (shouldClipAgain) { const CGRect clipRect = CGRectInset(clipView.bounds, -leeway, -leeway); [self react_updateClippedSubviewsWithClipRect:clipRect relativeToView:clipView]; _lastClippedToRect = bounds; } } - (void)setContentInset:(UIEdgeInsets)contentInset { if (UIEdgeInsetsEqualToEdgeInsets(contentInset, _contentInset)) { return; } CGPoint contentOffset = _scrollView.contentOffset; _contentInset = contentInset; [RCTView autoAdjustInsetsForView:self withScrollView:_scrollView updateOffset:NO]; _scrollView.contentOffset = contentOffset; } - (BOOL)isHorizontal:(UIScrollView *)scrollView { return scrollView.contentSize.width > self.frame.size.width; } - (void)scrollToOffset:(CGPoint)offset { [self scrollToOffset:offset animated:YES]; } - (void)scrollToOffset:(CGPoint)offset animated:(BOOL)animated { if (!CGPointEqualToPoint(_scrollView.contentOffset, offset)) { // Ensure at least one scroll event will fire _allowNextScrollNoMatterWhat = YES; [_scrollView setContentOffset:offset animated:animated]; } } /** * If this is a vertical scroll view, scrolls to the bottom. * If this is a horizontal scroll view, scrolls to the right. */ - (void)scrollToEnd:(BOOL)animated { BOOL isHorizontal = [self isHorizontal:_scrollView]; CGPoint offset; if (isHorizontal) { CGFloat offsetX = _scrollView.contentSize.width - _scrollView.bounds.size.width; offset = CGPointMake(MAX(offsetX, 0), 0); } else { CGFloat offsetY = _scrollView.contentSize.height - _scrollView.bounds.size.height; offset = CGPointMake(0, MAX(offsetY, 0)); } if (!CGPointEqualToPoint(_scrollView.contentOffset, offset)) { // Ensure at least one scroll event will fire _allowNextScrollNoMatterWhat = YES; [_scrollView setContentOffset:offset animated:animated]; } } - (void)zoomToRect:(CGRect)rect animated:(BOOL)animated { [_scrollView zoomToRect:rect animated:animated]; } - (void)refreshContentInset { [RCTView autoAdjustInsetsForView:self withScrollView:_scrollView updateOffset:YES]; } #pragma mark - ScrollView delegate #define RCT_SEND_SCROLL_EVENT(_eventName, _userData) { \ NSString *eventName = NSStringFromSelector(@selector(_eventName)); \ [self sendScrollEventWithName:eventName scrollView:_scrollView userData:_userData]; \ } #define RCT_FORWARD_SCROLL_EVENT(call) \ for (NSObject<UIScrollViewDelegate> *scrollViewListener in _scrollListeners) { \ if ([scrollViewListener respondsToSelector:_cmd]) { \ [scrollViewListener call]; \ } \ } #define RCT_SCROLL_EVENT_HANDLER(delegateMethod, eventName) \ - (void)delegateMethod:(UIScrollView *)scrollView \ { \ RCT_SEND_SCROLL_EVENT(eventName, nil); \ RCT_FORWARD_SCROLL_EVENT(delegateMethod:scrollView); \ } RCT_SCROLL_EVENT_HANDLER(scrollViewWillBeginDecelerating, onMomentumScrollBegin) RCT_SCROLL_EVENT_HANDLER(scrollViewDidZoom, onScroll) - (void)addScrollListener:(NSObject<UIScrollViewDelegate> *)scrollListener { [_scrollListeners addObject:scrollListener]; } - (void)removeScrollListener:(NSObject<UIScrollViewDelegate> *)scrollListener { [_scrollListeners removeObject:scrollListener]; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self updateClippedSubviews]; NSTimeInterval now = CACurrentMediaTime(); /** * TODO: this logic looks wrong, and it may be because it is. Currently, if _scrollEventThrottle * is set to zero (the default), the "didScroll" event is only sent once per scroll, instead of repeatedly * while scrolling as expected. However, if you "fix" that bug, ScrollView will generate repeated * warnings, and behave strangely (ListView works fine however), so don't fix it unless you fix that too! */ if (_allowNextScrollNoMatterWhat || (_scrollEventThrottle > 0 && _scrollEventThrottle < (now - _lastScrollDispatchTime))) { if (_DEPRECATED_sendUpdatedChildFrames) { // Calculate changed frames RCT_SEND_SCROLL_EVENT(onScroll, (@{@"updatedChildFrames": [self calculateChildFramesData]})); } else { RCT_SEND_SCROLL_EVENT(onScroll, nil); } // Update dispatch time _lastScrollDispatchTime = now; _allowNextScrollNoMatterWhat = NO; } RCT_FORWARD_SCROLL_EVENT(scrollViewDidScroll:scrollView); } - (NSArray<NSDictionary *> *)calculateChildFramesData { NSMutableArray<NSDictionary *> *updatedChildFrames = [NSMutableArray new]; [[_contentView reactSubviews] enumerateObjectsUsingBlock: ^(UIView *subview, NSUInteger idx, __unused BOOL *stop) { // Check if new or changed CGRect newFrame = subview.frame; BOOL frameChanged = NO; if (self->_cachedChildFrames.count <= idx) { frameChanged = YES; [self->_cachedChildFrames addObject:[NSValue valueWithCGRect:newFrame]]; } else if (!CGRectEqualToRect(newFrame, [self->_cachedChildFrames[idx] CGRectValue])) { frameChanged = YES; self->_cachedChildFrames[idx] = [NSValue valueWithCGRect:newFrame]; } // Create JS frame object if (frameChanged) { [updatedChildFrames addObject: @{ @"index": @(idx), @"x": @(newFrame.origin.x), @"y": @(newFrame.origin.y), @"width": @(newFrame.size.width), @"height": @(newFrame.size.height), }]; } }]; return updatedChildFrames; } - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { _allowNextScrollNoMatterWhat = YES; // Ensure next scroll event is recorded, regardless of throttle RCT_SEND_SCROLL_EVENT(onScrollBeginDrag, nil); RCT_FORWARD_SCROLL_EVENT(scrollViewWillBeginDragging:scrollView); } - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { // snapToInterval // An alternative to enablePaging which allows setting custom stopping intervals, // smaller than a full page size. Often seen in apps which feature horizonally // scrolling items. snapToInterval does not enforce scrolling one interval at a time // but guarantees that the scroll will stop at an interval point. if (self.snapToInterval) { CGFloat snapToIntervalF = (CGFloat)self.snapToInterval; // Find which axis to snap BOOL isHorizontal = [self isHorizontal:scrollView]; // What is the current offset? CGFloat velocityAlongAxis = isHorizontal ? velocity.x : velocity.y; CGFloat targetContentOffsetAlongAxis = isHorizontal ? targetContentOffset->x : targetContentOffset->y; // Offset based on desired alignment CGFloat frameLength = isHorizontal ? self.frame.size.width : self.frame.size.height; CGFloat alignmentOffset = 0.0f; if ([self.snapToAlignment isEqualToString: @"center"]) { alignmentOffset = (frameLength * 0.5f) + (snapToIntervalF * 0.5f); } else if ([self.snapToAlignment isEqualToString: @"end"]) { alignmentOffset = frameLength; } // Pick snap point based on direction and proximity CGFloat fractionalIndex = (targetContentOffsetAlongAxis + alignmentOffset) / snapToIntervalF; NSInteger snapIndex = velocityAlongAxis > 0.0 ? ceil(fractionalIndex) : velocityAlongAxis < 0.0 ? floor(fractionalIndex) : round(fractionalIndex); CGFloat newTargetContentOffset = (snapIndex * snapToIntervalF) - alignmentOffset; // Set new targetContentOffset if (isHorizontal) { targetContentOffset->x = newTargetContentOffset; } else { targetContentOffset->y = newTargetContentOffset; } } NSDictionary *userData = @{ @"velocity": @{ @"x": @(velocity.x), @"y": @(velocity.y) }, @"targetContentOffset": @{ @"x": @(targetContentOffset->x), @"y": @(targetContentOffset->y) } }; RCT_SEND_SCROLL_EVENT(onScrollEndDrag, userData); RCT_FORWARD_SCROLL_EVENT(scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset); } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndDragging:scrollView willDecelerate:decelerate); } - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view { RCT_SEND_SCROLL_EVENT(onScrollBeginDrag, nil); RCT_FORWARD_SCROLL_EVENT(scrollViewWillBeginZooming:scrollView withView:view); } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale { RCT_SEND_SCROLL_EVENT(onScrollEndDrag, nil); RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndZooming:scrollView withView:view atScale:scale); } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { // Fire a final scroll event _allowNextScrollNoMatterWhat = YES; [self scrollViewDidScroll:scrollView]; // Fire the end deceleration event RCT_SEND_SCROLL_EVENT(onMomentumScrollEnd, nil); RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndDecelerating:scrollView); } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { // Fire a final scroll event _allowNextScrollNoMatterWhat = YES; [self scrollViewDidScroll:scrollView]; // Fire the end deceleration event RCT_SEND_SCROLL_EVENT(onMomentumScrollEnd, nil); //TODO: shouldn't this be onScrollAnimationEnd? RCT_FORWARD_SCROLL_EVENT(scrollViewDidEndScrollingAnimation:scrollView); } - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView { for (NSObject<UIScrollViewDelegate> *scrollListener in _scrollListeners) { if ([scrollListener respondsToSelector:_cmd] && ![scrollListener scrollViewShouldScrollToTop:scrollView]) { return NO; } } return YES; } - (UIView *)viewForZoomingInScrollView:(__unused UIScrollView *)scrollView { return _contentView; } #pragma mark - Setters - (CGSize)_calculateViewportSize { CGSize viewportSize = self.bounds.size; if (_automaticallyAdjustContentInsets) { UIEdgeInsets contentInsets = [RCTView contentInsetsForView:self]; viewportSize = CGSizeMake(self.bounds.size.width - contentInsets.left - contentInsets.right, self.bounds.size.height - contentInsets.top - contentInsets.bottom); } return viewportSize; } - (CGPoint)calculateOffsetForContentSize:(CGSize)newContentSize { CGPoint oldOffset = _scrollView.contentOffset; CGPoint newOffset = oldOffset; CGSize oldContentSize = _scrollView.contentSize; CGSize viewportSize = [self _calculateViewportSize]; BOOL fitsinViewportY = oldContentSize.height <= viewportSize.height && newContentSize.height <= viewportSize.height; if (newContentSize.height < oldContentSize.height && !fitsinViewportY) { CGFloat offsetHeight = oldOffset.y + viewportSize.height; if (oldOffset.y < 0) { // overscrolled on top, leave offset alone } else if (offsetHeight > oldContentSize.height) { // overscrolled on the bottom, preserve overscroll amount newOffset.y = MAX(0, oldOffset.y - (oldContentSize.height - newContentSize.height)); } else if (offsetHeight > newContentSize.height) { // offset falls outside of bounds, scroll back to end of list newOffset.y = MAX(0, newContentSize.height - viewportSize.height); } } BOOL fitsinViewportX = oldContentSize.width <= viewportSize.width && newContentSize.width <= viewportSize.width; if (newContentSize.width < oldContentSize.width && !fitsinViewportX) { CGFloat offsetHeight = oldOffset.x + viewportSize.width; if (oldOffset.x < 0) { // overscrolled at the beginning, leave offset alone } else if (offsetHeight > oldContentSize.width && newContentSize.width > viewportSize.width) { // overscrolled at the end, preserve overscroll amount as much as possible newOffset.x = MAX(0, oldOffset.x - (oldContentSize.width - newContentSize.width)); } else if (offsetHeight > newContentSize.width) { // offset falls outside of bounds, scroll back to end newOffset.x = MAX(0, newContentSize.width - viewportSize.width); } } // all other cases, offset doesn't change return newOffset; } /** * Once you set the `contentSize`, to a nonzero value, it is assumed to be * managed by you, and we'll never automatically compute the size for you, * unless you manually reset it back to {0, 0} */ - (CGSize)contentSize { if (!CGSizeEqualToSize(_contentSize, CGSizeZero)) { return _contentSize; } return _contentView.frame.size; } - (void)reactBridgeDidFinishTransaction { CGSize contentSize = self.contentSize; if (!CGSizeEqualToSize(_scrollView.contentSize, contentSize)) { // When contentSize is set manually, ScrollView internals will reset // contentOffset to {0, 0}. Since we potentially set contentSize whenever // anything in the ScrollView updates, we workaround this issue by manually // adjusting contentOffset whenever this happens CGPoint newOffset = [self calculateOffsetForContentSize:contentSize]; _scrollView.contentSize = contentSize; _scrollView.contentOffset = newOffset; } } // Note: setting several properties of UIScrollView has the effect of // resetting its contentOffset to {0, 0}. To prevent this, we generate // setters here that will record the contentOffset beforehand, and // restore it after the property has been set. #define RCT_SET_AND_PRESERVE_OFFSET(setter, getter, type) \ - (void)setter:(type)value \ { \ CGPoint contentOffset = _scrollView.contentOffset; \ [_scrollView setter:value]; \ _scrollView.contentOffset = contentOffset; \ } \ - (type)getter \ { \ return [_scrollView getter]; \ } RCT_SET_AND_PRESERVE_OFFSET(setAlwaysBounceHorizontal, alwaysBounceHorizontal, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setAlwaysBounceVertical, alwaysBounceVertical, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setBounces, bounces, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setBouncesZoom, bouncesZoom, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setCanCancelContentTouches, canCancelContentTouches, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setDecelerationRate, decelerationRate, CGFloat) RCT_SET_AND_PRESERVE_OFFSET(setDirectionalLockEnabled, isDirectionalLockEnabled, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setIndicatorStyle, indicatorStyle, UIScrollViewIndicatorStyle) RCT_SET_AND_PRESERVE_OFFSET(setKeyboardDismissMode, keyboardDismissMode, UIScrollViewKeyboardDismissMode) RCT_SET_AND_PRESERVE_OFFSET(setMaximumZoomScale, maximumZoomScale, CGFloat) RCT_SET_AND_PRESERVE_OFFSET(setMinimumZoomScale, minimumZoomScale, CGFloat) RCT_SET_AND_PRESERVE_OFFSET(setScrollEnabled, isScrollEnabled, BOOL) #if !TARGET_OS_TV RCT_SET_AND_PRESERVE_OFFSET(setPagingEnabled, isPagingEnabled, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setScrollsToTop, scrollsToTop, BOOL) #endif RCT_SET_AND_PRESERVE_OFFSET(setShowsHorizontalScrollIndicator, showsHorizontalScrollIndicator, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setShowsVerticalScrollIndicator, showsVerticalScrollIndicator, BOOL) RCT_SET_AND_PRESERVE_OFFSET(setZoomScale, zoomScale, CGFloat); RCT_SET_AND_PRESERVE_OFFSET(setScrollIndicatorInsets, scrollIndicatorInsets, UIEdgeInsets); - (void)sendScrollEventWithName:(NSString *)eventName scrollView:(UIScrollView *)scrollView userData:(NSDictionary *)userData { if (![_lastEmittedEventName isEqualToString:eventName]) { _coalescingKey++; _lastEmittedEventName = [eventName copy]; } RCTScrollEvent *scrollEvent = [[RCTScrollEvent alloc] initWithEventName:eventName reactTag:self.reactTag scrollView:scrollView userData:userData coalescingKey:_coalescingKey]; [_eventDispatcher sendEvent:scrollEvent]; } @end @implementation RCTEventDispatcher (RCTScrollView) - (void)sendFakeScrollEvent:(NSNumber *)reactTag { // Use the selector here in case the onScroll block property is ever renamed NSString *eventName = NSStringFromSelector(@selector(onScroll)); RCTScrollEvent *fakeScrollEvent = [[RCTScrollEvent alloc] initWithEventName:eventName reactTag:reactTag scrollView:nil userData:nil coalescingKey:0]; [self sendEvent:fakeScrollEvent]; } @end
{ "content_hash": "e3742239708d0f4831fb3cd8a10ca947", "timestamp": "", "source": "github", "line_count": 911, "max_line_length": 156, "avg_line_length": 34.817782656421514, "alnum_prop": 0.7104259276774173, "repo_name": "skevy/react-native", "id": "124f3a5b6d631c79d5b38a2dcd71d15406d1e968", "size": "32027", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "React/Views/RCTScrollView.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "15392" }, { "name": "Awk", "bytes": "121" }, { "name": "Batchfile", "bytes": "683" }, { "name": "C", "bytes": "212653" }, { "name": "C++", "bytes": "673723" }, { "name": "CSS", "bytes": "43643" }, { "name": "HTML", "bytes": "174330" }, { "name": "IDL", "bytes": "2122" }, { "name": "Java", "bytes": "2864759" }, { "name": "JavaScript", "bytes": "3727524" }, { "name": "Makefile", "bytes": "6696" }, { "name": "Objective-C", "bytes": "1614806" }, { "name": "Objective-C++", "bytes": "247402" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "135578" }, { "name": "Ruby", "bytes": "12927" }, { "name": "Shell", "bytes": "42291" } ], "symlink_target": "" }
// .NAME vtkQuadricDecimation - reduce the number of triangles in a mesh // .SECTION Description // vtkQuadricDecimation is a filter to reduce the number of triangles in // a triangle mesh, forming a good approximation to the original geometry. // The input to vtkQuadricDecimation is a vtkPolyData object, and only // triangles are treated. If you desire to decimate polygonal meshes, first // triangulate the polygons with vtkTriangleFilter. // // The algorithm is based on repeated edge collapses until the requested mesh // reduction is achieved. Edges are placed in a priority queue based on the // "cost" to delete the edge. The cost is an approximate measure of error // (distance to the original surface)--described by the so-called quadric // error measure. The quadric error measure is associated with each vertex of // the mesh and represents a matrix of planes incident on that vertex. The // distance of the planes to the vertex is the error in the position of the // vertex (originally the vertex error iz zero). As edges are deleted, the // quadric error measure associated with the two end points of the edge are // summed (this combines the plane equations) and an optimal collapse point // can be computed. Edges connected to the collapse point are then reinserted // into the queue after computing the new cost to delete them. The process // continues until the desired reduction level is reached or topological // constraints prevent further reduction. Note that this basic algorithm can // be extended to higher dimensions by // taking into account variation in attributes (i.e., scalars, vectors, and // so on). // // This paper is based on the work of Garland and Heckbert who first // presented the quadric error measure at Siggraph '97 "Surface // Simplification Using Quadric Error Metrics". For details of the algorithm // Michael Garland's Ph.D. thesis is also recommended. Hughues Hoppe's Vis // '99 paper, "New Quadric Metric for Simplifying Meshes with Appearance // Attributes" is also a good take on the subject especially as it pertains // to the error metric applied to attributes. // // .SECTION Thanks // Thanks to Bradley Lowekamp of the National Library of Medicine/NIH for // contributing this class. #ifndef __vtkQuadricDecimation_h #define __vtkQuadricDecimation_h #include "vtkPolyDataAlgorithm.h" class vtkEdgeTable; class vtkIdList; class vtkPointData; class vtkPriorityQueue; class vtkDoubleArray; class VTK_GRAPHICS_EXPORT vtkQuadricDecimation : public vtkPolyDataAlgorithm { public: vtkTypeRevisionMacro(vtkQuadricDecimation, vtkPolyDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); static vtkQuadricDecimation *New(); // Description: // Set/Get the desired reduction (expressed as a fraction of the original // number of triangles). The actual reduction may be less depending on // triangulation and topological constraints. vtkSetClampMacro(TargetReduction, double, 0.0, 1.0); vtkGetMacro(TargetReduction, double); // Description: // Decide whether to include data attributes in the error metric. If off, // then only geometric error is used to control the decimation. By default // the attribute errors are off. vtkSetMacro(AttributeErrorMetric, int); vtkGetMacro(AttributeErrorMetric, int); vtkBooleanMacro(AttributeErrorMetric, int); // Description: // If attribute errors are to be included in the metric (i.e., // AttributeErrorMetric is on), then the following flags control which // attributes are to be included in the error calculation. By default all // of these are on. vtkSetMacro(ScalarsAttribute, int); vtkGetMacro(ScalarsAttribute, int); vtkBooleanMacro(ScalarsAttribute, int); vtkSetMacro(VectorsAttribute, int); vtkGetMacro(VectorsAttribute, int); vtkBooleanMacro(VectorsAttribute, int); vtkSetMacro(NormalsAttribute, int); vtkGetMacro(NormalsAttribute, int); vtkBooleanMacro(NormalsAttribute, int); vtkSetMacro(TCoordsAttribute, int); vtkGetMacro(TCoordsAttribute, int); vtkBooleanMacro(TCoordsAttribute, int); vtkSetMacro(TensorsAttribute, int); vtkGetMacro(TensorsAttribute, int); vtkBooleanMacro(TensorsAttribute, int); // Description: // Set/Get the scaling weight contribution of the attribute. These // values are used to weight the contribution of the attributes // towards the error metric. vtkSetMacro(ScalarsWeight, double); vtkSetMacro(VectorsWeight, double); vtkSetMacro(NormalsWeight, double); vtkSetMacro(TCoordsWeight, double); vtkSetMacro(TensorsWeight, double); vtkGetMacro(ScalarsWeight, double); vtkGetMacro(VectorsWeight, double); vtkGetMacro(NormalsWeight, double); vtkGetMacro(TCoordsWeight, double); vtkGetMacro(TensorsWeight, double); // Description: // Get the actual reduction. This value is only valid after the // filter has executed. vtkGetMacro(ActualReduction, double); protected: vtkQuadricDecimation(); ~vtkQuadricDecimation(); int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); // Description: // Do the dirty work of eliminating the edge; return the number of // triangles deleted. int CollapseEdge(vtkIdType pt0Id, vtkIdType pt1Id); // Description: // Compute quadric for all vertices void InitializeQuadrics(vtkIdType numPts); // Description: // Free boundary edges are weighted void AddBoundaryConstraints(void); // Description: // Compute quadric for this vertex. void ComputeQuadric(vtkIdType pointId); // Description: // Add the quadrics for these 2 points since the edge between them has // been collapsed. void AddQuadric(vtkIdType oldPtId, vtkIdType newPtId); // Description: // Compute cost for contracting this edge and the point that gives us this // cost. double ComputeCost(vtkIdType edgeId, double *x); double ComputeCost2(vtkIdType edgeId, double *x); // Description: // Find all edges that will have an endpoint change ids because of an edge // collapse. p1Id and p2Id are the endpoints of the edge. p2Id is the // pointId being removed. void FindAffectedEdges(vtkIdType p1Id, vtkIdType p2Id, vtkIdList *edges); // Description: // Find a cell that uses this edge. vtkIdType GetEdgeCellId(vtkIdType p1Id, vtkIdType p2Id); int IsGoodPlacement(vtkIdType pt0Id, vtkIdType pt1Id, const double *x); int TrianglePlaneCheck(const double t0[3], const double t1[3], const double t2[3], const double *x); void ComputeNumberOfComponents(void); void UpdateEdgeData(vtkIdType ptoId, vtkIdType pt1Id); // Description: // Helper function to set and get the point and it's attributes as an array void SetPointAttributeArray(vtkIdType ptId, const double *x); void GetPointAttributeArray(vtkIdType ptId, double *x); // Description: // Find out how many components there are for each attribute for this // poly data. void GetAttributeComponents(); double TargetReduction; double ActualReduction; int AttributeErrorMetric; int ScalarsAttribute; int VectorsAttribute; int NormalsAttribute; int TCoordsAttribute; int TensorsAttribute; double ScalarsWeight; double VectorsWeight; double NormalsWeight; double TCoordsWeight; double TensorsWeight; int NumberOfEdgeCollapses; vtkEdgeTable *Edges; vtkIdList *EndPoint1List; vtkIdList *EndPoint2List; vtkPriorityQueue *EdgeCosts; vtkDoubleArray *TargetPoints; int NumberOfComponents; vtkPolyData *Mesh; //BTX struct ErrorQuadric { double *Quadric; }; //ETX ErrorQuadric *ErrorQuadrics; int AttributeComponents[6]; double AttributeScale[6]; // Temporary variables for performance vtkIdList *CollapseCellIds; double *TempX; double *TempQuad; double *TempB; double **TempA; double *TempData; private: vtkQuadricDecimation(const vtkQuadricDecimation&); // Not implemented. void operator=(const vtkQuadricDecimation&); // Not implemented. }; #endif
{ "content_hash": "a2e278893fde86f2b7602d33caa0ac90", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 85, "avg_line_length": 36.15695067264574, "alnum_prop": 0.7526975071313406, "repo_name": "sgh/vtk", "id": "cb507afdf24f537aea615335a4fca649bca77536", "size": "8653", "binary": false, "copies": "1", "ref": "refs/heads/vtk-5.0.4_compilation_fixes", "path": "Graphics/vtkQuadricDecimation.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "9874" }, { "name": "C", "bytes": "12696174" }, { "name": "C++", "bytes": "23714469" }, { "name": "Java", "bytes": "60000" }, { "name": "Objective-C", "bytes": "269592" }, { "name": "Pascal", "bytes": "3255" }, { "name": "Perl", "bytes": "173644" }, { "name": "Python", "bytes": "660699" }, { "name": "Shell", "bytes": "1549" }, { "name": "Tcl", "bytes": "1703282" } ], "symlink_target": "" }
import { LinkContainer } from 'react-router-bootstrap' import { Navbar, Nav, NavItem } from 'react-bootstrap' import React from 'react' import { signIn, signUp } from 'routes' const PublicHeader = () => ( <Navbar> <Navbar.Header> <Navbar.Brand> <LinkContainer to='/'> <a>Invoices</a> </LinkContainer> </Navbar.Brand> </Navbar.Header> <Nav pullRight> <LinkContainer to={signIn()}> <NavItem>Sign in</NavItem> </LinkContainer> <LinkContainer to={signUp()}> <NavItem>Sign up</NavItem> </LinkContainer> </Nav> </Navbar> ) export default PublicHeader
{ "content_hash": "2d067e7a18964d4bfa7d5947420cede5", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 54, "avg_line_length": 23.925925925925927, "alnum_prop": 0.6068111455108359, "repo_name": "danielmoraes/invoices-web-client", "id": "541127752d9b07614c724f1b3aa9a6619921a925", "size": "646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/containers/Home/Header.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "956" }, { "name": "HTML", "bytes": "445" }, { "name": "JavaScript", "bytes": "154417" }, { "name": "Nginx", "bytes": "201" } ], "symlink_target": "" }
<?php namespace Cake\View\Helper; use Cake\Utility\Time; use Cake\View\Helper; use Cake\View\Helper\StringTemplateTrait; /** * Time Helper class for easy use of time data. * * Manipulation of time data. * * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html * @see \Cake\Utility\Time */ class TimeHelper extends Helper { use StringTemplateTrait; /** * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return Cake\Utility\Time * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function fromString($dateString, $timezone = null) { return (new Time($dateString))->timezone($timezone); } /** * Returns a nicely formatted date string for given Datetime string. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @param string $format The format to use. If null, `CakeTime::$niceFormat` is used * @return string Formatted date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function nice($dateString = null, $timezone = null, $locale = null) { return (new Time($dateString))->nice($timezone, $locale); } /** * Returns true if given datetime string is today. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string is today * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isToday($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isToday(); } /** * Returns true if given datetime string is in the future. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string is today * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isFuture($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isFuture(); } /** * Returns true if given datetime string is in the past. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string is today * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isPast($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isPast(); } /** * Returns true if given datetime string is within this week. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string is within current week * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isThisWeek($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isThisWeek(); } /** * Returns true if given datetime string is within this month * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string is within current month * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isThisMonth($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isThisMonth(); } /** * Returns true if given datetime string is within current year. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string is within current year * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isThisYear($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isThisYear(); } /** * Returns true if given datetime string was yesterday. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string was yesterday * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time * */ public function wasYesterday($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isYesterday(); } /** * Returns true if given datetime string is tomorrow. * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool True if datetime string was yesterday * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isTomorrow($dateString, $timezone = null) { return (new Time($dateString, $timezone))->isTomorrow(); } /** * Returns the quarter * * @see \Cake\Utility\Time::toQuarter() * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param bool $range if true returns a range in Y-m-d format * @return mixed 1, 2, 3, or 4 quarter of year or array if $range true * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toQuarter($dateString, $range = false) { return (new Time($dateString))->toQuarter($range); } /** * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime(). * * @see \Cake\Utility\Time::toUnix() * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return int Unix timestamp * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toUnix($dateString, $timezone = null) { return (new Time($dateString, $timezone))->toUnixString(); } /** * Returns a date formatted for Atom RSS feeds. * * @see \Cake\Utility\Time::toAtom() * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return string Formatted date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toAtom($dateString, $timezone = null) { $timezone = $timezone ?: date_default_timezone_get(); return (new Time($dateString))->timezone($timezone)->toATOMString(); } /** * Formats date for RSS feeds * * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return string Formatted date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toRSS($dateString, $timezone = null) { $timezone = $timezone ?: date_default_timezone_get(); return (new Time($dateString))->timezone($timezone)->toRSSString(); } /** * Formats date for RSS feeds * * @see \Cake\Utility\Time::timeAgoInWords() * * ## Additional options * * - `element` - The element to wrap the formatted time in. * Has a few additional options: * - `tag` - The tag to use, defaults to 'span'. * - `class` - The class name to use, defaults to `time-ago-in-words`. * - `title` - Defaults to the $dateTime input. * * @param int|string|\DateTime $dateTime UNIX timestamp, strtotime() valid string or DateTime object * @param array $options Default format if timestamp is used in $dateString * @return string Relative time string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function timeAgoInWords($dateTime, array $options = array()) { $element = null; if (!empty($options['element'])) { $element = array( 'tag' => 'span', 'class' => 'time-ago-in-words', 'title' => $dateTime ); if (is_array($options['element'])) { $element = $options['element'] + $element; } else { $element['tag'] = $options['element']; } unset($options['element']); } $relativeDate = (new Time($dateTime))->timeAgoInWords($options); if ($element) { $relativeDate = sprintf( '<%s%s>%s</%s>', $element['tag'], $this->templater()->formatAttributes($element, array('tag')), $relativeDate, $element['tag'] ); } return $relativeDate; } /** * Returns true if specified datetime was within the interval specified, else false. * @see \Cake\Utility\Time::wasWithinLast() * * @param string|int $timeInterval the numeric value with space then time type. * Example of valid types: 6 hours, 2 days, 1 minute. * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function wasWithinLast($timeInterval, $dateString, $timezone = null) { return (new Time($dateString, $timezone))->wasWithinLast($timeInterval); } /** * Returns true if specified datetime is within the interval specified, else false. * * @see \Cake\Utility\Time::isWithinLast() * * @param string|int $timeInterval the numeric value with space then time type. * Example of valid types: 6 hours, 2 days, 1 minute. * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return bool * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isWithinNext($timeInterval, $dateString, $timezone = null) { return (new Time($dateString, $timezone))->isWithinNext($timeInterval); } /** * Returns gmt as a UNIX timestamp. * * @see \Cake\Utility\Time::gmt() * * @param int|string|\DateTime $string UNIX timestamp, strtotime() valid string or DateTime object * @return int UNIX timestamp * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function gmt($string = null) { return (new Time($string))->toUnixString(); } /** * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string. * This function also accepts a time string and a format string as first and second parameters. * In that case this function behaves as a wrapper for Time::i18nFormat() * * @see \Cake\Utility\Time::i18nFormat() * * @param int|string|\DateTime $date UNIX timestamp, strtotime() valid string or DateTime object (or a date format string) * @param int|string $format date format string (or a UNIX timestamp, strtotime() valid string or DateTime object) * @param bool|string $invalid Default value to display on invalid dates * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return string Formatted and translated date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function format($date, $format = null, $invalid = false, $timezone = null) { return $this->i18nFormat($date, $format, $invalid, $timezone); } /** * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string. * It takes into account the default date format for the current language if a LC_TIME file is used. * * @see \Cake\Utility\Time::i18nFormat() * * @param int|string|\DateTime $date UNIX timestamp, strtotime() valid string or DateTime object * @param string $format strftime format string. * @param bool|string $invalid Default value to display on invalid dates * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object * @return string Formatted and translated date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting * @throws \InvalidArgumentException When the date cannot be parsed */ public function i18nFormat($date, $format = null, $invalid = false, $timezone = null) { try { $time = new Time($date, $timezone); return $time->i18nFormat($format, $timezone); } catch (\Exception $e) { if ($invalid === false) { throw $e; } return $invalid; } } /** * Event listeners. * * @return array */ public function implementedEvents() { return []; } }
{ "content_hash": "4c83f23e39498d64a516ac26e430470b", "timestamp": "", "source": "github", "line_count": 345, "max_line_length": 122, "avg_line_length": 38.791304347826085, "alnum_prop": 0.7225584697003662, "repo_name": "Numerico-Informatic-Systems-Pvt-Ltd/gsmpoly", "id": "6b8c5b00382ddc1ee561ee2c502d8494d5124bda", "size": "13968", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/View/Helper/TimeHelper.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1111" }, { "name": "Batchfile", "bytes": "2888" }, { "name": "CSS", "bytes": "104301" }, { "name": "HTML", "bytes": "4567" }, { "name": "JavaScript", "bytes": "28277" }, { "name": "PHP", "bytes": "15497518" }, { "name": "Shell", "bytes": "4170" } ], "symlink_target": "" }
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="admin"> <!-- route ID should be equal to the route front name (https://github.com/magento/magento2/pull/11020) --> <route id="prxgt" frontName="prxgt"> <module name="Praxigento_Core"/> </route> </router> </config>
{ "content_hash": "292c83d53496e7739615ca37db93470b", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 114, "avg_line_length": 45.888888888888886, "alnum_prop": 0.6440677966101694, "repo_name": "praxigento/mobi_mod_mage2_core", "id": "e5456a9a61b3521daff96a40e8572effb2039e69", "size": "413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "etc/adminhtml/routes.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "296446" } ], "symlink_target": "" }
<?php require $_SERVER['DOCUMENT_ROOT'] . '/app/libs/uoj-lib.php'; require UOJContext::documentRoot().'/app/route.php'; require UOJContext::documentRoot().'/app/controllers/subdomain/blog/route.php'; include UOJContext::documentRoot().'/app/controllers'.call_user_func(function() { $route = Route::dispatch(); $q_pos = strpos($route['action'], '?'); if ($q_pos === false) { $path = $route['action']; } else { parse_str(substr($route['action'], $q_pos + 1), $vars); $_GET += $vars; $path = substr($route['action'], 0, $q_pos); } if (isset($route['onload'])) { call_user_func($route['onload']); } return $path; });
{ "content_hash": "cdcc7f07ccbd004a647ba110fd0adbdc", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 81, "avg_line_length": 25.6, "alnum_prop": 0.621875, "repo_name": "UniversalOJ/UOJ-System", "id": "08506afe1ec4730ba46d59d8ba23a98ed8a6c159", "size": "640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/index.php", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "24869" }, { "name": "C++", "bytes": "193468" }, { "name": "CSS", "bytes": "80280" }, { "name": "Dockerfile", "bytes": "2618" }, { "name": "HTML", "bytes": "381504" }, { "name": "JavaScript", "bytes": "654521" }, { "name": "Makefile", "bytes": "1099" }, { "name": "PHP", "bytes": "402274" }, { "name": "Python", "bytes": "11545" }, { "name": "SCSS", "bytes": "58562" }, { "name": "Shell", "bytes": "15178" } ], "symlink_target": "" }
require 'spec_helper' require_relative 'set_environment' shared_examples 'add rating' do include_context 'set environment' it 'does not fail with cascadeCreate' do req = described_class.new('u_id','i_id',1,{'cascadeCreate' => true,'additionalData' => {'answer' => 42}}) resp = @client.send(req) end it 'does not fail with existing item and user' do req = described_class.new('entity_id','entity_id',0) resp = @client.send(req) end it 'fails with nonexisting item id' do req = described_class.new('entity_id','nonex_id',-1) expect { @client.send(req) }.to raise_exception { |exception| expect(exception).to be_a(RecombeeApiClient::ResponseError) expect(exception.status_code).to eq 404 } end it 'fails with nonexisting user id' do req = described_class.new('nonex_id','entity_id',0.5) expect { @client.send(req) }.to raise_exception { |exception| expect(exception).to be_a(RecombeeApiClient::ResponseError) expect(exception.status_code).to eq 404 } end it 'fails with invalid time' do req = described_class.new('entity_id','entity_id',0,{'timestamp' => -15}) expect { @client.send(req) }.to raise_exception { |exception| expect(exception).to be_a(RecombeeApiClient::ResponseError) expect(exception.status_code).to eq 400 } end it 'fails with invalid rating' do req = described_class.new('entity_id','entity_id',-2) expect { @client.send(req) }.to raise_exception { |exception| expect(exception).to be_a(RecombeeApiClient::ResponseError) expect(exception.status_code).to eq 400 } end it 'really stores interaction to the system' do req = described_class.new('u_id','i_id',0.3,{'cascadeCreate' => true,'timestamp' => 5}) resp = @client.send(req) expect { @client.send(req) }.to raise_exception { |exception| expect(exception).to be_a(RecombeeApiClient::ResponseError) expect(exception.status_code).to eq 409 } end end
{ "content_hash": "d8a95d563b9edc125de8da6478a6e1b0", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 109, "avg_line_length": 35.19298245614035, "alnum_prop": 0.6669990029910269, "repo_name": "Recombee/ruby-api-client", "id": "cde1511c1f0875e28f3a7e3b11a415a973bd2520", "size": "2054", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/api/add_rating.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "177399" } ], "symlink_target": "" }
<?php namespace Google\AdsApi\AdWords\v201809\mcm; /** * This file was generated from WSDL. DO NOT EDIT. */ class PendingInvitationSelector { /** * @var int[] $managerCustomerIds */ protected $managerCustomerIds = null; /** * @var int[] $clientCustomerIds */ protected $clientCustomerIds = null; /** * @param int[] $managerCustomerIds * @param int[] $clientCustomerIds */ public function __construct(array $managerCustomerIds = null, array $clientCustomerIds = null) { $this->managerCustomerIds = $managerCustomerIds; $this->clientCustomerIds = $clientCustomerIds; } /** * @return int[] */ public function getManagerCustomerIds() { return $this->managerCustomerIds; } /** * @param int[] $managerCustomerIds * @return \Google\AdsApi\AdWords\v201809\mcm\PendingInvitationSelector */ public function setManagerCustomerIds(array $managerCustomerIds) { $this->managerCustomerIds = $managerCustomerIds; return $this; } /** * @return int[] */ public function getClientCustomerIds() { return $this->clientCustomerIds; } /** * @param int[] $clientCustomerIds * @return \Google\AdsApi\AdWords\v201809\mcm\PendingInvitationSelector */ public function setClientCustomerIds(array $clientCustomerIds) { $this->clientCustomerIds = $clientCustomerIds; return $this; } }
{ "content_hash": "d44e79f154ea2d5173b14d2dd962294c", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 98, "avg_line_length": 22, "alnum_prop": 0.6323529411764706, "repo_name": "googleads/googleads-php-lib", "id": "b8ef886f783f389025e3be6a809034a47e27f79c", "size": "1496", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/Google/AdsApi/AdWords/v201809/mcm/PendingInvitationSelector.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "11415914" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>GLFW: Introduction to the API</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="extra.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <div class="glfwheader"> <a href="http://www.glfw.org/" id="glfwhome">GLFW</a> <ul class="glfwnavbar"> <li><a href="http://www.glfw.org/documentation.html">Documentation</a></li> <li><a href="http://www.glfw.org/download.html">Download</a></li> <li><a href="http://www.glfw.org/media.html">Media</a></li> <li><a href="http://www.glfw.org/community.html">Community</a></li> </ul> </div> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <!-- 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><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Introduction to the API </div> </div> </div><!--header--> <div class="contents"> <div class="toc"><h3>Table of Contents</h3> <ul><li class="level1"><a href="#intro_init">Initialization and termination</a><ul><li class="level2"><a href="#intro_init_init">Initializing GLFW</a></li> <li class="level2"><a href="#intro_init_terminate">Terminating GLFW</a></li> </ul> </li> <li class="level1"><a href="#error_handling">Error handling</a></li> <li class="level1"><a href="#coordinate_systems">Coordinate systems</a></li> <li class="level1"><a href="#guarantees_limitations">Guarantees and limitations</a><ul><li class="level2"><a href="#lifetime">Pointer lifetimes</a></li> <li class="level2"><a href="#reentrancy">Reentrancy</a></li> <li class="level2"><a href="#thread_safety">Thread safety</a></li> <li class="level2"><a href="#compatibility">Version compatibility</a></li> <li class="level2"><a href="#event_order">Event order</a></li> </ul> </li> <li class="level1"><a href="#intro_version">Version management</a><ul><li class="level2"><a href="#intro_version_compile">Compile-time version</a></li> <li class="level2"><a href="#intro_version_runtime">Run-time version</a></li> <li class="level2"><a href="#intro_version_string">Version string</a></li> </ul> </li> </ul> </div> <div class="textblock"><p>This guide introduces the basic concepts of GLFW and describes initialization reference error handling and API guarantees and limitations. For a broad but shallow tutorial, see <a class="el" href="quick_guide.html">Getting started</a> instead. For details on a specific function, see the <a class="el" href="group__init.html">reference documentation</a>.</p> <p>There are also guides for the other areas of GLFW.</p> <ul> <li><a class="el" href="window_guide.html">Window guide</a></li> <li><a class="el" href="context_guide.html">Context guide</a></li> <li><a class="el" href="vulkan_guide.html">Vulkan guide</a></li> <li><a class="el" href="monitor_guide.html">Monitor guide</a></li> <li><a class="el" href="input_guide.html">Input guide</a></li> </ul> <h1><a class="anchor" id="intro_init"></a> Initialization and termination</h1> <p>Before most GLFW functions may be called, the library must be initialized. This initialization checks what features are available on the machine, enumerates monitors and joysticks, initializes the timer and performs any required platform-specific initialization.</p> <p>Only the following functions may be called before the library has been successfully initialized, and only from the main thread.</p> <ul> <li><a class="el" href="group__init.html#ga9f8ffaacf3c269cc48eafbf8b9b71197">glfwGetVersion</a></li> <li><a class="el" href="group__init.html#ga23d47dc013fce2bf58036da66079a657">glfwGetVersionString</a></li> <li><a class="el" href="group__init.html#gaa5d796c3cf7c1a7f02f845486333fb5f">glfwSetErrorCallback</a></li> <li><a class="el" href="group__init.html#ga317aac130a235ab08c6db0834907d85e">glfwInit</a></li> <li><a class="el" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a></li> </ul> <p>Calling any other function before that time will cause a <a class="el" href="group__errors.html#ga2374ee02c177f12e1fa76ff3ed15e14a">GLFW_NOT_INITIALIZED</a> error.</p> <h2><a class="anchor" id="intro_init_init"></a> Initializing GLFW</h2> <p>The library is initialized with <a class="el" href="group__init.html#ga317aac130a235ab08c6db0834907d85e">glfwInit</a>, which returns <code>GLFW_FALSE</code> if an error occurred.</p> <div class="fragment"><div class="line"><span class="keywordflow">if</span> (!<a class="code" href="group__init.html#ga317aac130a235ab08c6db0834907d85e">glfwInit</a>())</div><div class="line">{</div><div class="line"> <span class="comment">// Handle initialization failure</span></div><div class="line">}</div></div><!-- fragment --><p>If any part of initialization fails, all remaining bits are terminated as if <a class="el" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a> was called. The library only needs to be initialized once and additional calls to an already initialized library will simply return <code>GLFW_TRUE</code> immediately.</p> <p>Once the library has been successfully initialized, it should be terminated before the application exits.</p> <h2><a class="anchor" id="intro_init_terminate"></a> Terminating GLFW</h2> <p>Before your application exits, you should terminate the GLFW library if it has been initialized. This is done with <a class="el" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a>.</p> <div class="fragment"><div class="line"><a class="code" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a>();</div></div><!-- fragment --><p>This will destroy any remaining window, monitor and cursor objects, restore any modified gamma ramps, re-enable the screensaver if it had been disabled and free any resources allocated by GLFW.</p> <p>Once the library is terminated, it is as if it had never been initialized and you will need to initialize it again before being able to use GLFW. If the library was not initialized or had already been terminated, it return immediately.</p> <h1><a class="anchor" id="error_handling"></a> Error handling</h1> <p>Some GLFW functions have return values that indicate an error, but this is often not very helpful when trying to figure out <em>why</em> the error occurred. Some functions also return otherwise valid values on error. Finally, far from all GLFW functions have return values.</p> <p>This is where the error callback comes in. This callback is called whenever an error occurs. It is set with <a class="el" href="group__init.html#gaa5d796c3cf7c1a7f02f845486333fb5f">glfwSetErrorCallback</a>, a function that may be called regardless of whether GLFW is initialized.</p> <div class="fragment"><div class="line"><a class="code" href="group__init.html#gaa5d796c3cf7c1a7f02f845486333fb5f">glfwSetErrorCallback</a>(error_callback);</div></div><!-- fragment --><p>The error callback receives a human-readable description of the error and (when possible) its cause. The description encoded as UTF-8. The callback is also provided with an <a class="el" href="group__errors.html">error code</a>.</p> <div class="fragment"><div class="line"><span class="keywordtype">void</span> error_callback(<span class="keywordtype">int</span> error, <span class="keyword">const</span> <span class="keywordtype">char</span>* description)</div><div class="line">{</div><div class="line"> puts(description);</div><div class="line">}</div></div><!-- fragment --><p>The error code indicates the general category of the error. Some error codes, such as <a class="el" href="group__errors.html#ga2374ee02c177f12e1fa76ff3ed15e14a">GLFW_NOT_INITIALIZED</a> has only a single meaning, whereas others like <a class="el" href="group__errors.html#gad44162d78100ea5e87cdd38426b8c7a1">GLFW_PLATFORM_ERROR</a> are used for many different errors.</p> <p>The description string is only valid until the error callback returns, as it may have been generated specifically for that error. This lets GLFW provide much more specific error descriptions but means you must make a copy if you want to keep the description string.</p> <dl class="section note"><dt>Note</dt><dd>Relying on erroneous behavior is not forward compatible. In other words, do not rely on a currently invalid call to generate a specific error, as that same call may in future versions generate a different error or become valid.</dd></dl> <h1><a class="anchor" id="coordinate_systems"></a> Coordinate systems</h1> <p>GLFW has two primary coordinate systems: the <em>virtual screen</em> and the window <em>client area</em> or <em>content area</em>. Both use the same unit: <em>virtual screen coordinates</em>, or just <em>screen coordinates</em>, which don't necessarily correspond to pixels.</p> <div class="image"> <img src="spaces.svg" width="90%"/> </div> <p>Both the virtual screen and the client area coordinate systems have the X-axis pointing to the right and the Y-axis pointing down.</p> <p>Window and monitor positions are specified as the position of the upper-left corners of their content areas relative to the virtual screen, while cursor positions are specified relative to a window's client area.</p> <p>Because the origin of the window's client area coordinate system is also the point from which the window position is specified, you can translate client area coordinates to the virtual screen by adding the window position. The window frame, when present, extends out from the client area but does not affect the window position.</p> <p>Almost all positions and sizes in GLFW are measured in screen coordinates relative to one of the two origins above. This includes cursor positions, window positions and sizes, window frame sizes, monitor positions and video mode resolutions.</p> <p>Two exceptions are the <a class="el" href="monitor_guide.html#monitor_size">monitor physical size</a>, which is measured in millimetres, and <a class="el" href="window_guide.html#window_fbsize">framebuffer size</a>, which is measured in pixels.</p> <p>Pixels and screen coordinates may map 1:1 on your machine, but they won't on every other machine, for example on a Mac with a Retina display. The ratio between screen coordinates and pixels may also change at run-time depending on which monitor the window is currently considered to be on.</p> <h1><a class="anchor" id="guarantees_limitations"></a> Guarantees and limitations</h1> <p>This section describes the conditions under which GLFW can be expected to function, barring bugs in the operating system or drivers. Use of GLFW outside of these limits may work on some platforms, or on some machines, or some of the time, or on some versions of GLFW, but it may break at any time and this will not be considered a bug.</p> <h2><a class="anchor" id="lifetime"></a> Pointer lifetimes</h2> <p>GLFW will never free any pointer you provide to it and you must never free any pointer it provides to you.</p> <p>Many GLFW functions return pointers to dynamically allocated structures, strings or arrays, and some callbacks are provided with strings or arrays. These are always managed by GLFW and should never be freed by the application. The lifetime of these pointers is documented for each GLFW function and callback. If you need to keep this data, you must copy it before its lifetime expires.</p> <p>Many GLFW functions accept pointers to structures or strings allocated by the application. These are never freed by GLFW and are always the responsibility of the application. If GLFW needs to keep the data in these structures or strings, it is copied before the function returns.</p> <p>Pointer lifetimes are guaranteed not to be shortened in future minor or patch releases.</p> <h2><a class="anchor" id="reentrancy"></a> Reentrancy</h2> <p>GLFW event processing and object creation and destruction are not reentrant. This means that the following functions must not be called from any callback function:</p> <ul> <li><a class="el" href="group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344">glfwCreateWindow</a></li> <li><a class="el" href="group__window.html#gacdf43e51376051d2c091662e9fe3d7b2">glfwDestroyWindow</a></li> <li><a class="el" href="group__input.html#gafca356935e10135016aa49ffa464c355">glfwCreateCursor</a></li> <li><a class="el" href="group__input.html#gaa65f416d03ebbbb5b8db71a489fcb894">glfwCreateStandardCursor</a></li> <li><a class="el" href="group__input.html#ga81b952cd1764274d0db7fb3c5a79ba6a">glfwDestroyCursor</a></li> <li><a class="el" href="group__window.html#ga37bd57223967b4211d60ca1a0bf3c832">glfwPollEvents</a></li> <li><a class="el" href="group__window.html#ga554e37d781f0a997656c26b2c56c835e">glfwWaitEvents</a></li> <li><a class="el" href="group__window.html#ga605a178db92f1a7f1a925563ef3ea2cf">glfwWaitEventsTimeout</a></li> <li><a class="el" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a></li> </ul> <p>These functions may be made reentrant in future minor or patch releases, but functions not on this list will not be made non-reentrant.</p> <h2><a class="anchor" id="thread_safety"></a> Thread safety</h2> <p>Most GLFW functions must only be called from the main thread, but some may be called from any thread. However, no GLFW function may be called from any thread but the main thread until GLFW has been successfully initialized, including functions that may called before initialization.</p> <p>The reference documentation for every GLFW function states whether it is limited to the main thread.</p> <p>Initialization and termination, event processing and the creation and destruction of windows, contexts and cursors are all limited to the main thread due to limitations of one or several platforms.</p> <p>Because event processing must be performed on the main thread, all callbacks except for the error callback will only be called on that thread. The error callback may be called on any thread, as any GLFW function may generate errors.</p> <p>The posting of empty events may be done from any thread. The window user pointer and close flag may also be accessed and modified from any thread, but this is not synchronized by GLFW. The following window related functions may be called from any thread:</p> <ul> <li><a class="el" href="group__window.html#gab5997a25187e9fd5c6f2ecbbc8dfd7e9">glfwPostEmptyEvent</a></li> <li><a class="el" href="group__window.html#ga17807ce0f45ac3f8bb50d6dcc59a4e06">glfwGetWindowUserPointer</a></li> <li><a class="el" href="group__window.html#ga3d2fc6026e690ab31a13f78bc9fd3651">glfwSetWindowUserPointer</a></li> <li><a class="el" href="group__window.html#ga24e02fbfefbb81fc45320989f8140ab5">glfwWindowShouldClose</a></li> <li><a class="el" href="group__window.html#ga49c449dde2a6f87d996f4daaa09d6708">glfwSetWindowShouldClose</a></li> </ul> <p>Rendering may be done on any thread. The following context related functions may be called from any thread:</p> <ul> <li><a class="el" href="group__context.html#ga1c04dc242268f827290fe40aa1c91157">glfwMakeContextCurrent</a></li> <li><a class="el" href="group__context.html#gac84759b1f6c2d271a4fea8ae89ec980d">glfwGetCurrentContext</a></li> <li><a class="el" href="group__window.html#ga15a5a1ee5b3c2ca6b15ca209a12efd14">glfwSwapBuffers</a></li> <li><a class="el" href="group__context.html#ga6d4e0cdf151b5e579bd67f13202994ed">glfwSwapInterval</a></li> <li><a class="el" href="group__context.html#ga87425065c011cef1ebd6aac75e059dfa">glfwExtensionSupported</a></li> <li><a class="el" href="group__context.html#ga35f1837e6f666781842483937612f163">glfwGetProcAddress</a></li> </ul> <p>The raw timer may be queried from any thread. The following raw timer related functions may be called from any thread:</p> <ul> <li><a class="el" href="group__input.html#ga3289ee876572f6e91f06df3a24824443">glfwGetTimerFrequency</a></li> <li><a class="el" href="group__input.html#ga09b2bd37d328e0b9456c7ec575cc26aa">glfwGetTimerValue</a></li> </ul> <p>The regular timer may be used from any thread, but the reading and writing of the timer offset is not synchronized by GLFW. The following timer related functions may be called from any thread:</p> <ul> <li><a class="el" href="group__input.html#gaa6cf4e7a77158a3b8fd00328b1720a4a">glfwGetTime</a></li> <li><a class="el" href="group__input.html#gaf59589ef6e8b8c8b5ad184b25afd4dc0">glfwSetTime</a></li> </ul> <p>Library version information may be queried from any thread. The following version related functions may be called from any thread:</p> <ul> <li><a class="el" href="group__init.html#ga9f8ffaacf3c269cc48eafbf8b9b71197">glfwGetVersion</a></li> <li><a class="el" href="group__init.html#ga23d47dc013fce2bf58036da66079a657">glfwGetVersionString</a></li> </ul> <p>Vulkan objects may be created and information queried from any thread. The following Vulkan related functions may be called from any thread:</p> <ul> <li><a class="el" href="group__vulkan.html#ga2e7f30931e02464b5bc8d0d4b6f9fe2b">glfwVulkanSupported</a></li> <li><a class="el" href="group__vulkan.html#ga1abcbe61033958f22f63ef82008874b1">glfwGetRequiredInstanceExtensions</a></li> <li><a class="el" href="group__vulkan.html#gadf228fac94c5fd8f12423ec9af9ff1e9">glfwGetInstanceProcAddress</a></li> <li><a class="el" href="group__vulkan.html#gaff3823355cdd7e2f3f9f4d9ea9518d92">glfwGetPhysicalDevicePresentationSupport</a></li> <li><a class="el" href="group__vulkan.html#ga1a24536bec3f80b08ead18e28e6ae965">glfwCreateWindowSurface</a></li> </ul> <p>GLFW uses no synchronization objects internally except for thread-local storage to keep track of the current context for each thread. Synchronization is left to the application.</p> <p>Functions that may currently be called from any thread will always remain so, but functions that are currently limited to the main thread may be updated to allow calls from any thread in future releases.</p> <h2><a class="anchor" id="compatibility"></a> Version compatibility</h2> <p>GLFW guarantees binary backward compatibility with earlier minor versions of the API. This means that you can drop in a newer version of the GLFW DLL / shared library / dynamic library and existing applications will continue to run.</p> <p>Once a function or constant has been added, the signature of that function or value of that constant will remain unchanged until the next major version of GLFW. No compatibility of any kind is guaranteed between major versions.</p> <p>Undocumented behavior, i.e. behavior that is not described in the documentation, may change at any time until it is documented.</p> <p>If the reference documentation and the implementation differ, the reference documentation is correct and the implementation will be fixed in the next release.</p> <h2><a class="anchor" id="event_order"></a> Event order</h2> <p>The order of arrival of related events is not guaranteed to be consistent across platforms. The exception is synthetic key and mouse button release events, which are always delivered after the window defocus event.</p> <h1><a class="anchor" id="intro_version"></a> Version management</h1> <p>GLFW provides mechanisms for identifying what version of GLFW your application was compiled against as well as what version it is currently running against. If you are loading GLFW dynamically (not just linking dynamically), you can use this to verify that the library binary is compatible with your application.</p> <h2><a class="anchor" id="intro_version_compile"></a> Compile-time version</h2> <p>The compile-time version of GLFW is provided by the GLFW header with the <code>GLFW_VERSION_MAJOR</code>, <code>GLFW_VERSION_MINOR</code> and <code>GLFW_VERSION_REVISION</code> macros.</p> <div class="fragment"><div class="line">printf(<span class="stringliteral">&quot;Compiled against GLFW %i.%i.%i\n&quot;</span>,</div><div class="line"> <a class="code" href="group__init.html#ga6337d9ea43b22fc529b2bba066b4a576">GLFW_VERSION_MAJOR</a>,</div><div class="line"> <a class="code" href="group__init.html#gaf80d40f0aea7088ff337606e9c48f7a3">GLFW_VERSION_MINOR</a>,</div><div class="line"> <a class="code" href="group__init.html#gab72ae2e2035d9ea461abc3495eac0502">GLFW_VERSION_REVISION</a>);</div></div><!-- fragment --><h2><a class="anchor" id="intro_version_runtime"></a> Run-time version</h2> <p>The run-time version can be retrieved with <a class="el" href="group__init.html#ga9f8ffaacf3c269cc48eafbf8b9b71197">glfwGetVersion</a>, a function that may be called regardless of whether GLFW is initialized.</p> <div class="fragment"><div class="line"><span class="keywordtype">int</span> major, minor, revision;</div><div class="line"><a class="code" href="group__init.html#ga9f8ffaacf3c269cc48eafbf8b9b71197">glfwGetVersion</a>(&amp;major, &amp;minor, &amp;revision);</div><div class="line"></div><div class="line">printf(<span class="stringliteral">&quot;Running against GLFW %i.%i.%i\n&quot;</span>, major, minor, revision);</div></div><!-- fragment --><h2><a class="anchor" id="intro_version_string"></a> Version string</h2> <p>GLFW 3 also provides a compile-time generated version string that describes the version, platform, compiler and any platform-specific compile-time options. This is primarily intended for submitting bug reports, to allow developers to see which code paths are enabled in a binary.</p> <p>The version string is returned by <a class="el" href="group__init.html#ga23d47dc013fce2bf58036da66079a657">glfwGetVersionString</a>, a function that may be called regardless of whether GLFW is initialized.</p> <p><b>Do not use the version string</b> to parse the GLFW library version. The <a class="el" href="group__init.html#ga9f8ffaacf3c269cc48eafbf8b9b71197">glfwGetVersion</a> function already provides the version of the running library binary.</p> <p>The format of the string is as follows:</p><ul> <li>The version of GLFW</li> <li>The name of the window system API</li> <li>The name of the context creation API</li> <li>Any additional options or APIs</li> </ul> <p>For example, when compiling GLFW 3.0 with MinGW using the Win32 and WGL back ends, the version string may look something like this:</p> <div class="fragment"><div class="line">3.0.0 Win32 WGL MinGW</div></div><!-- fragment --> </div></div><!-- contents --> <address class="footer"> <p> Last update on Thu Jun 2 2016 for GLFW 3.2.0 </p> </address> </body> </html>
{ "content_hash": "4043c9e379aaa595bfe98541fe591aad", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 722, "avg_line_length": 95.17424242424242, "alnum_prop": 0.7400302475523363, "repo_name": "yurikoma/PhysicsForGamesAIE_StudentWork", "id": "d07beaba1963bbc550f6fe963d8755841c4ae265", "size": "25126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dependencies/glfw/docs/html/intro_guide.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "281448" }, { "name": "C++", "bytes": "146590" } ], "symlink_target": "" }
In this section, we present our algorithm for bootstrapping new examples from expert demonstrations. At its core, the idea is simple: if we get examples of new states that are able to successfully transfer a trajectory to, we get a new example of a successful manipulation. We can use these examples to transfer trajectories better in new settings. Formally, we assume access to an environment and a reward signal. In our work, this environment is simulated although the approach can apply to real settings. Our reward signal is a 1-0 response which tells us if a manipulation succeeds. For tasks involving several steps, we associate success with a manipulation if a success signal is received before a fixed time horizon is reached. To ease discussion, we will use the concept of a \emph{transfer set}. Given a method for transfering a demonstration trajectory to a new state, the associated transfer set is the set of states such that the transferred trajectory will successfully execute a demonstrated manipulation. The assumption behind the nearest-neighbor selection method from Schulman et al.~\cite{Schulmanetal_ISRR2013} can be stated that states which have a low registration cost to the demonstration scene are likely to be in the transfer set for that demonstration. This assumes that the state space is locally smooth with respect to registration cost. In practice, this assumption has been borne out in the success of this approach. By attempting to transfer trajectories in simulation, we can get additional feedback and examples of states that are in the transfer set for our demonstrations. Continuing with this line of reasoning, a natural next step is to hope that that states that are close (with respect to registration cost) to states in the transfer set are likely to be that transfer set. This suggest a simple way to improve performance through experimentation: given a set of states that a trajectory, $t$, has been successfully transferred to, $S_T$, we select a trajectory to transfer according to the following rule: \begin{equation} \underset{t}{\argmin} \ \ \underset{s\in S_t}{\min} \ \ {\text{registration cost}}(s). \end{equation} We can take this idea a step further. When we succeed in completing a task in a new scenario, we get a new set of states and trajectories that perform our desired manipulation. These are new examples of successful manipulations in their own right. Instead of simply storing the states we successfully transfer to, we can add those examples to our trajectory library and consider transferring the derived trajectories to new scenes. Alg.~\ref{alg:bootstrap} shows an exploration strategy to apply bootstrapping to a trajectory library. The process repeatedly selects the nearest-neighbour with respect to registration cost, and adds it to the trajectory library if successful. \begin{algorithm} \SetKwInOut{trajLib}{input}\SetKwInOut{bootstrapLib}{output} \trajLib{trajLib $= \left[(s_{1},t_{1}), (s_{2}, t_{2}), \ldots \right]$} \bootstrapLib{bootstrapLib, bootstrapped trajectory library} bootstrapLib $\leftarrow$ trajLib\; \For{$i \leftarrow 0$ \KwTo $N$}{ $s_{test}$ $\leftarrow$ sampleNewInitialState()\; $(s_{p}, t_{p})$ $\leftarrow \underset{(s,t)}{\argmin} \ registration\_cost(s, s_{test})$\; $t_{warped}$ $\leftarrow$ $fit\_TPS(s_{p}, s_{test}, t_{parent})$\; \If{successful\_trajectory\_execution}{ bootstrapLib $\leftarrow$ $(s_{p}, t_{warped})$ $\cup$ bootstrapLib \; } } \caption{Bootstrapping a Trajectory Library} \label{alg:bootstrap} \end{algorithm} One possible objection to this method is as follows: given that these derived examples are simply deformations of an original, why would we expect this to be better than simply transferring the original? The answer to this question is based in different aspects of the TPS approach to trajectory transfer. The first is that, in addition to finding a transfer function that minimizes curvature, we are also finding correspondences between points in the different scenes. Finding correspondences is a difficult and well-studied problem in computer vision and the best approaches are subject to local optima. The TPS-RPM algorithm is no exception. We could appeal to local features to improve this difficulty, but finding feature descriptors that capture important aspects of general manipulation problems is a difficult task. The states we add to our trajectory library are examples of states and correspondences that successfully transferred a demonstration trajectory. By transferring directly from those states, as opposed to the original demonstration state, we are providing a better initialization to the TPS-RPM algorithm and we should be able to find better correspondences between points. The second reason we would expect this to be successful is that in transferring derived states and trajectories, we enable the use of a broader class of functions for transferring trajectories. In transferring a trajectory, $t$, from state $s_1$ through state $s_2$ to $s_3$, we compute a thin plate spline from $s_1$ to $s_2$ ($f_{1\rightarrow 2}$) then from $s_2$ to $s_3$ ($f_{2\rightarrow 3}$). The trajectory we execute is then $f_{1\rightarrow 2}(f_{2\rightarrow 3}(t)) \ne f_{1\rightarrow 3}(t)$. Instead of using a thin plate spline, we are using a form of iterated thin plate spline. The intuition behind this is that a thin plate spline represents an encoding of a preference for non-rigid functions to transfer a state. For a general approach, this is a good preference to have. However, for a particular manipulation task, not all deformations will have the same effect on transfer success. As an example, consider a robot transferring trajectories for opening a drawer. In transferring the first portion of a demonstration, almost any deformation is OK: all that needs to happen is that the robot grabs the drawer handle. However, for the second part---actually opening the drawer---almost any non-rigid deformation will result in a failed transfer. In fitting a thin plate spline to derived trajectories, we gain the ability to learn these transfer properties for the manipulation we are exploring. The non-rigid deformations that resulted in successful transfers are no longer penalized in fitting the thin plate spline. For our drawer example, after enough examples of successful transfers this technique would effectively learn to allow certain types of deformations (e.g. those that allow us to grab the drawer) but still maintain the ability to penalize for others (e.g. deformations that do not allow the robot to open the drawer).
{ "content_hash": "2786051774309ca2f5fc1137bf579be3", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 442, "avg_line_length": 73.3076923076923, "alnum_prop": 0.7821915754759406, "repo_name": "dhadfieldmenell/bootstrapping-lfd", "id": "cd133fadf4fa644a081c9c0c1ffa0464f0e98973", "size": "6671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "paper/bootstrapping.tex", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "14266" }, { "name": "Python", "bytes": "449529" }, { "name": "Shell", "bytes": "1045" }, { "name": "TeX", "bytes": "263566" } ], "symlink_target": "" }
namespace extensions { namespace { const char kEnableMediaRouterExperiment[] = "EnableMediaRouter"; const char kEnableMediaRouterWithCastExtensionExperiment[] = "EnableMediaRouterWithCastExtension"; const char kExtensionActionRedesignExperiment[] = "ExtensionActionRedesign"; class CommonSwitches { public: CommonSwitches() : easy_off_store_install(nullptr, FeatureSwitch::DEFAULT_DISABLED), force_dev_mode_highlighting(switches::kForceDevModeHighlighting, FeatureSwitch::DEFAULT_DISABLED), prompt_for_external_extensions( #if defined(CHROMIUM_BUILD) switches::kPromptForExternalExtensions, #else nullptr, #endif #if defined(OS_WIN) FeatureSwitch::DEFAULT_ENABLED), #else FeatureSwitch::DEFAULT_DISABLED), #endif error_console(switches::kErrorConsole, FeatureSwitch::DEFAULT_DISABLED), enable_override_bookmarks_ui(switches::kEnableOverrideBookmarksUI, FeatureSwitch::DEFAULT_DISABLED), extension_action_redesign(switches::kExtensionActionRedesign, kExtensionActionRedesignExperiment, FeatureSwitch::DEFAULT_DISABLED), extension_action_redesign_override(switches::kExtensionActionRedesign, FeatureSwitch::DEFAULT_ENABLED), scripts_require_action(switches::kScriptsRequireAction, FeatureSwitch::DEFAULT_DISABLED), embedded_extension_options(switches::kEmbeddedExtensionOptions, FeatureSwitch::DEFAULT_DISABLED), trace_app_source(switches::kTraceAppSource, FeatureSwitch::DEFAULT_ENABLED), // The switch media-router is defined in // chrome/common/chrome_switches.cc, but we can't depend on chrome here. media_router("media-router", kEnableMediaRouterExperiment, FeatureSwitch::DEFAULT_DISABLED), media_router_with_cast_extension( "media-router", kEnableMediaRouterWithCastExtensionExperiment, FeatureSwitch::DEFAULT_DISABLED) { } // Enables extensions to be easily installed from sites other than the web // store. FeatureSwitch easy_off_store_install; FeatureSwitch force_dev_mode_highlighting; // Should we prompt the user before allowing external extensions to install? // Default is yes. FeatureSwitch prompt_for_external_extensions; FeatureSwitch error_console; FeatureSwitch enable_override_bookmarks_ui; FeatureSwitch extension_action_redesign; FeatureSwitch extension_action_redesign_override; FeatureSwitch scripts_require_action; FeatureSwitch embedded_extension_options; FeatureSwitch trace_app_source; FeatureSwitch media_router; FeatureSwitch media_router_with_cast_extension; }; base::LazyInstance<CommonSwitches> g_common_switches = LAZY_INSTANCE_INITIALIZER; } // namespace FeatureSwitch* FeatureSwitch::force_dev_mode_highlighting() { return &g_common_switches.Get().force_dev_mode_highlighting; } FeatureSwitch* FeatureSwitch::easy_off_store_install() { return &g_common_switches.Get().easy_off_store_install; } FeatureSwitch* FeatureSwitch::prompt_for_external_extensions() { return &g_common_switches.Get().prompt_for_external_extensions; } FeatureSwitch* FeatureSwitch::error_console() { return &g_common_switches.Get().error_console; } FeatureSwitch* FeatureSwitch::enable_override_bookmarks_ui() { return &g_common_switches.Get().enable_override_bookmarks_ui; } FeatureSwitch* FeatureSwitch::extension_action_redesign() { // Force-enable the redesigned extension action toolbar when the Media Router // is enabled. Should be removed when the toolbar redesign is used by default. // See crbug.com/514694 // TODO(kmarshall): Remove this override. if (media_router()->IsEnabled()) return &g_common_switches.Get().extension_action_redesign_override; return &g_common_switches.Get().extension_action_redesign; } FeatureSwitch* FeatureSwitch::scripts_require_action() { return &g_common_switches.Get().scripts_require_action; } FeatureSwitch* FeatureSwitch::embedded_extension_options() { return &g_common_switches.Get().embedded_extension_options; } FeatureSwitch* FeatureSwitch::trace_app_source() { return &g_common_switches.Get().trace_app_source; } FeatureSwitch* FeatureSwitch::media_router() { return &g_common_switches.Get().media_router; } FeatureSwitch* FeatureSwitch::media_router_with_cast_extension() { return &g_common_switches.Get().media_router_with_cast_extension; } FeatureSwitch::ScopedOverride::ScopedOverride(FeatureSwitch* feature, bool override_value) : feature_(feature), previous_value_(feature->GetOverrideValue()) { feature_->SetOverrideValue( override_value ? OVERRIDE_ENABLED : OVERRIDE_DISABLED); } FeatureSwitch::ScopedOverride::~ScopedOverride() { feature_->SetOverrideValue(previous_value_); } FeatureSwitch::FeatureSwitch(const char* switch_name, DefaultValue default_value) : FeatureSwitch(base::CommandLine::ForCurrentProcess(), switch_name, default_value) {} FeatureSwitch::FeatureSwitch(const char* switch_name, const char* field_trial_name, DefaultValue default_value) : FeatureSwitch(base::CommandLine::ForCurrentProcess(), switch_name, field_trial_name, default_value) {} FeatureSwitch::FeatureSwitch(const base::CommandLine* command_line, const char* switch_name, DefaultValue default_value) : FeatureSwitch(command_line, switch_name, nullptr, default_value) {} FeatureSwitch::FeatureSwitch(const base::CommandLine* command_line, const char* switch_name, const char* field_trial_name, DefaultValue default_value) : command_line_(command_line), switch_name_(switch_name), field_trial_name_(field_trial_name), default_value_(default_value == DEFAULT_ENABLED), override_value_(OVERRIDE_NONE) {} bool FeatureSwitch::IsEnabled() const { if (override_value_ != OVERRIDE_NONE) return override_value_ == OVERRIDE_ENABLED; if (!switch_name_) return default_value_; std::string temp = command_line_->GetSwitchValueASCII(switch_name_); std::string switch_value; base::TrimWhitespaceASCII(temp, base::TRIM_ALL, &switch_value); if (switch_value == "1") return true; if (switch_value == "0") return false; if (!default_value_ && command_line_->HasSwitch(GetLegacyEnableFlag())) return true; if (default_value_ && command_line_->HasSwitch(GetLegacyDisableFlag())) return false; if (field_trial_name_) { std::string group_name = base::FieldTrialList::FindFullName(field_trial_name_); if (group_name == "Enabled") return true; if (group_name == "Disabled") return false; } return default_value_; } std::string FeatureSwitch::GetLegacyEnableFlag() const { DCHECK(switch_name_); return std::string("enable-") + switch_name_; } std::string FeatureSwitch::GetLegacyDisableFlag() const { DCHECK(switch_name_); return std::string("disable-") + switch_name_; } void FeatureSwitch::SetOverrideValue(OverrideValue override_value) { override_value_ = override_value; } FeatureSwitch::OverrideValue FeatureSwitch::GetOverrideValue() const { return override_value_; } } // namespace extensions
{ "content_hash": "d15916f8a679e11a59e73e591a5db88f", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 80, "avg_line_length": 36.51643192488263, "alnum_prop": 0.6775520699408588, "repo_name": "Workday/OpenFrame", "id": "f61781fbc6486bbfa63878fd7ba636f6644a5cbb", "size": "8171", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "extensions/common/feature_switch.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import pandas as pd import numpy as np import matplotlib.pyplot as plt import cv2 import math from keras.layers.core import Dense, Activation, Flatten, Dropout, Reshape, Lambda from keras.activations import relu, softmax from keras.layers.pooling import MaxPooling2D from keras.layers.convolutional import Convolution2D from keras.models import Sequential from keras.optimizers import Adam from sklearn.model_selection import train_test_split img_rows, img_cols, ch = 64, 64, 3 def load_image(imagepath): imagepath = imagepath.replace(' ', '') #image = np.array(Image.open(imagepath)) image = cv2.imread(imagepath) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) return image def resize_image(image): shape = image.shape # Crop top and remove hood image = image[math.floor(shape[0]/5):shape[0] - 25:,:] # Resize to 64 x 64 image = cv2.resize(image, (img_rows, img_cols), interpolation=cv2.INTER_AREA) return image def augment_brightness(image): new_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) random_brightness = 0.3 + np.random.uniform() new_image[:,:,2] = new_image[:,:,2] * random_brightness new_image = cv2.cvtColor(new_image, cv2.COLOR_HSV2RGB) return new_image def augment_trans_shifts(image, steer, trans_range): rows, cols, ch = image.shape x_translation = trans_range * np.random.uniform() - trans_range / 2 steer_angle = steer + x_translation / trans_range * 2 * 0.2 y_translation = 40 * np.random.uniform() - 40 / 2 m_translation = np.float32([[1, 0, x_translation], [0, 1, y_translation]]) image_trans = cv2.warpAffine(image, m_translation, (cols, rows)) return image_trans, steer_angle def preprocess(input_files): position = np.random.choice(['center', 'left', 'right'])#, p = [0.40, 0.10, 0.50]) idx = np.random.randint(len(input_files)) image_path = input_file[position][idx] if position == 'left': shift_angle = 0.25 elif position == 'right': shift_angle = -0.25 else: shift_angle = 0. image = load_image(image_path) steer_angle = input_file['steering'][idx] + shift_angle image = augment_brightness(image) image, steer_angle = augment_trans_shifts(image, steer_angle, 70) image = resize_image(image) if np.random.randint(2) == 0: image = cv2.flip(image, 1) steer_angle = -steer_angle return image, steer_angle def generate_data(input_file, batch_size=32): features = np.zeros((batch_size, img_rows, img_cols, ch)) label = np.zeros(batch_size) while True: for i in range(batch_size): X, y = preprocess(input_file) X = X.reshape(1, img_rows, img_cols, 3) features[i] = X label[i] = y yield features, label def get_model(): model = Sequential() model.add(MaxPooling2D(pool_size=(2,2), strides=None, border_mode='valid', input_shape=(64, 64, 3))) model.add(Lambda(lambda x: x / 255. - 0.5)) model.add(Convolution2D(24, 5, 5, border_mode='same')) model.add(Activation('relu')) model.add(Convolution2D(36, 5, 5, border_mode='same')) model.add(Activation('relu')) model.add(Convolution2D(48, 5, 5, border_mode='same')) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3, border_mode='same')) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3, border_mode='same')) model.add(Activation('relu')) model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(100)) model.add(Activation('relu')) model.add(Dense(50)) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('relu')) model.add(Dropout(0.25)) model.add(Dense(1)) #model.summary() return model if __name__ == "__main__": model = get_model() samples_per_epoch = 20000 nb_epoch = 5 val_size = samples_per_epoch / 10. input_file = pd.read_csv('driving_log.csv') data = np.array([resize_image(load_image(img)) for img in input_file['center']]) y = np.array([angle for angle in input_file['steering']]) X_test, X_val, y_test, y_val = train_test_split(data, y, test_size=0.33, random_state=42) train_generator = generate_data(input_file) adam = Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0) model.compile(optimizer=adam, loss='mean_squared_error', metrics=['accuracy']) model.fit_generator(train_generator, samples_per_epoch=samples_per_epoch, nb_epoch=nb_epoch, validation_data=(X_val, y_val), nb_val_samples=val_size, verbose=1) score = model.evaluate(X_test, y_test) print("Test data %s: %.3f" % (model.metrics_names[1], score[1])) # Save model json_string = model.to_json() model.save_weights('./model.h5') import json with open("model.json", "w") as json_file: json_file.write(json_string)
{ "content_hash": "fa4fa885985bb4254a498cfc624d2d45", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 104, "avg_line_length": 31.673076923076923, "alnum_prop": 0.6460230722525805, "repo_name": "olinguyen/self-driving-cars", "id": "d1cc53a4544d06f65a2d24992fbc0b1aa1628273", "size": "4941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "p3-behavioral-cloning/model.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "15335803" }, { "name": "Python", "bytes": "40511" } ], "symlink_target": "" }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal; import com.google.common.collect.ImmutableList; import com.intellij.execution.TaskExecutor; import com.intellij.execution.configuration.EnvironmentVariablesData; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessWaitFor; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PathMacroManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.terminal.JBTerminalWidget; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.execution.ParametersListUtil; import com.jediterm.pty.PtyProcessTtyConnector; import com.jediterm.terminal.TtyConnector; import com.pty4j.PtyProcess; import com.pty4j.PtyProcessBuilder; import com.pty4j.unix.UnixPtyProcess; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class LocalTerminalDirectRunner extends AbstractTerminalRunner<PtyProcess> { private static final Logger LOG = Logger.getInstance(LocalTerminalDirectRunner.class); private static final String JEDITERM_USER_RCFILE = "JEDITERM_USER_RCFILE"; private static final String ZDOTDIR = "ZDOTDIR"; private static final String XDG_CONFIG_HOME = "XDG_CONFIG_HOME"; private static final String IJ_COMMAND_HISTORY_FILE_ENV = "__INTELLIJ_COMMAND_HISTFILE__"; private static final String LOGIN_SHELL = "LOGIN_SHELL"; private static final String LOGIN_CLI_OPTION = "--login"; private static final ImmutableList<String> LOGIN_CLI_OPTIONS = ImmutableList.of(LOGIN_CLI_OPTION, "-l"); private static final String INTERACTIVE_CLI_OPTION = "-i"; private static final String BASH_NAME = "bash"; private static final String SH_NAME = "sh"; private static final String ZSH_NAME = "zsh"; private static final String FISH_NAME = "fish"; private final Charset myDefaultCharset; public LocalTerminalDirectRunner(Project project) { super(project); myDefaultCharset = StandardCharsets.UTF_8; } @Nullable private static String findRCFile(@NotNull String shellName) { String rcfile = null; if (BASH_NAME.equals(shellName) || SH_NAME.equals(shellName)) { rcfile = "jediterm-bash.in"; } else if (ZSH_NAME.equals(shellName)) { rcfile = ".zshenv"; } else if (FISH_NAME.equals(shellName)) { rcfile = "fish/config.fish"; } if (rcfile != null) { try { return findAbsolutePath(rcfile); } catch (Exception e) { LOG.warn("Unable to find " + rcfile + " configuration file", e); } } return null; } @NotNull private static String findAbsolutePath(@NotNull String relativePath) throws IOException { String jarPath = PathUtil.getJarPathForClass(LocalTerminalDirectRunner.class); final File result; if (jarPath.endsWith(".jar")) { File jarFile = new File(jarPath); if (!jarFile.isFile()) { throw new IOException("Broken installation: " + jarPath + " is not a file"); } File pluginBaseDir = jarFile.getParentFile().getParentFile(); result = new File(pluginBaseDir, relativePath); } else { Application application = ApplicationManager.getApplication(); if (application != null && application.isInternal()) { jarPath = StringUtil.trimEnd(jarPath.replace('\\', '/'), '/') + '/'; String srcDir = jarPath.replace("/out/classes/production/intellij.terminal/", "/community/plugins/terminal/resources/"); if (new File(srcDir).isDirectory()) { jarPath = srcDir; } } result = new File(jarPath, relativePath); } if (!result.isFile()) { throw new IOException("Cannot find " + relativePath + ": " + result.getAbsolutePath() + " is not a file"); } return result.getAbsolutePath(); } @NotNull public static LocalTerminalDirectRunner createTerminalRunner(Project project) { return new LocalTerminalDirectRunner(project); } private Map<String, String> getTerminalEnvironment() { Map<String, String> envs = SystemInfo.isWindows ? CollectionFactory.createCaseInsensitiveStringMap() : new HashMap<>(); EnvironmentVariablesData envData = TerminalProjectOptionsProvider.getInstance(myProject).getEnvData(); if (envData.isPassParentEnvs()) { envs.putAll(System.getenv()); } if (!SystemInfo.isWindows) { envs.put("TERM", "xterm-256color"); } envs.put("TERMINAL_EMULATOR", "JetBrains-JediTerm"); envs.put("TERM_SESSION_ID", UUID.randomUUID().toString()); if (SystemInfo.isMac) { EnvironmentUtil.setLocaleEnv(envs, myDefaultCharset); } PathMacroManager macroManager = PathMacroManager.getInstance(myProject); for (Map.Entry<String, String> env : envData.getEnvs().entrySet()) { envs.put(env.getKey(), macroManager.expandPath(env.getValue())); } return envs; } @Override public @NotNull PtyProcess createProcess(@NotNull TerminalProcessOptions options, @Nullable JBTerminalWidget widget) throws ExecutionException { Map<String, String> envs = getTerminalEnvironment(); String[] command = ArrayUtil.toStringArray(getInitialCommand(envs)); for (LocalTerminalCustomizer customizer : LocalTerminalCustomizer.EP_NAME.getExtensions()) { try { command = customizer.customizeCommandAndEnvironment(myProject, command, envs); } catch (Exception e) { LOG.error("Exception during customization of the terminal session", e); } } String commandHistoryFilePath = ShellTerminalWidget.getCommandHistoryFilePath(widget); if (commandHistoryFilePath != null) { envs.put(IJ_COMMAND_HISTORY_FILE_ENV, commandHistoryFilePath); } String workingDir = getWorkingDirectory(options.getWorkingDirectory()); TerminalUsageTriggerCollector.triggerLocalShellStarted(myProject, command); try { long startNano = System.nanoTime(); PtyProcessBuilder builder = new PtyProcessBuilder(command) .setEnvironment(envs) .setDirectory(workingDir) .setInitialColumns(options.getInitialColumns()) .setInitialRows(options.getInitialRows()); PtyProcess process = builder.start(); if (LOG.isDebugEnabled()) { LOG.debug("Started " + process.getClass().getName() + " from " + Arrays.toString(command) + " in " + workingDir + " [" + options.getInitialColumns() + "," + options.getInitialRows() + "]" + " (" + TimeoutUtil.getDurationMillis(startNano) + " ms)"); } return process; } catch (IOException e) { String errorMessage = "Failed to start " + Arrays.toString(command) + " in " + workingDir; if (workingDir != null && !new File(workingDir).isDirectory()) { errorMessage = "No such directory: " + workingDir; } throw new ExecutionException(errorMessage, e); } } @Nullable private String getWorkingDirectory(@Nullable String directory) { if (directory != null) return directory; return TerminalProjectOptionsProvider.getInstance(myProject).getStartingDirectory(); } @Override protected ProcessHandler createProcessHandler(final PtyProcess process) { return new PtyProcessHandler(process, getShellPath()); } @Override protected @NotNull TtyConnector createTtyConnector(@NotNull PtyProcess process) { return new PtyProcessTtyConnector(process, myDefaultCharset) { @Override public void close() { if (process instanceof UnixPtyProcess) { ((UnixPtyProcess)process).hangup(); AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> { if (process.isAlive()) { LOG.info("Terminal hasn't been terminated by SIGHUP, performing default termination"); process.destroy(); } }, 1000, TimeUnit.MILLISECONDS); } else { process.destroy(); } } @Override public void resize(@NotNull Dimension termWinSize) { if (LOG.isDebugEnabled()) { LOG.debug("resize to " + termWinSize); } super.resize(termWinSize); } }; } @Override public String runningTargetName() { return "Local Terminal"; } @Override protected String getTerminalConnectionName(PtyProcess process) { return "Local Terminal"; } /** * @param envs environment variables * @return initial command. The result command to execute is calculated by applying * {@link LocalTerminalCustomizer#customizeCommandAndEnvironment} to it. */ public @NotNull List<String> getInitialCommand(@NotNull Map<String, String> envs) { return getCommands(envs); } /** * @deprecated use {@link #getInitialCommand(Map)} instead */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated public @NotNull List<String> getCommands(@NotNull Map<String, String> envs) { return Arrays.asList(getCommand(envs)); } /** * @deprecated use {@link #getInitialCommand(Map)} instead */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") public String[] getCommand(Map<String, String> envs) { String shellPath = getShellPath(); return ArrayUtil.toStringArray(getCommand(shellPath, envs, TerminalOptionsProvider.getInstance().shellIntegration())); } private @NotNull String getShellPath() { return TerminalProjectOptionsProvider.getInstance(myProject).getShellPath(); } public static @NotNull List<String> getCommand(@NotNull String shellPath, @NotNull Map<String, String> envs, boolean shellIntegration) { if (SystemInfo.isWindows) { return ParametersListUtil.parse(shellPath, false, false); } List<String> command = ParametersListUtil.parse(shellPath, false, true); String shellCommand = ContainerUtil.getFirstItem(command); if (shellCommand == null) { return command; } command.remove(0); String shellName = PathUtil.getFileName(shellCommand); if (!containsLoginOrInteractiveOption(command)) { if (isLoginOptionAvailable(shellName) && SystemInfo.isMac) { command.add(LOGIN_CLI_OPTION); } if (isInteractiveOptionAvailable(shellName)) { command.add(INTERACTIVE_CLI_OPTION); } } List<String> result = new ArrayList<>(); result.add(shellCommand); String rcFilePath = shellIntegration ? findRCFile(shellName) : null; if (rcFilePath != null) { if (shellName.equals(BASH_NAME) || (SystemInfo.isMac && shellName.equals(SH_NAME))) { addRcFileArgument(envs, command, result, rcFilePath, "--rcfile"); // remove --login to enable --rcfile sourcing boolean loginShell = command.removeAll(LOGIN_CLI_OPTIONS); setLoginShellEnv(envs, loginShell); } else if (shellName.equals(ZSH_NAME)) { String zdotdir = envs.get(ZDOTDIR); if (StringUtil.isNotEmpty(zdotdir)) { envs.put("_INTELLIJ_ORIGINAL_ZDOTDIR", zdotdir); } envs.put(ZDOTDIR, PathUtil.getParentPath(rcFilePath)); } else if (shellName.equals(FISH_NAME)) { String xdgConfig = EnvironmentUtil.getEnvironmentMap().get(XDG_CONFIG_HOME); if (StringUtil.isNotEmpty(xdgConfig)) { File fishConfig = new File(new File(FileUtil.expandUserHome(xdgConfig), "fish"), "config.fish"); if (fishConfig.exists()) { envs.put(JEDITERM_USER_RCFILE, fishConfig.getAbsolutePath()); } envs.put("OLD_" + XDG_CONFIG_HOME, xdgConfig); } envs.put(XDG_CONFIG_HOME, new File(rcFilePath).getParentFile().getParent()); } setLoginShellEnv(envs, isLogin(command)); } result.addAll(command); return result; } private static boolean isLoginOptionAvailable(@NotNull String shellName) { return isBashZshFish(shellName); } private static boolean isInteractiveOptionAvailable(@NotNull String shellName) { return isBashZshFish(shellName); } private static boolean isBashZshFish(@NotNull String shellName) { return shellName.equals(BASH_NAME) || (SystemInfo.isMac && shellName.equals(SH_NAME)) || shellName.equals(ZSH_NAME) || shellName.equals(FISH_NAME); } private static void setLoginShellEnv(@NotNull Map<String, String> envs, boolean loginShell) { if (loginShell) { envs.put(LOGIN_SHELL, "1"); } } private static void addRcFileArgument(Map<String, String> envs, List<String> command, List<String> result, String rcFilePath, String rcfileOption) { result.add(rcfileOption); result.add(rcFilePath); int idx = command.indexOf(rcfileOption); if (idx >= 0) { command.remove(idx); if (idx < command.size()) { envs.put(JEDITERM_USER_RCFILE, FileUtil.expandUserHome(command.get(idx))); command.remove(idx); } } } private static boolean containsLoginOrInteractiveOption(List<String> command) { return isLogin(command) || command.contains(INTERACTIVE_CLI_OPTION); } private static boolean isLogin(@NotNull List<String> command) { return command.stream().anyMatch(LOGIN_CLI_OPTIONS::contains); } private static class PtyProcessHandler extends ProcessHandler implements TaskExecutor { private final PtyProcess myProcess; private final ProcessWaitFor myWaitFor; PtyProcessHandler(PtyProcess process, @NotNull String presentableName) { myProcess = process; myWaitFor = new ProcessWaitFor(process, this, presentableName); } @Override public void startNotify() { addProcessListener(new ProcessAdapter() { @Override public void startNotified(@NotNull ProcessEvent event) { try { myWaitFor.setTerminationCallback(integer -> notifyProcessTerminated(integer)); } finally { removeProcessListener(this); } } }); super.startNotify(); } @Override protected void destroyProcessImpl() { myProcess.destroy(); } @Override protected void detachProcessImpl() { destroyProcessImpl(); } @Override public boolean detachIsDefault() { return false; } @Override public boolean isSilentlyDestroyOnClose() { return true; } @Nullable @Override public OutputStream getProcessInput() { return myProcess.getOutputStream(); } @NotNull @Override public Future<?> executeTask(@NotNull Runnable task) { return AppExecutorUtil.getAppExecutorService().submit(task); } } }
{ "content_hash": "e2bf9122a8c0926533a679a4a41d675f", "timestamp": "", "source": "github", "line_count": 442, "max_line_length": 140, "avg_line_length": 35.93891402714932, "alnum_prop": 0.6828454516839786, "repo_name": "allotria/intellij-community", "id": "7979123c3ecfc1ee19c0bf5a75f4a9de59515336", "size": "15885", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "60580" }, { "name": "C", "bytes": "195249" }, { "name": "C#", "bytes": "1264" }, { "name": "C++", "bytes": "195810" }, { "name": "CMake", "bytes": "1675" }, { "name": "CSS", "bytes": "201445" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "3197810" }, { "name": "HLSL", "bytes": "57" }, { "name": "HTML", "bytes": "1891055" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "164463076" }, { "name": "JavaScript", "bytes": "570364" }, { "name": "Jupyter Notebook", "bytes": "93222" }, { "name": "Kotlin", "bytes": "4240307" }, { "name": "Lex", "bytes": "147047" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "51270" }, { "name": "Objective-C", "bytes": "27941" }, { "name": "Perl", "bytes": "903" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6680" }, { "name": "Python", "bytes": "25385564" }, { "name": "Roff", "bytes": "37534" }, { "name": "Ruby", "bytes": "1217" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "65705" }, { "name": "Smalltalk", "bytes": "338" }, { "name": "TeX", "bytes": "25473" }, { "name": "Thrift", "bytes": "1846" }, { "name": "TypeScript", "bytes": "9469" }, { "name": "Visual Basic", "bytes": "77" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
This is a PoC of an OpenFlow 1.0 controller I wrote in 2014 as part of my concluding project for Bachelor of Science in Computer Science. ## Quick Start $ ./bootstrap.sh $ ./run.sh
{ "content_hash": "c4b470186858f5581d5d009ac183e1b3", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 70, "avg_line_length": 27.285714285714285, "alnum_prop": 0.7120418848167539, "repo_name": "renatoaguiar/ljof", "id": "67838893f0a5e9dc99da472f3d8a3d5131460455", "size": "229", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "19744" }, { "name": "Shell", "bytes": "332" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "84d5f9498535610e2210fa314258b18d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "5e7a31287749bb2d1a20cdf45227e80185a545f2", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Ranunculaceae/Ranunculus/Ranunculus chuanchingensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
"use strict"; module.exports = function( Promise, Promise$_CreatePromiseArray, PromiseArray, apiRejection, INTERNAL) { var ASSERT = require("./assert.js"); function Reduction(callback, index, accum, items, receiver) { this.promise = new Promise(INTERNAL); this.index = index; this.length = items.length; this.items = items; this.callback = callback; this.receiver = receiver; this.accum = accum; } Reduction.prototype.reject = function Reduction$reject(e) { this.promise._reject(e); }; Reduction.prototype.fulfill = function Reduction$fulfill(value, index) { this.accum = value; this.index = index + 1; this.iterate(); }; Reduction.prototype.iterate = function Reduction$iterate() { var i = this.index; var len = this.length; var items = this.items; var result = this.accum; var receiver = this.receiver; var callback = this.callback; var iterate = this.iterate; for(; i < len; ++i) { result = Promise._cast( callback.call( receiver, result, items[i], i, len ), iterate, void 0 ); if (result instanceof Promise) { result._then( this.fulfill, this.reject, void 0, this, i, iterate); return; } } this.promise._fulfill(result); }; function Promise$_reducer(fulfilleds, initialValue) { var fn = this; var receiver = void 0; if (typeof fn !== "function") { receiver = fn.receiver; fn = fn.fn; } var len = fulfilleds.length; var accum = void 0; var startIndex = 0; if (initialValue !== void 0) { accum = initialValue; startIndex = 0; } else { startIndex = 1; if (len > 0) accum = fulfilleds[0]; } var i = startIndex; if (i >= len) { return accum; } var reduction = new Reduction(fn, i, accum, fulfilleds, receiver); reduction.iterate(); return reduction.promise; } function Promise$_unpackReducer(fulfilleds) { var fn = this.fn; var initialValue = this.initialValue; return Promise$_reducer.call(fn, fulfilleds, initialValue); } function Promise$_slowReduce( promises, fn, initialValue, useBound, caller) { return initialValue._then(function callee(initialValue) { return Promise$_Reduce( promises, fn, initialValue, useBound, callee); }, void 0, void 0, void 0, void 0, caller); } function Promise$_Reduce(promises, fn, initialValue, useBound, caller) { if (typeof fn !== "function") { return apiRejection("fn must be a function"); } if (useBound === true && promises._isBound()) { fn = { fn: fn, receiver: promises._boundTo }; } if (initialValue !== void 0) { if (Promise.is(initialValue)) { if (initialValue.isFulfilled()) { initialValue = initialValue._settledValue; } else { return Promise$_slowReduce(promises, fn, initialValue, useBound, caller); } } return Promise$_CreatePromiseArray(promises, PromiseArray, caller, useBound === true && promises._isBound() ? promises._boundTo : void 0) .promise() ._then(Promise$_unpackReducer, void 0, void 0, { fn: fn, initialValue: initialValue }, void 0, Promise.reduce); } return Promise$_CreatePromiseArray(promises, PromiseArray, caller, useBound === true && promises._isBound() ? promises._boundTo : void 0).promise() ._then(Promise$_reducer, void 0, void 0, fn, void 0, caller); } Promise.reduce = function Promise$Reduce(promises, fn, initialValue) { return Promise$_Reduce(promises, fn, initialValue, false, Promise.reduce); }; Promise.prototype.reduce = function Promise$reduce(fn, initialValue) { return Promise$_Reduce(this, fn, initialValue, true, this.reduce); }; };
{ "content_hash": "4a70430f24f5cceae65c4be2cb10e237", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 78, "avg_line_length": 30.662337662337663, "alnum_prop": 0.5082592121982211, "repo_name": "viniborges/designizando", "id": "704a55ed02c00faf7ed9b2d8e0cbdde44fddc7e0", "size": "5848", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/knex/node_modules/bluebird/js/zalgo/reduce.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "215111" }, { "name": "JavaScript", "bytes": "4008078" } ], "symlink_target": "" }
num = input('Enter a number: ') print num if num > 0: print 'The number is positive' elif num<0: print 'The number is negative' else: print 'The number is zero'
{ "content_hash": "0649a5134e491272910ba61e7356c8ab", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 34, "avg_line_length": 19.333333333333332, "alnum_prop": 0.6551724137931034, "repo_name": "MarsBighead/mustang", "id": "7fd425f23a0f89b194ca52a02b8085db55106e59", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/elif.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "622" }, { "name": "C++", "bytes": "15533" }, { "name": "CSS", "bytes": "2525" }, { "name": "Dockerfile", "bytes": "499" }, { "name": "Erlang", "bytes": "5855" }, { "name": "Go", "bytes": "3879" }, { "name": "HTML", "bytes": "3879" }, { "name": "Java", "bytes": "541" }, { "name": "JavaScript", "bytes": "7858" }, { "name": "Julia", "bytes": "2223" }, { "name": "Makefile", "bytes": "650" }, { "name": "Modula-3", "bytes": "43" }, { "name": "PHP", "bytes": "771" }, { "name": "PLpgSQL", "bytes": "4642" }, { "name": "Perl", "bytes": "46253" }, { "name": "Python", "bytes": "110755" }, { "name": "Raku", "bytes": "378" }, { "name": "Shell", "bytes": "22680" } ], "symlink_target": "" }
import copy import itertools import logging import pymel.core as pymel from collections import defaultdict from omtk.core.utils import decorator_uiexpose from omtk.libs import libCtrlShapes from omtk.libs import libPymel from omtk.libs import libPython from omtk.libs import libRigging from omtk.libs.libRigging import get_average_pos_between_nodes from omtk.models import model_ctrl_linear, model_avar_linear from omtk.modules import rigFaceAvar log = logging.getLogger('omtk') def _find_mid_avar(avars): jnts = [avar.jnt for avar in avars] nearest_jnt = get_average_pos_between_nodes(jnts) return avars[jnts.index(nearest_jnt)] if nearest_jnt else None # # Ctrls # class BaseCtrlUpp(rigFaceAvar.BaseCtrlFace): """ Deprecated, defined for backward compatibility (so libSerialization recognize it and we can access the ctrl shapes) """ pass class BaseCtrlLow(rigFaceAvar.BaseCtrlFace): """ Deprecated, defined for backward compatibility (so libSerialization recognize it and we can access the ctrl shapes) """ pass class CtrlFaceUpp(rigFaceAvar.BaseCtrlFace): """ Base controller class for an avar controlling the top portion of an AvarGrp. """ def __createNode__(self, size=1.0, **kwargs): return libCtrlShapes.create_triangle_upp(size=size) class CtrlFaceLow(rigFaceAvar.BaseCtrlFace): """ Base controller class for an avar controlling the bottom portion of an AvarGrp. """ def __createNode__(self, size=1.0, **kwargs): return libCtrlShapes.create_triangle_low(size=size) class CtrlFaceAll(rigFaceAvar.BaseCtrlFace): ATTR_NAME_GLOBAL_SCALE = 'globalScale' """ Base controller class for an avar controlling all the avars of an AvarGrp. """ def __createNode__(self, size=1.0, **kwargs): # todo: find the best shape transform, _ = libCtrlShapes.create_shape_circle(size=size, normal=(0, 0, 1)) return transform class CtrlFaceHorizontal(rigFaceAvar.BaseCtrlFace): """ Base controller class for an avar controlling the left or right porsion of an AvarGrp. """ def __createNode__(self, size=1.0, **kwargs): return libCtrlShapes.create_triangle_left(size=size) class CtrlFaceMacroL(rigFaceAvar.BaseCtrlFace): def __createNode__(self, size=1.0, **kwargs): return libCtrlShapes.create_triangle_left(size=size) class CtrlFaceMacroR(rigFaceAvar.BaseCtrlFace): def __createNode__(self, size=1.0, **kwargs): return libCtrlShapes.create_triangle_right(size=size) # # Models # class ModelMicroAvarCtrl(model_ctrl_linear.ModelCtrlLinear): def connect(self, avar, avar_grp, ud=True, fb=True, lr=True, yw=True, pt=True, rl=True, sx=True, sy=True, sz=True): avar_tweak = avar_grp._get_micro_tweak_avars_dict().get(avar, None) if avar_tweak: super(ModelMicroAvarCtrl, self).connect(avar, avar_grp, ud=ud, fb=fb, lr=lr, yw=False, pt=False, rl=False, sx=False, sy=False, sz=False) super(ModelMicroAvarCtrl, self).connect(avar_tweak, avar_grp, ud=False, fb=False, lr=False, yw=yw, pt=pt, rl=rl, sx=sx, sy=sy, sz=sz) else: super(ModelMicroAvarCtrl, self).connect(avar, avar_grp, ud=ud, fb=fb, lr=lr, yw=yw, pt=pt, rl=rl, sx=sx, sy=sy, sz=sz) class ModelCtrlMacroAll(model_ctrl_linear.ModelCtrlLinear): def connect(self, avar, avar_grp, ud=True, fb=True, lr=True, yw=True, pt=True, rl=True, sx=True, sy=True, sz=True): super(ModelCtrlMacroAll, self).connect(avar, avar_grp, ud=True, fb=True, lr=True, yw=True, pt=True, rl=True, sx=True, sy=True, sz=True) # # # # Compute the calibration automatically # # # # nomenclature_rig = self.get_nomenclature_rig() # # # Compute the calibration automatically # attr_calibration_lr = libRigging.create_utility_node( # 'multiplyDivide', # name=nomenclature_rig.resolve('getCalibrationLr'), # input1X=avar.attr_multiplier_lr, # input2X=avar._attr_length_u # ).outputX # attr_calibration_ud = libRigging.create_utility_node( # 'multiplyDivide', # name=nomenclature_rig.resolve('getCalibrationUd'), # input1X=avar.attr_multiplier_ud, # input2X=avar._attr_length_v # ).outputX # attr_calibration_fb = libRigging.create_utility_node( # 'multiplyDivide', # name=nomenclature_rig.resolve('getCalibrationFb'), # input1X=avar.attr_multiplier_fb, # input2X=avar._attr_length_u # ).outputX # # pymel.connectAttr(attr_calibration_lr, self.attr_sensitivity_tx) # pymel.connectAttr(attr_calibration_ud, self.attr_sensitivity_ty) # pymel.connectAttr(attr_calibration_fb, self.attr_sensitivity_tz) def build(self, avar, parent_pos=None, parent_rot=None, **kwargs): parent_pos = avar._grp_output # parent_rot = avar._grp_output super(ModelCtrlMacroAll, self).build( avar, parent_pos=parent_pos, parent_rot=parent_rot, **kwargs) def calibrate(self, **kwargs): """ Since the avar_all macro follow directly the surface, we don't need to calibrate it. """ pass # # Models # class AvarGrp( rigFaceAvar.AbstractAvar): # todo: why do we inherit from AbstractAvar exactly? Is inheriting from module more logical? """ Base class for a group of 'avars' that share the same properties. """ # Define the class to use for all avars. _CLS_AVAR = rigFaceAvar.AvarSimple _CLS_CTRL_MICRO = rigFaceAvar.CtrlFaceMicro _CLS_CTRL_TWEAK = None # In our case we hide the tweak avars by default since they are controlled using their parent controller. _CLS_MODEL_CTRL_MICRO = ModelMicroAvarCtrl _CLS_MODEL_CTRL_TWEAK = None SHOW_IN_UI = True # Enable this flag if the module contain only one influence. # ex: The FaceJaw module can accept two objects. The jaw and the jaw_end. However we consider the jaw_end as extra information for the positioning. # TODO: Find a generic way to get the InteractiveCtrl follicle position. SINGLE_INFLUENCE = False # Set this flag to false if each avars need to have an individual parent. # Please note that this have not been tested when used with 'tweak' avars. # This flag have been added to diminish the chances of breaking something in production (see Task #70413), # however we should check if it is possible to always have this behavior by default. # todo: Find a generic way. SINGLE_PARENT = True def __init__(self, *args, **kwargs): super(AvarGrp, self).__init__(*args, **kwargs) # This property contain all the MICRO Avars. # Micro Avars directly drive the input influence of the Module. # Macro Avars indirectly drive nothing by themself but are generally connected to Micro Avars. # It is really important that if you implement Macro Avars in other properties than this one. self.avars = [] self.preDeform = False self._grp_anm_avars_macro = None self._grp_anm_avars_micro = None self._grp_rig_avars_macro = None self._grp_rig_avars_micro = None # # Avar properties # Note that theses are only accessible after the avars have been built. # def _iter_all_avars(self): """ Generator that return all avars, macro and micros. Override this method if your module implement new avars. :return: An iterator that yield avars. """ for avar in self.avars: yield avar def get_all_avars(self): """ :return: All macro and micro avars of the module. This is mainly used to automate the handling of avars and remove the need to abuse class inheritance. """ return list(self._iter_all_avars()) def get_avars_upp(self): """ :return: All the upper section avars (micro and macros). """ return self.get_avars_micro_upp() @libPython.memoized_instancemethod def get_avars_micro_upp(self): """ Return all the avars controlling the AvarGrp upper area. ex: For lips, this will return the upper lip influences (without any corners). :return: A list of Avar instances. """ # TODO: Find a better way fnFilter = lambda avar: 'upp' in avar.name.lower() return filter(fnFilter, self.avars) def get_avars_low(self): """ :return: All the lower section avars (micro and macros). """ return self.get_avars_micro_low() @libPython.memoized_instancemethod def get_avars_micro_low(self): """ Return all the avars controlling the AvarGrp lower area. ex: For the lips, this will return the lower lip influences (without any corners). :return: Al list of Avar instrances. """ # TODO: Find a better way fnFilter = lambda avar: 'low' in avar.name.lower() return filter(fnFilter, self.avars) # # Influence properties # @libPython.cached_property() def jnts(self): fn_is_nurbsSurface = lambda obj: libPymel.isinstance_of_transform(obj, pymel.nodetypes.Joint) return filter(fn_is_nurbsSurface, self.input) @libPython.memoized_instancemethod def _get_absolute_parent_level_by_influences(self): result = defaultdict(list) for jnt in self.jnts: level = libPymel.get_num_parents(jnt) result[level].append(jnt) return dict(result) # todo: implement Tree datatype def _get_highest_absolute_parent_level(self): return min(self._get_absolute_parent_level_by_influences().keys()) def _get_hierarchy_depth(self): return max(self._get_relative_parent_level_by_influences().keys()) def _can_create_tweak_avars(self): # If the hierarchy depth is of only 1, the avar_all have priority. # This is because there's a potential for ambiguity between the all_avar and tweak avars. lowest_relative_parent_level = self._get_hierarchy_depth() if lowest_relative_parent_level == 1 and self.get_influence_all(): return False return True @libPython.memoized_instancemethod def _get_relative_parent_level_by_influences(self): result = defaultdict(list) objs_by_absolute_parent_level = self._get_absolute_parent_level_by_influences() top_level = self._get_highest_absolute_parent_level() for parent_level, objs in objs_by_absolute_parent_level.iteritems(): result[parent_level - top_level] = objs return dict(result) @libPython.memoized_instancemethod def get_influence_all(self): """ If the rigger provided a global parent for the influences in the module, it will be considered as an influence for the 'all' macro avar. """ # If there's only one influence, we'll handle it as a simple avar. if len(self.jnts) <= 1: return None objs_by_absolute_parent_level = self._get_absolute_parent_level_by_influences() top_level = self._get_highest_absolute_parent_level() root_objs = objs_by_absolute_parent_level[top_level] if len(root_objs) == 1: return root_objs[0] return None @libPython.memoized_instancemethod def get_influence_micros(self): """ :return: Only the influence used in micro avars. """ result = set() for avar in self.avars: if self._is_tweak_avar(avar): continue result.update(avar.jnts) return list(result) @libPython.memoized_instancemethod def _get_micro_avar_by_influence(self, influence): for avar in self.avars: if influence in avar.input: return avar @libPython.memoized_instancemethod def _get_micro_tweak_avars_dict(self): result = {} influences_by_parent_level = self._get_relative_parent_level_by_influences() top_level = self._get_hierarchy_depth() for influence in influences_by_parent_level[top_level]: parent_influence = influence.getParent() avar = self._get_micro_avar_by_influence(influence) avar_parent = self._get_micro_avar_by_influence(parent_influence) if avar and avar_parent: result[avar_parent] = avar return result def _is_tweak_avar(self, avar): return avar in self._get_micro_tweak_avars_dict().values() # # Avar methods # def get_multiplier_u(self): return 1.0 def get_multiplier_v(self): return 1.0 def _get_default_ctrl_size(self, jnts=None, max_ctrl_size=None, epsilon=0.001): """ Resolve the desired ctrl size One thing we are sure is that ctrls should not overlay, so we'll max out their radius to half of the shortest distances between each. Also the radius cannot be bigger than 3% of the head length. :param epsilon: Prevent ctrl from dissapearing if two influences share the same location """ result = 1 # Resolve maximum ctrl size from head joint head_jnt = self.get_head_jnt() try: head_length = self.rig.get_head_length(head_jnt) except Exception, e: head_length = None self.warning(str(e)) if head_length: max_ctrl_size = head_length * 0.05 if jnts is None: # Use only the micro influence as reference since the distance # between micro and tweak avars can be very small. jnts = self.get_influence_micros() if len(jnts) > 1: distances = [libPymel.distance_between_nodes(jnt_src, jnt_dst) for jnt_src, jnt_dst in itertools.permutations(jnts, 2)] distances = filter(lambda x: x > epsilon, distances) if distances: result = min(distances) / 2.0 if max_ctrl_size is not None and result > max_ctrl_size: self.debug("Limiting ctrl size to {}".format(max_ctrl_size)) result = max_ctrl_size else: self.debug("Not enough ctrls to guess size. Using default {}".format(result)) return result def _get_avars_influences(self): """ Return the influences that need to have avars associated with. Normally for 3 influences, we create 3 avars. However if the SINGLE_INFLUENCE flag is up, only the first influence will be rigged, the others mights be handled upstream. (ex: FaceJaw). """ if self.SINGLE_INFLUENCE: return [self.jnt] else: return copy.copy(self.jnts) # copy to prevent modifying the cache accidentaly by reference. def validate(self): """ Ensure all influences are influencing a geometry. This allow us to prevent the user to find out when building. """ super(AvarGrp, self).validate() # Try to resolve the head joint. # With strict=True, an exception will be raised if nothing is found. if self.get_head_jnt(strict=False) is None: raise Exception("Can't resolve the head. Please create a Head module.") def _create_micro_avars(self): """ For each influence, create it's associated avar instance. """ # For various reason, we may have a mismatch between the stored Avars the number of influences. # The best way to deal with this is to check each existing Avar and see if we need to created it or keep it. avar_influences = self._get_avars_influences() if not avar_influences: raise Exception("Found no avars!") new_avars = [] for avar in self.avars: # Any existing Avar that we don't reconize will be deleted. # Be aware that the .avars property only store MICRO Avars. Macro Avars need to be implemented in their own properties. if avar.jnt not in avar_influences: self.warning("Unexpected Avar {0} will be deleted.".format(avar.name)) # Any existing Avar that don't have the desired datatype will be re-created. # However the old value will be passed by so the factory method can handle specific tricky cases. else: new_avar = self._init_avar( self._CLS_AVAR, avar, ref=avar.jnt ) new_avars.append(new_avar) for influence in avar_influences: if not any(True for avar in new_avars if influence == avar.jnt): new_avar = self._init_avar( self._CLS_AVAR, None, # no previous value ref=influence ) new_avars.append(new_avar) return new_avars def _create_avars(self): """ Create the avars objects if they were never created (generally on first build). """ # Create avars if needed (this will get skipped if the module have already been built once) self.avars = self._create_micro_avars() def _build_avars(self, parent=None, connect_global_scale=None, create_ctrls=True, constraint=True, **kwargs): if parent is None: parent = not self.preDeform if connect_global_scale is None: connect_global_scale = self.preDeform # Resolve the U and V modifiers. # Note that this only applies to avars on a surface. # TODO: Move to AvarGrpOnSurface mult_u = self.get_multiplier_u() if self.surface else None mult_v = self.get_multiplier_v() if self.surface else None # Build avars and connect them to global avars avar_influences = self._get_avars_influences() for jnt, avar in zip(avar_influences, self.avars): self.configure_avar(avar) self._build_avar_micro(avar, create_ctrl=create_ctrls, constraint=constraint, mult_u=mult_u, mult_v=mult_v, connect_global_scale=connect_global_scale, **kwargs ) # Connect 'tweak' avars to their equivalent. for avar_micro, avar_tweak in self._get_micro_tweak_avars_dict().iteritems(): libRigging.connectAttr_withBlendWeighted(avar_micro.attr_lr, avar_tweak.attr_lr) libRigging.connectAttr_withBlendWeighted(avar_micro.attr_ud, avar_tweak.attr_ud) libRigging.connectAttr_withBlendWeighted(avar_micro.attr_fb, avar_tweak.attr_fb) def _build_avar(self, avar, **kwargs): # HACK: Validate avars at runtime try: avar.validate() except Exception, e: self.warning("Can't build avar {0}, failed validation: {1}".format( avar.name, e )) return None avar.build(**kwargs) def _build_avar_micro(self, avar, **kwargs): self._build_avar(avar, **kwargs) if libPymel.is_valid_PyNode(avar.grp_anm): if self._grp_anm_avars_micro: avar.grp_anm.setParent(self._grp_anm_avars_micro) else: avar.grp_anm.setParent(self.grp_anm) if libPymel.is_valid_PyNode(avar.grp_rig): if self._grp_rig_avars_micro: avar.grp_rig.setParent(self._grp_rig_avars_micro) else: avar.grp_rig.setParent(self.grp_rig) # todo: raise warning? def _build_avar_macro(self, cls_ctrl, avar, constraint=False, **kwargs): """ Factory method that create an avar that is not affiliated with any influence and is only used for connections. :param cls_ctrl: The class definition to use for the ctrl. :param avar: The Avar class instance to use. :param constraint: By default, a macro Avar don't affect it's influence (directly). This is False by default. :param kwargs: Any additional keyword arguments will be sent to the avar build method. :return: """ if cls_ctrl: avar._CLS_CTRL = cls_ctrl # Hack, find a more elegant way. self._build_avar(avar, constraint=constraint, **kwargs ) if libPymel.is_valid_PyNode(avar.grp_anm): if self._grp_anm_avars_macro: avar.grp_anm.setParent(self._grp_anm_avars_macro) else: avar.grp_anm.setParent(self.grp_anm) if libPymel.is_valid_PyNode(avar.grp_rig): if self._grp_rig_avars_macro: avar.grp_rig.setParent(self._grp_rig_avars_macro) else: avar.grp_rig.setParent(self.grp_rig) # todo: raise warning? return avar def _get_parent_adjustment_tm(self, avar): """ Return an attribute containing the additional contribution on the parent matrix. """ if not self.avar_all or self._is_tweak_avar(avar): return attr_avar_all_stack_result_tm = self.avar_all._stack.node.worldMatrix return libRigging.create_utility_node( 'multMatrix', matrixIn=( self.avar_all.grp_offset.inverseMatrix, # enter avar_all space attr_avar_all_stack_result_tm, # apply avar_all contribution self.avar_all.grp_offset.matrix, # exit avar_all space ) ).matrixSum def _parent_avar(self, avar, parent_tm): """ Connect the 'parent' group. This allow the avar resulting transform to be affected by something (ex: Head_Jnt). :param avar: :param parent_tm: :return: """ if avar.model_infl: libRigging.connect_matrix_to_node(parent_tm, avar._grp_parent) # avar.model_infl.connect_parent(parent_tm) if avar.model_ctrl: pymel.connectAttr(parent_tm, avar.model_ctrl._attr_inn_parent_tm) # pymel.connectAttr(u.outputTranslate, avar._grp_parent.translate) # pymel.connectAttr(u.outputRotate, avar._grp_parent.rotate) # pymel.connectAttr(u.outputScale, avar._grp_parent.scale) def _get_parent_identity_tm(self, parent): print(parent) # So correctly support non-uniform scaling, we need to rely on something more than scaleConstraint. # For this reason we'll need to store ourself the bindpose of our parent. grp_parent_bind = pymel.createNode( 'transform', name=(parent.name() + '_BindPose') ) grp_parent_bind.setParent(self.grp_rig) grp_parent_bind.setMatrix(parent.getMatrix(worldSpace=True)) attr_get_parent_tm = libRigging.create_utility_node( 'multMatrix', matrixIn=( grp_parent_bind.worldInverseMatrix, parent.worldMatrix, ), ).matrixSum return attr_get_parent_tm def _parent_avars(self): """ Parent each avars to their associated parent. :return: """ # If the deformation order is set to post (aka the deformer is in the final skinCluster) # we will want the offset node to follow it's original parent (ex: the head) nomenclature_rig = self.get_nomenclature_rig() attr_parent_tm_by_parent = {} for avar in self.get_all_avars(): avar_parent = None if self.SINGLE_PARENT: if avar.jnt: avar_parent = avar.jnt.getParent() else: # If we asked for a single parent for each avar but encounter an avar that don't have any influences, fallback to the module parent. avar_parent = self.parent else: avar_parent = self.parent # Hack: If the parent is the 'all' influence, we want to skip it since the 'all' influence is used in the stack. # Otherwise this will result in double-transformation. all_influence = self.get_influence_all() if avar_parent and avar_parent == all_influence: avar_parent = avar_parent.getParent() if avar_parent: attr_parent_tm = attr_parent_tm_by_parent.get(avar_parent) if not attr_parent_tm: attr_parent_tm = attr_parent_tm_by_parent[avar_parent] = self._get_parent_identity_tm(avar_parent) self._parent_avar(avar, attr_parent_tm) def _create_avars_ctrls(self, connect=False, **kwargs): for avar in self.avars: if self._is_tweak_avar(avar): if self._CLS_CTRL_TWEAK: avar._CLS_MODEL_CTRL = self._CLS_MODEL_CTRL_TWEAK avar._CLS_CTRL = self._CLS_CTRL_TWEAK avar.create_ctrl(self, **kwargs) else: if self._CLS_CTRL_MICRO: avar._CLS_MODEL_CTRL = self._CLS_MODEL_CTRL_MICRO avar._CLS_CTRL = self._CLS_CTRL_MICRO avar.create_ctrl(self, **kwargs) def handle_surface(self): """ Create the surface that the follicle will slide on if necessary. :return: """ # Hack: Provide backward compatibility for when surface was provided as an input. if not libPymel.isinstance_of_shape(self.surface, pymel.nodetypes.NurbsSurface): fn_is_nurbsSurface = lambda obj: libPymel.isinstance_of_shape(obj, pymel.nodetypes.NurbsSurface) surface = next(iter(filter(fn_is_nurbsSurface, self.input)), None) if surface: self.input.remove(surface) self.surface = surface return True # Create surface if it doesn't exist. self.warning("Can't find surface for {0}, creating one...".format(self)) self.surface = self.create_surface() def build(self, connect_global_scale=None, create_ctrls=True, parent=True, constraint=True, create_grp_rig_macro=True, create_grp_rig_micro=True, create_grp_anm_macro=True, create_grp_anm_micro=True, calibrate=True, **kwargs): self.handle_surface() super(AvarGrp, self).build(connect_global_scale=connect_global_scale, parent=parent, **kwargs) # We group the avars in 'micro' and 'macro' groups to make it easier for the animator to differentiate them. nomenclature_anm = self.get_nomenclature_anm_grp() if create_grp_anm_macro: name_grp_macro = nomenclature_anm.resolve('macro') self._grp_anm_avars_macro = pymel.createNode('transform', name=name_grp_macro) self._grp_anm_avars_macro.setParent(self.grp_anm) if create_grp_anm_micro: name_grp_micro = nomenclature_anm.resolve('micro') self._grp_anm_avars_micro = pymel.createNode('transform', name=name_grp_micro) self._grp_anm_avars_micro.setParent(self.grp_anm) # We group the avars in 'micro' and 'macro' groups to make it easier for the rigger to differentiate them. nomenclature_rig = self.get_nomenclature_rig_grp() if create_grp_rig_macro: name_grp_macro = nomenclature_rig.resolve('macro') self._grp_rig_avars_macro = pymel.createNode('transform', name=name_grp_macro) self._grp_rig_avars_macro.setParent(self.grp_rig) if create_grp_rig_micro: name_grp_micro = nomenclature_rig.resolve('micro') self._grp_rig_avars_micro = pymel.createNode('transform', name=name_grp_micro) self._grp_rig_avars_micro.setParent(self.grp_rig) self._create_avars() self._build_avars(parent=parent, connect_global_scale=connect_global_scale, constraint=constraint) if create_ctrls: ctrl_size = self._get_default_ctrl_size() self._create_avars_ctrls(ctrl_size=ctrl_size) if parent: self._parent_avars() if calibrate: self.calibrate() def unbuild(self): for avar in self.avars: avar.unbuild() super(AvarGrp, self).unbuild() def iter_ctrls(self): for ctrl in super(AvarGrp, self).iter_ctrls(): yield ctrl for avar in self._iter_all_avars(): for ctrl in avar.iter_ctrls(): yield ctrl @decorator_uiexpose() def calibrate(self): for avar in self.avars: if not self._is_tweak_avar(avar): # tweak avar have no ctrl and should not be calibrated avar.calibrate() def _init_avar(self, cls, inst, ref=None, cls_ctrl=None, cls_ctrl_model=None, cls_infl_model=None, name=None, suffix=None): """ Factory method that initialize an avar instance only if necessary. If the instance already had been initialized in a previous build, it's correct value will be preserved, This also handle the following checks - Preserve ctrl information if we need to re-created the avar because of a type mismatch. - Ensure that the avar always have a surface. # todo: implement this only on AvarGrpOnSurface. :param cls: The desired class. :param inst: The current value. This should always exist since defined in the module constructor. :param ref: :param cls_ctrl: The desired ctrl class. We might want to remove this for simplicity :param cls_ctrl_model: The desired controller model class. :param cls_infl_model: The desired influence model class. :return: The initialized instance. If the instance was already fine, it is returned as is. """ # Hack: Ensure ref is a list. # todo: fix upstream result_inputs = [ref] if ref else [] result_inputs.extend(self.get_meshes()) # ensure avars propage the mesh to their AvarCtrlModel # todo: remove this call when we know it is safe. if cls is None: self.warning("No avar class specified for {0}, using default.".format(self)) cls = rigFaceAvar.AvarSimple result = self.init_module(cls, inst, inputs=result_inputs, suffix=suffix) # It is possible that the old avar type don't match the desired one. # When this happen, we'll try at least to save the ctrl instance so the shapes match. if inst and result != inst: result.ctrl = inst.ctrl result.avar_network = inst.avar_network # Ensure the result instance always have the same surface as it's parent. result.surface = self.surface # Apply cls_ctrl override if specified if cls_ctrl: result._CLS_CTRL = cls_ctrl # Apply cls_ctrl_model override if specified if cls_ctrl_model: result._CLS_MODEL_CTRL = cls_ctrl_model # Apply cls_infl_model override if specified if cls_infl_model: result._CLS_MODEL_INFL = cls_infl_model # Apply name override if specified if name: result.name = name else: ref = result.jnt if ref: result.name = ( self.get_nomenclature() + self.rig.nomenclature(ref.stripNamespace().nodeName())).resolve() # Keep a reference to the module parent. # todo: implement a generic mechanism for all modules? result._parent_module = self return result def configure_avar(self, avar): """ This method is called as soon as we access or create an avar. Use it to configure the avar automatically. """ if avar.surface is None and self.surface: avar.surface = self.surface def _need_to_connect_macro_avar(self, avar): """ Macro avars are made to control micro avars. In the first build, it is necessary to create default connection so the rigger got something that work. However with time it is normal than a rigger remove this connection or replace it with other type of connection. This call check if the avar is connected to at least another avar. If True, no connection is needed. """ def _is_obj_avar(obj): return obj.hasAttr('avar_lr') # ugly but it work attr_holder = avar.grp_rig for hist in attr_holder.listHistory(future=False): if isinstance(hist, pymel.nodetypes.Transform) and hist != attr_holder and _is_obj_avar(hist): return False return True # todo: deprecate this class in favor of composition class AvarGrpOnSurface(AvarGrp): """ Highest-level surface-based AvarGrp module. With additional features like: - Horizontal macro avars (avar_l, avar_r) - Vertical macro avars (avar_upp, avar_low) - Global macro avar (avar_all) - Ability to have 'tweak' avars that follow their parent only in translation. Especially useful to have different falloff on translation than on rotation. Here's examples of the type of hierarchy that the rigger can provide: -------------------------------------------------------------------------------------------------------------------- | NAME | AVAR_ALL | AVAR_L | AVAR_R | AVAR_UPP | AVAR_LOW | NOTES -------------------------------------------------------------------------------------------------------------------- ex #1: | jnt_avar_01 | YES | NO | NO | NO | NO | | jnt_avar_02 | YES | NO | NO | NO | NO | | jnt_avar_03 | YES | NO | NO | NO | NO | ex #2: | jnt_root | YES | NO | NO | NO | NO | Affected by avar_all only. | jnt_avar_01 | YES | NO | NO | NO | NO | | jnt_avar_02 | YES | NO | NO | NO | NO | | jnt_avar_upp | YES | NO | NO | YES | NO | Affected by avar_upp because of the 'upp' token. | jnt_avar_low | YES | NO | NO | NO | YES | Affected by avar_low because of the 'low' token. | l_jnt_avar | YES | YES | NO | NO | NO | Affected by avar_l because of the 'l' token. | r_jnt_avar | YES | NO | YES | NO | NO | Affected by avar_r because of the 'r' token. ex #3: | jnt_root | YES | NO | NO | NO | NO | Affected by avar_all only. | jnt_avar_01 | YES | NO | NO | NO | NO | | jnt_avar_01_tweak | NO | NO | NO | NO | NO | Affected by jnt_avar_01 in translation only. """ _CLS_AVAR = rigFaceAvar.AvarFollicle _CLS_AVAR_MACRO = rigFaceAvar.AvarFollicle # Macro avars are always abstract (except the all macro which can potentially drive something) def __init__(self, *args, **kwargs): super(AvarGrpOnSurface, self).__init__(*args, **kwargs) self.surface = None self.create_macro_horizontal = self.CREATE_MACRO_AVAR_HORIZONTAL self.create_macro_vertical = self.CREATE_MACRO_AVAR_VERTICAL self.create_macro_all = self.CREATE_MACRO_AVAR_ALL self.avar_all = None self.avar_l = None self.avar_r = None self.avar_upp = None self.avar_low = None @decorator_uiexpose() def create_surface(self, *args, **kwargs): """ Expose the function in the ui, using the decorator. """ return super(AvarGrpOnSurface, self).create_surface(*args, **kwargs) _CLS_CTRL_LFT = CtrlFaceMacroL _CLS_CTRL_RGT = CtrlFaceMacroR _CLS_CTRL_UPP = CtrlFaceUpp _CLS_CTRL_LOW = CtrlFaceLow _CLS_CTRL_ALL = CtrlFaceAll _CLS_MODEL_CTRL_ALL = ModelCtrlMacroAll # We always want a linear avar-influence model for the 'all' macro avar. # For example if eyelids are following a round surface, we still want the 'all' macro avar to be linear. # However we might want to define the range from the shared surface. _CLS_MODEL_INFL_ALL = model_avar_linear.AvarLinearModel SHOW_IN_UI = True UI_DISPLAY_NAME = 'AvarGrp' CREATE_MACRO_AVAR_HORIZONTAL = True CREATE_MACRO_AVAR_VERTICAL = True CREATE_MACRO_AVAR_ALL = True def validate(self): super(AvarGrpOnSurface, self).validate() # Ensure that we support the hyerarchy of the influences. influence_hyearchy_deepness = max(self._get_relative_parent_level_by_influences().keys()) if influence_hyearchy_deepness > 2: raise Exception("Unsupported hierarchy depth! Please revise your inputs hierarchy.") # Ensure that we have a mesh to follow. if not self.get_meshes(): raise Exception("Please provide one reference mesh to follow.") # Ensure that if we are building macro avars, we have reference for all of them. # If some are missing we won't be able to build. if self.create_macro_horizontal: if not self.get_jnt_l_mid(): raise Exception("Cannot find a reference input for the lft horizontal macro avar.") if not self.get_jnt_r_mid(): raise Exception("Cannot find a reference input for the rgt horizontal macro avar.") if self.create_macro_vertical: if not self.get_jnt_upp_mid(): raise Exception("Cannot find a reference input for the upp macro avar.") if not self.get_jnt_low_mid(): raise Exception("Cannot find a reference input for the dwn macro avar.") # # Influence getter functions. # @libPython.memoized_instancemethod def get_jnts_upp(self): """ :return: The upper section influences. """ # TODO: Find a better way fnFilter = lambda jnt: 'upp' in jnt.stripNamespace().nodeName().lower() return filter(fnFilter, self.jnts) @libPython.memoized_instancemethod def get_jnt_upp_mid(self): """ :return: The middle influence of the upper section. """ return get_average_pos_between_nodes(self.get_jnts_upp()) @libPython.memoized_instancemethod def get_jnts_low(self): """ :return: The upper side influences. """ # TODO: Find a better way fnFilter = lambda jnt: 'low' in jnt.stripNamespace().nodeName().lower() return filter(fnFilter, self.jnts) @libPython.memoized_instancemethod def get_jnt_low_mid(self): """ :return: The middle influence of the lower section. """ return get_average_pos_between_nodes(self.get_jnts_low()) @libPython.memoized_instancemethod def get_jnts_l(self): """ :return: All the left side influences. # TODO: Use the nomenclature instead of the position? """ middle = self.get_pos_all_middle() jnt_all = self.get_influence_all() # ignore all influence, it have no side def _filter(jnt): if jnt == jnt_all: return False return jnt.getTranslation(space='world').x >= middle.x return filter(_filter, self.jnts) @libPython.memoized_instancemethod def get_jnts_r(self): """ :return: All the right side influences. # TODO: Use the nomenclature instead of the position? """ middle = self.get_pos_all_middle() jnt_all = self.get_influence_all() def _filter(jnt): if jnt == jnt_all: return False return jnt.getTranslation(space='world').x < middle.x return filter(_filter, self.jnts) @libPython.memoized_instancemethod def get_jnt_l_mid(self): """ :return: The left most influence (highest positive distance in x) """ fn_get_pos_x = lambda x: x.getTranslation(space='world').x return next(iter(reversed(sorted(self.get_jnts_l(), key=fn_get_pos_x))), None) @libPython.memoized_instancemethod def get_jnt_r_mid(self): """ :return: The right most influence (highest negative distance in x) """ fn_get_pos_x = lambda x: x.getTranslation(space='world').x return next(iter(sorted(self.get_jnts_r(), key=fn_get_pos_x)), None) # # Avars getter functions # @libPython.memoized_instancemethod def get_avar_mid(self): return _find_mid_avar(self.avars) @libPython.memoized_instancemethod def get_avars_micro_l(self): """ Resolve all micro avars on the left side of the face that would be affected by a left macro avar. Note that we explicitly ignoring any middle avars since no 'side' macro can affect the 'middle' avars. :return: A list of avar instances. """ middle = self.get_pos_all_middle() avar_corner_upp = self.get_avar_upp_corner() avar_corner_low = self.get_avar_low_corner() def fn_filter(avar): # Ignore any vertical corner avars. if avar_corner_upp and avar is avar_corner_upp: return False if avar_corner_low and avar is avar_corner_low: return False # Ignore right-sided avars. pos = avar.jnt.getTranslation(space='world') if pos.x < middle.x: return False return True return [avar for avar in self.avars if avar and fn_filter(avar)] @libPython.memoized_instancemethod def get_avars_micro_r(self): """ Resolve all micro avars on the right side of the face that would be affected by a right macro avar. Note that we explicitly ignoring any middle avars since no 'side' macro can affect the 'middle' avars. :return: A list of avar instances. """ middle = self.get_pos_all_middle() avar_corner_upp = self.get_avar_upp_corner() avar_corner_low = self.get_avar_low_corner() def fn_filter(avar): # Ignore any vertical corner avars. if avar_corner_upp and avar is avar_corner_upp: return False if avar_corner_low and avar is avar_corner_low: return False # Ignore right-sided avars. pos = avar.jnt.getTranslation(space='world') if pos.x > middle.x: return False return True return [avar for avar in self.avars if avar and fn_filter(avar)] @libPython.memoized_instancemethod def get_avar_l_corner(self): """ :return: The farthest avar in the positive X axis. """ fn_get_avar_pos_x = lambda avar: avar.jnt.getTranslation(space='world').x return next(iter(reversed(sorted(self.get_avars_micro_l(), key=fn_get_avar_pos_x))), None) @libPython.memoized_instancemethod def get_avar_r_corner(self): """ :return: The farthest avar in the negative X axis. """ fn_get_avar_pos_x = lambda avar: avar.jnt.getTranslation(space='world').x return next(iter(sorted(self.get_avars_micro_r(), key=fn_get_avar_pos_x)), None) @libPython.memoized_instancemethod def get_avar_upp_corner(self): """ :return: The middle upp micro avar. """ avars = self.get_avars_micro_upp() middle = self.get_pos_upp_middle() def get_distance(avar): return abs(avar.jnt.getTranslation(space='world').x - middle.x) avars = sorted(avars, key=get_distance) return next(iter(avars), None) @libPython.memoized_instancemethod def get_avar_low_corner(self): """ :return: The middle low micro avar. """ avars = self.get_avars_micro_low() middle = self.get_pos_low_middle() def get_distance(avar): return abs(avar.jnt.getTranslation(space='world').x - middle.x) avars = sorted(avars, key=get_distance) return next(iter(avars), None) @libPython.memoized_instancemethod def get_pos_all_middle(self): # type () -> pymel.datatypes.Vector """ :return: The average position using all the influences. """ return libRigging.get_average_pos_between_vectors(self.jnts) @libPython.memoized_instancemethod def get_pos_upp_middle(self): # type () -> pymel.datatypes.Vector """ :return: The average position using all the upper section influences. """ return libRigging.get_average_pos_between_vectors([avar.jnt for avar in self.get_avars_micro_upp()]) @libPython.memoized_instancemethod def get_pos_low_middle(self): # type () -> pymel.datatypes.Vector """ :return: The average position using all the lower section influences. """ return libRigging.get_average_pos_between_vectors([avar.jnt for avar in self.get_avars_micro_low()]) def _iter_all_avars(self): for avar in super(AvarGrpOnSurface, self)._iter_all_avars(): yield avar if self.create_macro_horizontal: if self.avar_l: yield self.avar_l if self.avar_r: yield self.avar_r if self.create_macro_vertical: if self.avar_upp: yield self.avar_upp if self.avar_low: yield self.avar_low if self.create_macro_all: if self.avar_all: yield self.avar_all def add_avars(self, attr_holder): """ An AvarGrp don't create any avar by default. It is the responsibility of the inherited module to implement it if necessary. """ pass def get_multiplier_u(self): """ Since we are using the same plane for the eyebrows, we want to attenget_multiplier_lruate the relation between the LR avar and the plane V coordinates. In the best case scenario, at LR -1, the V coordinates of the BrowInn are 0.5 both. """ base_u, base_v = self.get_base_uv() return abs(base_u - 0.5) * 2.0 def _get_avars_influences(self): """ If the rigger provided an influence for the 'all' Avar, don't create an Avar for it. We will handle it manually. :return: """ influences = super(AvarGrpOnSurface, self)._get_avars_influences() influence_all = self.get_influence_all() if influence_all and influence_all in influences: influences.remove(influence_all) return influences @libPython.memoized_instancemethod def get_influences_tweak(self): return self._get_relative_parent_level_by_influences().get(2, []) def _create_avars(self): super(AvarGrpOnSurface, self)._create_avars() # todo: for horizontal and vertical avars, is ref really necessary? they are always abstract avars middle = self.get_head_jnt().getTranslation(space='world') # Create horizontal macro avars if self.create_macro_horizontal: # Create avar_l if necessary ref_l = self.get_jnt_l_mid() if not ref_l: self.info("Cannot create macro avar 'L', found no matching influence.") else: # Resolve name nomenclature = self.rig.nomenclature(self.get_module_name()) nomenclature.add_tokens('macro') if self.IS_SIDE_SPECIFIC: side = ref_l.getTranslation(space='world').x > middle.x if side: # left nomenclature.side = nomenclature.SIDE_L nomenclature.add_tokens('out') else: nomenclature.side = nomenclature.SIDE_R nomenclature.add_tokens('inn') else: nomenclature.side = nomenclature.SIDE_L avar_macro_l_name = nomenclature.resolve() # avar_macro_l_name = 'L_{0}'.format(self.get_module_name()) self.avar_l = self._init_avar( self._CLS_AVAR_MACRO, self.avar_l, ref=ref_l, cls_ctrl=self._CLS_CTRL_LFT, name=avar_macro_l_name ) # Create avar_r if necessary ref_r = self.get_jnt_r_mid() if not ref_r: self.info("Cannot create macro avar 'L', found no matching influence.") else: # Resolve name nomenclature = self.rig.nomenclature(self.get_module_name()) nomenclature.add_tokens('macro') if self.IS_SIDE_SPECIFIC: side = ref_r.getTranslation(space='world').x > middle.x if side: # left nomenclature.side = nomenclature.SIDE_L nomenclature.add_tokens('inn') else: nomenclature.side = nomenclature.SIDE_R nomenclature.add_tokens('out') else: nomenclature.side = nomenclature.SIDE_R avar_macro_r_name = nomenclature.resolve() # avar_macro_r_name = 'R_{0}'.format(self.get_module_name()) self.avar_r = self._init_avar( self._CLS_AVAR_MACRO, self.avar_r, ref=ref_r, cls_ctrl=self._CLS_CTRL_RGT, name=avar_macro_r_name ) # Create vertical macro avars if self.create_macro_vertical: # Create avar_upp if necessary ref_upp = self.get_jnt_upp_mid() if not ref_upp: self.info( "Cannot create macro avar '{}', found no matching influence.".format(self.rig.AVAR_NAME_UPP)) else: # Resolve avar name avar_upp_name = self.get_nomenclature().resolve('macro', self.rig.AVAR_NAME_UPP) self.avar_upp = self._init_avar( self._CLS_AVAR_MACRO, self.avar_upp, ref=ref_upp, cls_ctrl=self._CLS_CTRL_UPP, name=avar_upp_name ) # Create avar_low if necessary ref_low = self.get_jnt_low_mid() if not ref_low: self.info( "Cannot create macro avar '{}', found no matching influence.".format(self.rig.AVAR_NAME_LOW)) else: # Resolve avar name avar_low_name = self.get_nomenclature().resolve('macro', self.rig.AVAR_NAME_LOW) self.avar_low = self._init_avar( self._CLS_AVAR_MACRO, self.avar_low, ref=ref_low, cls_ctrl=self._CLS_CTRL_LOW, name=avar_low_name ) # Create all macro avar # Note that the all macro avar can drive an influence or not, both are supported. # This allow the rigger to provided an additional falloff in case the whole section is moved. if self.create_macro_all: avar_all_ref = self.get_influence_all() nomenclature = self.get_nomenclature_anm().copy() nomenclature.add_tokens('macro', self.rig.AVAR_NAME_ALL) avar_all_name = nomenclature.resolve() self.avar_all = self._init_avar( self._CLS_AVAR_MACRO, self.avar_all, ref=avar_all_ref, cls_ctrl=self._CLS_CTRL_UPP, cls_ctrl_model=self._CLS_MODEL_CTRL_ALL, cls_infl_model=self._CLS_MODEL_INFL_ALL, name=avar_all_name ) self.avar_all.name = avar_all_name # The avar_all is special since it CAN drive an influence. old_ref_all = self.avar_all.jnt if old_ref_all != avar_all_ref: self.warning( "Unexpected influence for avar {0}, expected {1}, got {2}. Will update the influence.".format( self.avar_all.name, avar_all_ref, old_ref_all )) self.avar_all.input = [avar_all_ref if inf == old_ref_all else inf for inf in self.avar_all.input] # Hack: Delete all cache since it may have used the old inputs. try: del self.avar_all._cache except AttributeError: pass def _build_avar_macro_horizontal(self, avar_parent, avar_middle, avar_children, cls_ctrl, connect_ud=True, connect_lr=True, connect_fb=True, **kwargs): self._build_avar_macro( cls_ctrl, avar_parent, **kwargs ) def _connect_avar_macro_horizontal(self, avar_parent, avar_children, connect_ud=True, connect_lr=True, connect_fb=True): for child_avar in avar_children: if connect_ud: libRigging.connectAttr_withLinearDrivenKeys(avar_parent.attr_ud, child_avar.attr_ud) if connect_lr: libRigging.connectAttr_withLinearDrivenKeys(avar_parent.attr_lr, child_avar.attr_lr) if connect_fb: libRigging.connectAttr_withLinearDrivenKeys(avar_parent.attr_fb, child_avar.attr_fb) def _build_avar_macro_vertical(self, avar_parent, avar_middle, avar_children, cls_ctrl, **kwargs): self._build_avar_macro( cls_ctrl, avar_parent, **kwargs ) def _connect_avar_macro_vertical(self, avar_parent, avar_children, connect_ud=True, connect_lr=True, connect_fb=True): for child_avar in avar_children: if connect_ud: libRigging.connectAttr_withLinearDrivenKeys(avar_parent.attr_ud, child_avar.attr_ud) if connect_lr: libRigging.connectAttr_withLinearDrivenKeys(avar_parent.attr_lr, child_avar.attr_lr) if connect_fb: libRigging.connectAttr_withLinearDrivenKeys(avar_parent.attr_fb, child_avar.attr_fb) def _build_avar_macro_l(self, **kwargs): # Create left avar if necessary ref = self.get_jnt_l_mid() if self.create_macro_horizontal and ref: self._build_avar_macro_horizontal(self.avar_l, self.get_avar_mid(), self.get_avars_micro_l(), self._CLS_CTRL_LFT, **kwargs) def _connect_avar_macro_l(self, avar, child_avars): self._connect_avar_macro_horizontal(avar, child_avars) def _build_avar_macro_r(self, **kwargs): # Create right avar if necessary ref = self.get_jnt_r_mid() if self.create_macro_horizontal and ref: self._build_avar_macro_horizontal(self.avar_r, self.get_avar_mid(), self.get_avars_micro_r(), self._CLS_CTRL_RGT, **kwargs) def _connect_avar_macro_r(self, avar, child_avars): self._connect_avar_macro_horizontal(avar, child_avars) def _build_avar_macro_upp(self, **kwargs): # Create upp avar if necessary ref = self.get_jnt_upp_mid() if self.create_macro_vertical and ref: self._build_avar_macro_vertical(self.avar_upp, self.get_avar_mid(), self.get_avars_micro_upp(), self._CLS_CTRL_UPP, **kwargs) def _connect_avar_macro_upp(self, avar, child_avar): self._connect_avar_macro_vertical(avar, child_avar) def _build_avar_macro_low(self, **kwargs): # Create low avar if necessary ref = self.get_jnt_low_mid() if self.create_macro_vertical and ref: self._build_avar_macro_vertical(self.avar_low, self.get_avar_mid(), self.get_avars_micro_low(), self._CLS_CTRL_LOW, **kwargs) def _connect_avar_macro_low(self, avar, child_avars): self._connect_avar_macro_vertical(avar, child_avars) def _connect_avar_macro_all(self, connect_ud=True, connect_lr=True, connect_fb=True): """ Connect the avar_all to their micro equivalent. The avar_all is special as it support rotation and scale like if the micro avars were parented to it. :param connect_ud: If True, will connect the avar_ud. :param connect_lr: If True, will connect the avar_lr :param connect_fb: If True, will connect the avar_fb. :return: """ influence_all = self.get_influence_all() def _can_connect_avar_scale(avar): """ Note that we don't connect the scale on the all_influence. Since the all_influence contain an additional falloff for (ie) when we move the mouth, it generally give better results if it is not scaled. """ if influence_all and avar.jnt == influence_all: return False return True for avar_child in self.avars: # Hack: Tweak avars are affected by their parent avar which is already affected by the all influence. if self._is_tweak_avar(avar_child): continue # # Connect macro_all ctrl to each avar_child. # # Since the movement is 'absolute', we'll only do a simple transform at the beginning of the stack. # # Using the rotate/scalePivot functionality, we are able to save some nodes. # attr_get_pivot_tm = libRigging.create_utility_node( # 'multMatrix', # matrixIn=( # self.avar_all._stack.node.worldMatrix, # avar_child._grp_offset.worldInverseMatrix # ) # ).matrixSum # # layer_parent = avar_child._stack.prepend_layer(name='globalInfluence') # layer_parent.t.set(0, 0, 0) # Hack: why? # # attr_get_all_stack_tm = libRigging.create_utility_node( # 'multMatrix', # matrixIn=( # self.avar_all._stack.node.worldMatrix, # self.avar_all._grp_offset.inverseMatrix # ) # ).matrixSum # # attr_global_tm = libRigging.create_utility_node( # 'multMatrix', # matrixIn=( # avar_child._grp_offset.matrix, # self.avar_all._grp_offset.inverseMatrix, # attr_get_all_stack_tm, # self.avar_all._grp_offset.matrix, # avar_child._grp_offset.inverseMatrix # ) # ).matrixSum # # util_decompose_global_tm = libRigging.create_utility_node( # 'decomposeMatrix', # inputMatrix=attr_global_tm # ) # # pymel.connectAttr(util_decompose_global_tm.outputTranslateX, layer_parent.tx) # pymel.connectAttr(util_decompose_global_tm.outputTranslateY, layer_parent.ty) # pymel.connectAttr(util_decompose_global_tm.outputTranslateZ, layer_parent.tz) # pymel.connectAttr(util_decompose_global_tm.outputRotateX, layer_parent.rx) # pymel.connectAttr(util_decompose_global_tm.outputRotateY, layer_parent.ry) # pymel.connectAttr(util_decompose_global_tm.outputRotateZ, layer_parent.rz) # pymel.connectAttr(util_decompose_global_tm.outputScaleX, layer_parent.sx) # pymel.connectAttr(util_decompose_global_tm.outputScaleY, layer_parent.sy) # pymel.connectAttr(util_decompose_global_tm.outputScaleZ, layer_parent.sz) @libPython.memoized_instancemethod def _get_avar_macro_all_influence_tm(self): """ Return the pivot matrix of the influence controller by the 'all' macro avar. :return: A pymel.datatypes.Matrix instance. """ influence_all = self.get_influence_all() if influence_all: pos = influence_all.getTranslation(space='world') elif self.surface: # We'll always want to macro avar to be positionned at the center of the plane. pos = libRigging.get_point_on_surface_from_uv(self.surface, 0.5, 0.5) else: # If we are not controlling a specific influence and no surface exist, take our chance and use the first influence. pos = self.jnt.getTranslation(space='world') jnt_tm = pymel.datatypes.Matrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, pos.x, pos.y, pos.z, 1 ) # By default, we expect all joint from the right side of the face to be mirrored in 'behavior'. # Since we are creating a new transformation matrix that didn't exist before, we'll need to follow the same rules. if pos.x < 0: jnt_tm = pymel.datatypes.Matrix( 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0) * jnt_tm return jnt_tm def _get_avar_macro_all_ctrl_tm(self): """ :return: The default ctrl matrix for the avar_all ctrl. """ # todo: move this logic in the model tm = self._get_avar_macro_all_influence_tm() pos = tm.translate dir = pymel.datatypes.Point(0, 0, 1) raycast_result = self.rig.raycast_farthest(pos, dir) if raycast_result: pos = raycast_result # Ensure that the ctrl is affar from the head. # Resolve maximum ctrl size from head joint offset_z = 0 head_jnt = self.get_head_jnt() try: head_length = self.rig.get_head_length(head_jnt) except Exception, e: head_length = None self.warning(str(e)) if head_length: offset_z = head_length * 0.05 if pos.x >= 0: jnt_tm = pymel.datatypes.Matrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, pos.x, pos.y, pos.z + offset_z, 1 ) else: jnt_tm = pymel.datatypes.Matrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, pos.x, pos.y, pos.z + offset_z, 1 ) jnt_tm = pymel.datatypes.Matrix( 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0) * jnt_tm return jnt_tm def _build_avar_macro_all(self, connect_ud=True, connect_lr=True, connect_fb=True, constraint=False): # Create all avar if necessary # Note that the use can provide an influence. # If no influence was found, we'll create an 'abstract' avar that doesn't move anything. if self.create_macro_all: # We'll always want to macro avar to be positionned at the center of the plane. jnt_tm = self._get_avar_macro_all_influence_tm() constraint = True if self.get_influence_all() else False self._build_avar_macro(self._CLS_CTRL_ALL, self.avar_all, jnt_tm=jnt_tm, constraint=constraint) # self._connect_avar_macro_all(connect_ud=connect_ud, connect_lr=connect_lr, connect_fb=connect_fb) def _build_avars(self, **kwargs): # TODO: Some calls might need to be move super(AvarGrpOnSurface, self)._build_avars(**kwargs) self._build_avar_macro_l() self._build_avar_macro_r() self._build_avar_macro_upp() self._build_avar_macro_low() self._build_avar_macro_all() self._patch_avars() def _patch_avars(self): """ After all the avars are created, we might want to add custom logic for them :return: """ # For each avars with an avar logic, add the 'all' macro avar contribution before. # If there's no 'all' macro avar, skip this step. if self.create_macro_all: for avar in self._iter_all_avars(): if avar == self.avar_all: continue # If we are dealing with a 'tweak' avar, it already inherit it's parent transform. if self._is_tweak_avar(avar): continue if avar.model_infl: self._add_macro_all_avar_contribution(avar) def _add_macro_all_avar_contribution(self, avar): attr_avar_all_stack_result_tm = self.avar_all.model_infl._attr_out_tm # attr_avar_all_offset_tm = self.avar_all._grp_offset.matrix # attr_avar_all_offset_tm_inv = self.avar_all._grp_offset.inverseMatrix attr_avar_all_offset_tm = self.avar_all._stack_post.worldMatrix attr_avar_all_offset_tm_inv = self.avar_all._stack_post.worldInverseMatrix new_layer = avar._stack_post.append_layer(name='macroAvarAll') attr_tm = libRigging.create_utility_node( 'multMatrix', matrixIn=( avar.grp_offset.matrix, # enter local space, note that this is a hack, our parent contain the local space already... attr_avar_all_offset_tm_inv, # enter avar_all space attr_avar_all_stack_result_tm, # apply avar_all contribution attr_avar_all_offset_tm, # exit avar_all space avar.grp_offset.inverseMatrix, # exit local space (return to avar space) ) ).matrixSum util_decompose_tm = libRigging.create_utility_node( 'decomposeMatrix', inputMatrix=attr_tm, ) pymel.connectAttr(util_decompose_tm.outputTranslate, new_layer.translate) pymel.connectAttr(util_decompose_tm.outputRotate, new_layer.rotate) pymel.connectAttr(util_decompose_tm.outputScale, new_layer.scale) # u = libRigging.create_utility_node( # 'multMatrix', # matrixIn=( # attr_avar_all_offset_tm, # avar._grp_offset.inverseMatrix # ) # ).matrixSum # u2 = libRigging.create_utility_node( # 'decomposeMatrix', # inputMatrix=u # ) # pymel.connectAttr(u2.outputTranslate, new_layer.rotatePivot) # pymel.connectAttr(u2.outputTranslate, new_layer.scalePivot) def _create_avar_macro_all_ctrls(self, parent_pos=None, parent_rot=None, ctrl_tm=None, **kwargs): # Note: Since the avar_all might not have any influence, we resolve the ctrl_tm outside of the model. # todo: resolve ctrl_tm inside of the model? ctrl_tm = self._get_avar_macro_all_ctrl_tm() parent_pos = self.avar_all._grp_output # parent_rot=self.avar_all._grp_output parent_rot = None self.avar_all.create_ctrl( self, ctrl_tm=ctrl_tm, follow_mesh=False, parent_pos=parent_pos, parent_rot=parent_rot, **kwargs ) def _create_avar_macro_l_ctrls(self, **kwargs): self.avar_l.create_ctrl(self, **kwargs) def _create_avar_macro_r_ctrls(self, **kwargs): self.avar_r.create_ctrl(self, **kwargs) def _create_avar_macro_upp_ctrls(self, **kwargs): self.avar_upp.create_ctrl(self, **kwargs) def create_avar_macro_low_ctrls(self, **kwargs): self.avar_low.create_ctrl(self, **kwargs) def _create_avars_ctrls(self, parent_rot=None, parent_scl=None, **kwargs): parent_rot = self.get_head_jnt() parent_scl = None # Since micro avars ctrls can be constraint to macro avars ctrls, we create the macro first. if self.create_macro_all: self._create_avar_macro_all_ctrls( parent_rot=parent_rot, parent_scl=parent_scl, **kwargs ) self._connect_avar_macro_all() # parent_rot = self.avar_all.model_ctrl._stack.get_stack_end() parent_rot = self.avar_all._grp_output parent_scl = self.avar_all.ctrl unconnected_micro_avars = set(avar for avar in self.avars if self._need_to_connect_macro_avar(avar)) if self.create_macro_horizontal: if self.avar_l: self._create_avar_macro_l_ctrls( parent_rot=parent_rot, parent_scl=parent_scl, **kwargs ) child_avar_l = set(self.get_avars_micro_l()) & unconnected_micro_avars if child_avar_l: self._connect_avar_macro_l(self.avar_l, child_avar_l) if self.avar_r: self._create_avar_macro_r_ctrls( parent_rot=parent_rot, parent_scl=parent_scl, **kwargs ) child_avar_r = set(self.get_avars_micro_r()) & unconnected_micro_avars self._connect_avar_macro_r(self.avar_r, child_avar_r) if self.create_macro_vertical: if self.avar_upp: self._create_avar_macro_upp_ctrls( parent_rot=parent_rot, parent_scl=parent_scl, **kwargs ) child_avar_upp = set(self.get_avars_micro_upp()) & unconnected_micro_avars self._connect_avar_macro_upp(self.avar_upp, child_avar_upp) if self.avar_low: self.create_avar_macro_low_ctrls( parent_rot=parent_rot, parent_scl=parent_scl, **kwargs ) child_avar_low = set(self.get_avars_micro_low()) & unconnected_micro_avars self._connect_avar_macro_low(self.avar_low, child_avar_low) super(AvarGrpOnSurface, self)._create_avars_ctrls(parent_rot=parent_rot, parent_scl=parent_scl, **kwargs) def unbuild(self): if self.avar_l: self.avar_l.unbuild() if self.avar_r: self.avar_r.unbuild() if self.avar_upp: self.avar_upp.unbuild() if self.avar_low: self.avar_low.unbuild() if self.avar_all: self.avar_all.unbuild() super(AvarGrpOnSurface, self).unbuild() @decorator_uiexpose() def calibrate(self): """ Ensure macro avars are correctly calibrated. This override might not be necessary if the design was better. """ super(AvarGrpOnSurface, self).calibrate() if self.avar_l: self.avar_l.calibrate() if self.avar_r: self.avar_r.calibrate() if self.avar_upp: self.avar_upp.calibrate() if self.avar_low: self.avar_low.calibrate() if self.avar_all: self.avar_all.calibrate() def get_avars_upp(self, macro=True): result = super(AvarGrpOnSurface, self).get_avars_upp() if macro and self.avar_upp: result.append(self.avar_upp) return result def get_avars_low(self, macro=True): result = super(AvarGrpOnSurface, self).get_avars_low() if macro and self.avar_low: result.append(self.avar_low) return result def _get_default_ctrl_size(self, jnts=None, max_ctrl_size=None, epsilon=0.001): if self.CREATE_MACRO_AVAR_VERTICAL: jnts_upp = [avar.jnt for avar in self.get_avars_micro_upp()] default_ctrl_size_upp = super(AvarGrpOnSurface, self)._get_default_ctrl_size(jnts=jnts_upp, max_ctrl_size=max_ctrl_size, epsilon=epsilon) jnts_low = [avar.jnt for avar in self.get_avars_micro_low()] default_ctrl_size_low = super(AvarGrpOnSurface, self)._get_default_ctrl_size(jnts=jnts_low, max_ctrl_size=max_ctrl_size, epsilon=epsilon) return max(default_ctrl_size_upp, default_ctrl_size_low) else: return super(AvarGrpOnSurface, self)._get_default_ctrl_size(jnts=None, max_ctrl_size=None, epsilon=epsilon) def register_plugin(): return AvarGrpOnSurface
{ "content_hash": "4110aa7cfe2983b64921a1115922ec55", "timestamp": "", "source": "github", "line_count": 1807, "max_line_length": 152, "avg_line_length": 40.819590481460985, "alnum_prop": 0.5814590366182671, "repo_name": "SqueezeStudioAnimation/omtk", "id": "5e695c5f937c34672964f4c256e9a919e9ffc3dc", "size": "73761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/omtk/modules/rigFaceAvarGrps.py", "mode": "33261", "license": "mit", "language": [ { "name": "Mathematica", "bytes": "1124321" }, { "name": "Python", "bytes": "1054644" }, { "name": "Shell", "bytes": "143" } ], "symlink_target": "" }
Off the beaten path Las Vegas Circle Tour
{ "content_hash": "e75c7f06be683028d7d154267335928d", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 41, "avg_line_length": 42, "alnum_prop": 0.8095238095238095, "repo_name": "conniepokorny/lasvegastour", "id": "603b5714e5618c9784632a7bb4fbb55080cf94c8", "size": "57", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29764" }, { "name": "HTML", "bytes": "9005" }, { "name": "JavaScript", "bytes": "13978" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Madurai Best Cabs</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/modern-business.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">Start Bootstrap</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="about.html">About</a> </li> <li> <a href="services.html">Services</a> </li> <li> <a href="contact.html">Contact</a> </li> <li> <a href="Vehicles.html"> Vehicles</a> </li> <li> <a href="faq.html">FAQ</a> </li> </ul> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <!-- Page Heading/Breadcrumbs --> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Tata Indica </h1> <ol class="breadcrumb"> <li><a href="index.html">Home</a> </li> <li class="active">Vehicles</li> </ol> </div> </div> <!-- /.row --> <!-- Portfolio Item Row --> <div class="row"> <div class="col-md-8"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img class="img-responsive" src="imgs/banner16.jpg" alt=""> </div> </div> </a> </div> </div> <div class="col-md-4"> <h3>Vehicle Description</h3> <p>Seating Capacity = 4 + 1 (AC) & NON(AC).</p> <h3>Fare Details</h3> <ul> <li>Lorem </li> <li>Dolor t</li> <li>Conseur</li> <li>Adipiscing </li> </ul> </div> </div> <!-- /.row --> <!-- interiors --> <div class="row"> <div class="col-lg-12"> <h3 class="page-header">Interiors</h3> </div> <div class="col-sm-3 col-xs-6"> <a href="#"> <img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt=""> </a> </div> <div class="col-sm-3 col-xs-6"> <a href="#"> <img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt=""> </a> </div> <div class="col-sm-3 col-xs-6"> <a href="#"> <img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt=""> </a> </div> <div class="col-sm-3 col-xs-6"> <a href="#"> <img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt=""> </a> </div> </div> <!-- /.row --> <hr> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <p>Copyright &copy; Your Website 2014</p> </div> </div> </footer> </div> <!-- /.container --> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> </body> </html>
{ "content_hash": "4392d9dabae3f1e28a1074b7001cff88", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 127, "avg_line_length": 31.96276595744681, "alnum_prop": 0.41987019470793807, "repo_name": "maduraibestcabs/maduraibestcabs.github.io", "id": "f5c6cbdc8a0c0a27e50a32d28f172e1ec2160516", "size": "6009", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tata Indica.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "111814" }, { "name": "HTML", "bytes": "106227" }, { "name": "JavaScript", "bytes": "39436" }, { "name": "PHP", "bytes": "932" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>kildall: 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.8.0 / kildall - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> kildall <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-19 02:36:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-19 02:36:57 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/kildall&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Kildall&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: Kildall&quot; &quot;keyword: data flow analysis&quot; &quot;keyword: bytecode verification&quot; &quot;category: Computer Science/Semantics and Compilation/Semantics&quot; &quot;date: 2005-07&quot; ] authors: [ &quot;Solange Coupet-Grimal &lt;Solange.Coupet@cmi.univ-mrs.fr&gt;&quot; &quot;William Delobel &lt;delobel@cmi.univ-mrs.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/kildall/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/kildall.git&quot; synopsis: &quot;Application of the Generic kildall&#39;s Data Flow Analysis Algorithm to a Type and Shape Static Analyses of Bytecode&quot; description: &quot;&quot;&quot; http://www.lif-sud.univ-mrs.fr/Rapports/24-2005.html This Library provides a generic data flow analysis algorithm and a proof of its correctness. This algorithm is then used to perform type and shape analysis at bytecode level on a first order functionnal language.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/kildall/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=b82273b17f19d74039c1af26043de211&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-kildall.8.7.0 coq.8.8.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0). The following dependencies couldn&#39;t be met: - coq-kildall -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.06.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-kildall.8.7.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": "7fcba42c3904257fd6a059a0461d1a3f", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 222, "avg_line_length": 43.04705882352941, "alnum_prop": 0.5552063405301995, "repo_name": "coq-bench/coq-bench.github.io", "id": "48b8d90891e6208cc9fc918abc68a627218fd999", "size": "7343", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.8.0/kildall/8.7.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php use Hubzero\Content\Migration\Base; // No direct access defined('_HZEXEC_') or die(); /** * Migration script to fix character encoding on field (from past schema upgrade) **/ class Migration2016090710350000ComBillboards extends Base { public function up() { if ($this->db->tableHasField('#__billboards_collections', 'name')) { $query = "ALTER TABLE `#__billboards_collections` CHANGE COLUMN `name` `name` varchar(255) DEFAULT NULL;"; $this->db->setQuery($query); $this->db->query(); } } public function down() { } }
{ "content_hash": "5a260754e387ab5285aa1072bc649621", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 109, "avg_line_length": 20.37037037037037, "alnum_prop": 0.6745454545454546, "repo_name": "zweidner/hubzero-cms", "id": "2197d4050049d734f9b02f7b4906a407bfc945e0", "size": "698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/migrations/Migration2016090710350000ComBillboards.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "171251" }, { "name": "AngelScript", "bytes": "1638" }, { "name": "CSS", "bytes": "2725992" }, { "name": "HTML", "bytes": "1103502" }, { "name": "JavaScript", "bytes": "12590362" }, { "name": "PHP", "bytes": "24800288" }, { "name": "Shell", "bytes": "10666" }, { "name": "TSQL", "bytes": "572" } ], "symlink_target": "" }
using System.Diagnostics.CodeAnalysis; namespace System.Globalization { /// <summary> /// Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar. /// That is, /// Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01 /// </summary> /// <remarks> /// Calendar support range: /// Calendar Minimum Maximum /// ========== ========== ========== /// Gregorian 1912/01/01 9999/12/31 /// Taiwan 01/01/01 8088/12/31 /// </remarks> public class TaiwanCalendar : Calendar { // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 private static EraInfo[] s_taiwanEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; private static volatile Calendar s_defaultInstance; private readonly GregorianCalendarHelper _helper; internal static Calendar GetDefaultInstance() { return s_defaultInstance ?? (s_defaultInstance = new TaiwanCalendar()); } private static readonly DateTime s_calendarMinValue = new DateTime(1912, 1, 1); public override DateTime MinSupportedDateTime => s_calendarMinValue; public override DateTime MaxSupportedDateTime => DateTime.MaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; public TaiwanCalendar() { try { new CultureInfo("zh-TW"); } catch (ArgumentException e) { throw new TypeInitializationException(GetType().ToString(), e); } _helper = new GregorianCalendarHelper(this, s_taiwanEraInfo); } internal override CalendarId ID => CalendarId.TAIWAN; public override DateTime AddMonths(DateTime time, int months) { return _helper.AddMonths(time, months); } public override DateTime AddYears(DateTime time, int years) { return _helper.AddYears(time, years); } public override int GetDaysInMonth(int year, int month, int era) { return _helper.GetDaysInMonth(year, month, era); } public override int GetDaysInYear(int year, int era) { return _helper.GetDaysInYear(year, era); } public override int GetDayOfMonth(DateTime time) { return _helper.GetDayOfMonth(time); } public override DayOfWeek GetDayOfWeek(DateTime time) { return _helper.GetDayOfWeek(time); } public override int GetDayOfYear(DateTime time) { return _helper.GetDayOfYear(time); } public override int GetMonthsInYear(int year, int era) { return _helper.GetMonthsInYear(year, era); } public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return _helper.GetWeekOfYear(time, rule, firstDayOfWeek); } public override int GetEra(DateTime time) { return _helper.GetEra(time); } public override int GetMonth(DateTime time) { return _helper.GetMonth(time); } public override int GetYear(DateTime time) { return _helper.GetYear(time); } public override bool IsLeapDay(int year, int month, int day, int era) { return _helper.IsLeapDay(year, month, day, era); } public override bool IsLeapYear(int year, int era) { return _helper.IsLeapYear(year, era); } public override int GetLeapMonth(int year, int era) { return _helper.GetLeapMonth(year, era); } public override bool IsLeapMonth(int year, int month, int era) { return _helper.IsLeapMonth(year, month, era); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era); } public override int[] Eras => _helper.Eras; private const int DefaultTwoDigitYearMax = 99; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > _helper.MaxYear) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear)); } _twoDigitYearMax = value; } } /// <summary> /// For Taiwan calendar, four digit year is not used. /// Therefore, for any two digit number, we just return the original number. /// </summary> public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedPosNum); } if (year > _helper.MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), year, SR.Format(SR.ArgumentOutOfRange_Range, 1, _helper.MaxYear)); } return year; } } }
{ "content_hash": "4eae13f4d2c44ba699b8ff8b5e27d3f3", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 141, "avg_line_length": 30.939698492462313, "alnum_prop": 0.549618320610687, "repo_name": "mmitche/coreclr", "id": "f3414d383a5ef0b153660f2681db76a292660753", "size": "6361", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "956111" }, { "name": "Awk", "bytes": "6916" }, { "name": "Batchfile", "bytes": "168475" }, { "name": "C", "bytes": "5588467" }, { "name": "C#", "bytes": "150477201" }, { "name": "C++", "bytes": "65887021" }, { "name": "CMake", "bytes": "715184" }, { "name": "Groovy", "bytes": "225924" }, { "name": "M4", "bytes": "15214" }, { "name": "Makefile", "bytes": "46117" }, { "name": "Objective-C", "bytes": "16829" }, { "name": "Perl", "bytes": "23640" }, { "name": "PowerShell", "bytes": "54894" }, { "name": "Python", "bytes": "548588" }, { "name": "Roff", "bytes": "656420" }, { "name": "Scala", "bytes": "4102" }, { "name": "Shell", "bytes": "490554" }, { "name": "Smalltalk", "bytes": "635930" }, { "name": "SuperCollider", "bytes": "650" }, { "name": "TeX", "bytes": "126781" }, { "name": "XSLT", "bytes": "1016" }, { "name": "Yacc", "bytes": "157492" } ], "symlink_target": "" }
package com.softsynth.shared.time; /** * @author Phil Burk, (C) 2009 Mobileer Inc */ public class TimeStamp implements Comparable<TimeStamp> { private final double time; public TimeStamp(double time) { this.time = time; } public double getTime() { return time; } /** * @return -1 if (this &lt; t2), 0 if equal, or +1 */ @Override public int compareTo(TimeStamp t2) { if (time < t2.time) return -1; else if (time == t2.time) return 0; else return 1; } /** * Create a new TimeStamp at a relative offset in seconds. * * @param delta * @return earlier or later TimeStamp */ public TimeStamp makeRelative(double delta) { return new TimeStamp(time + delta); } }
{ "content_hash": "72305b1cfdcd66f709cc6e86a5dcd12f", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 62, "avg_line_length": 19.833333333333332, "alnum_prop": 0.5558223289315727, "repo_name": "philburk/jsyn", "id": "6d243ed8c5abcd1e6fd91380b90907630c654172", "size": "1439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/softsynth/shared/time/TimeStamp.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1191" }, { "name": "Java", "bytes": "1011177" }, { "name": "Shell", "bytes": "1928" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ru"> <head> <title>DrawingTableCell (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DrawingTableCell (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><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 class="navBarCell1Rev">Class</li> <li><a href="class-use/DrawingTableCell.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTable.html" title="class in org.apache.poi.xslf.usermodel"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTableRow.html" title="class in org.apache.poi.xslf.usermodel"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/poi/xslf/usermodel/DrawingTableCell.html" target="_top">Frames</a></li> <li><a href="DrawingTableCell.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All 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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.poi.xslf.usermodel</div> <h2 title="Class DrawingTableCell" class="title">Class DrawingTableCell</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.apache.poi.xslf.usermodel.DrawingTableCell</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">DrawingTableCell</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTableCell.html#DrawingTableCell(org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell)">DrawingTableCell</a></strong>(org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell&nbsp;cell)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTextBody.html" title="class in org.apache.poi.xslf.usermodel">DrawingTextBody</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTableCell.html#getTextBody()">getTextBody</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DrawingTableCell(org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DrawingTableCell</h4> <pre>public&nbsp;DrawingTableCell(org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell&nbsp;cell)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getTextBody()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getTextBody</h4> <pre>public&nbsp;<a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTextBody.html" title="class in org.apache.poi.xslf.usermodel">DrawingTextBody</a>&nbsp;getTextBody()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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 class="navBarCell1Rev">Class</li> <li><a href="class-use/DrawingTableCell.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTable.html" title="class in org.apache.poi.xslf.usermodel"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/poi/xslf/usermodel/DrawingTableRow.html" title="class in org.apache.poi.xslf.usermodel"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/poi/xslf/usermodel/DrawingTableCell.html" target="_top">Frames</a></li> <li><a href="DrawingTableCell.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All 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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2014 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
{ "content_hash": "0e520876d5d0d197621b4ed544c15200", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 306, "avg_line_length": 35.065891472868216, "alnum_prop": 0.6359014037802586, "repo_name": "pedro93/ifarmaStudents", "id": "526aee6a28a8fce77241372d7960be509fdbf299", "size": "9047", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "poi-3.10-FINAL/docs/apidocs/org/apache/poi/xslf/usermodel/DrawingTableCell.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25085" }, { "name": "Java", "bytes": "26983" } ], "symlink_target": "" }
package org.apache.bookkeeper.api.kv; import org.apache.bookkeeper.api.kv.op.CompareOp; import org.apache.bookkeeper.api.kv.op.CompareResult; import org.apache.bookkeeper.api.kv.op.DeleteOp; import org.apache.bookkeeper.api.kv.op.IncrementOp; import org.apache.bookkeeper.api.kv.op.OpFactory; import org.apache.bookkeeper.api.kv.op.PutOp; import org.apache.bookkeeper.api.kv.op.RangeOp; import org.apache.bookkeeper.api.kv.options.Options; /** * A base class for {@link PTable}. */ public interface PTableBase<K, V> extends AutoCloseable { OpFactory<K, V> opFactory(); default CompareOp<K, V> compareCreateRevision(CompareResult result, K key, long revision) { return opFactory().compareCreateRevision(result, key, revision); } default CompareOp<K, V> compareModRevision(CompareResult result, K key, long revision) { return opFactory().compareModRevision(result, key, revision); } default CompareOp<K, V> compareVersion(CompareResult result, K key, long version) { return opFactory().compareVersion(result, key, version); } default CompareOp<K, V> compareValue(CompareResult result, K key, V value) { return opFactory().compareValue(result, key, value); } default PutOp<K, V> newPut(K key, V value) { return opFactory().newPut(key, value, Options.blindPut()); } default DeleteOp<K, V> newDelete(K key) { return opFactory().newDelete(key, Options.delete()); } default IncrementOp<K, V> newIncrement(K key, long amount) { return opFactory().newIncrement(key, amount, Options.blindIncrement()); } default IncrementOp<K, V> newIncrementAndGet(K key, long amount) { return opFactory().newIncrement(key, amount, Options.incrementAndGet()); } default RangeOp<K, V> newGet(K key) { return opFactory().newRange( key, Options.get()); } @Override void close(); }
{ "content_hash": "4cb90ba2d844be20bbff8f90bda84bfc", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 95, "avg_line_length": 31.950819672131146, "alnum_prop": 0.6906105695228322, "repo_name": "apache/bookkeeper", "id": "1fa79db7c8cb91066fbdcf0cd65f79f6081ce5ee", "size": "2754", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "stream/api/src/main/java/org/apache/bookkeeper/api/kv/PTableBase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11886" }, { "name": "C++", "bytes": "17844" }, { "name": "Dockerfile", "bytes": "11186" }, { "name": "Groovy", "bytes": "48262" }, { "name": "Java", "bytes": "15908174" }, { "name": "JavaScript", "bytes": "12042" }, { "name": "Makefile", "bytes": "6544" }, { "name": "Python", "bytes": "215336" }, { "name": "Roff", "bytes": "39396" }, { "name": "SCSS", "bytes": "1345" }, { "name": "Shell", "bytes": "183376" }, { "name": "Thrift", "bytes": "1473" } ], "symlink_target": "" }
FROM balenalib/iot-gate-imx8-fedora:35-build ENV GO_VERSION 1.16.14 RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "5e59056e36704acb25809bcdb27191f27593cb7aba4d716b523008135a1e764a go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/613d8e9ca8540f29a43fddf658db56a8d826fffe/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 35 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.14 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "550036bcc17eb5474d921cb882de7bd2", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 672, "avg_line_length": 63.774193548387096, "alnum_prop": 0.7243297926150734, "repo_name": "resin-io-library/base-images", "id": "e712cc321e19c26b21fbe3170cdb9d2eaf4903cd", "size": "1998", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/golang/iot-gate-imx8/fedora/35/1.16.14/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
package io.mycat.ep.v1.order; public final class OrderCartInfoHolder extends Ice.Holder<OrderCartInfo> { public OrderCartInfoHolder() { } public OrderCartInfoHolder(OrderCartInfo value) { super(value); } }
{ "content_hash": "2cf971ebbabaa78c9017211e5121f35f", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 72, "avg_line_length": 16.533333333333335, "alnum_prop": 0.6653225806451613, "repo_name": "MyCATApache/Mycat-openEP", "id": "85f8791b0448abbb9ac34deeee8d0e43b72beb90", "size": "739", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mycat-ep-server2/mycat-ep-order/src/main/java/io/mycat/ep/v1/order/OrderCartInfoHolder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "26" }, { "name": "Java", "bytes": "1121591" }, { "name": "Nginx", "bytes": "1968" }, { "name": "PHP", "bytes": "12704" }, { "name": "Shell", "bytes": "21747" } ], "symlink_target": "" }
package com.hyh.video.base; import android.app.Application; /** * Created by Eric_He on 2019/7/14. */ public class AppContext extends Application { @Override public void onCreate() { super.onCreate(); /*IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Intent intent1 = new Intent(getApplicationContext(), VideoActivity.class); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent1); } }, intentFilter);*/ } }
{ "content_hash": "451540b89eb24678f256847e3f78267e", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 90, "avg_line_length": 28.833333333333332, "alnum_prop": 0.6257225433526011, "repo_name": "EricHyh/FileDownloader", "id": "77d6d8b0811e0c7d253b0cb40adc37c0238e758b", "size": "692", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VideoSample/src/main/java/com/hyh/video/base/AppContext.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "11700" }, { "name": "Java", "bytes": "1576112" } ], "symlink_target": "" }